From cbed2868bae274d76c0763526d9358ccbe120dcb Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 7 Oct 2021 14:22:38 +0200 Subject: [PATCH 01/53] German translation --- .../resources/assets/bclib/lang/de_de.json | 64 +++++++++---------- .../resources/assets/bclib/lang/en_us.json | 4 +- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/main/resources/assets/bclib/lang/de_de.json b/src/main/resources/assets/bclib/lang/de_de.json index 3a291a8f..c9b2518e 100644 --- a/src/main/resources/assets/bclib/lang/de_de.json +++ b/src/main/resources/assets/bclib/lang/de_de.json @@ -5,43 +5,43 @@ "bclib.datafixer.backupWarning.backup": "Backup erstellen bevor die Reperaturen angewendet werden", "bclib.datafixer.backupWarning.nofixes": "Weiter ohne Reperaturen", "bclib.datafixer.backupWarning.fix": "Reperaturen Anwenden", - "title.bclib.bclibmissmatch": "Version Mismatch", - "message.bclib.bclibmissmatch": "The Version of BCLib on the server and this client do not match. This will cause problems when playing.\n\nDo you want to automatically download the BCLib-Version from the server? \n\nBCLib will move the old version into a subdirectory of your Mods-Folder and before installing the new one.", - "title.bclib.syncfiles": "Mismatching Data", - "message.bclib.syncfiles": "Some Content on the Server does not match the versions on the client.\nDo you want to replace the selected content with the data from the server?", - "message.bclib.syncfiles.mods": "Synchronize Mods", - "message.bclib.syncfiles.configs": "Synchronize Configs", - "message.bclib.syncfiles.folders": "Synchronize Folders and Files", - "message.bclib.syncfiles.delete": "Delete unneeded", - "title.bclib.confirmrestart": "Restart Required", - "message.bclib.confirmrestart": "The requested content was synchronized. You need to restart Minecraft now.", + "title.bclib.bclibmissmatch": "Versionsunterschied", + "message.bclib.bclibmissmatch": "Die Version von BCLib auf dem Server und dem Client sind unterschiedlich. Dies kann Probleme verursachen.\n\nSoll die passende Version von BCLib vom Server auf diese Maschine kopiert werden? \n\nDazu wird die aktuell installierte Version von BCLib im Mods-Verzeichnis in einen Unterordner verschoben und die Version vom Server installiert.", + "title.bclib.syncfiles": "Inkonsistente Daten", + "message.bclib.syncfiles": "Einige Daten (Konfigurationen, Mods, ...) sind unterschiedlich.\nSollen die unten ausgewählten Inhalte vom Server auf diese Maschine kopieren?", + "message.bclib.syncfiles.mods": "Mods synchronisieren", + "message.bclib.syncfiles.configs": "Einstellungen synchronisieren", + "message.bclib.syncfiles.folders": "Dateien und Ordner synchronisieren", + "message.bclib.syncfiles.delete": "Unnötige löschen", + "title.bclib.confirmrestart": "Neustart erforderlich", + "message.bclib.confirmrestart": "Die angeforderten Inhalte wurden erfolgreich übertragen. Minecraft muss nun neu gestartet werden.", "title.link.bclib.discord": "Discord", - "title.bclib.modmenu.main": "BCLib Settings", - "title.bclib.progress": "Progress", - "title.bclib.filesync.progress": "File Transfer", - "message.bclib.filesync.progress": "Syncing File-Content with Server", + "title.bclib.modmenu.main": "BCLib Einstellungen", + "title.bclib.progress": "Fortschritt", + "title.bclib.filesync.progress": "Datenübertragung", + "message.bclib.filesync.progress": "Snychronisiere Dateien und Verzeichnise vom Server", "message.bclib.filesync.progress.stage.empty": "", - "title.config.bclib.client.auto_sync.enabled": "Enable Auto-Sync", - "title.config.bclib.client.auto_sync.acceptConfigs": "Accept incoming Confog Files", - "title.config.bclib.client.auto_sync.acceptFiles": "Accept incoming Files", - "title.config.bclib.client.auto_sync.acceptMods": "Accept incoming Mods", - "title.config.bclib.client.auto_sync.displayModInfo": "Display warning when Serverside Mods differ from Client", - "title.config.bclib.client.auto_sync.debugHashes": "Print Auto-Sync Debug-Hashes to Log", + "title.config.bclib.client.auto_sync.enabled": "Auto-Sync Aktivieren", + "title.config.bclib.client.auto_sync.acceptConfigs": "Konfiguration von Server annehmen", + "title.config.bclib.client.auto_sync.acceptFiles": "Dateien von Server annehmen", + "title.config.bclib.client.auto_sync.acceptMods": "Mods von Server annehmen", + "title.config.bclib.client.auto_sync.displayModInfo": "Warnung anzeigen wen Mods auf Server/Client unterschiedlich", + "title.config.bclib.client.auto_sync.debugHashes": "Erweiterete Logausgabe für Auto-Sync", "title.bclib.syncfiles.modInfo": "Mod Info", "title.bclib.syncfiles.modlist": "Mod Information", - "message.bclib.syncfiles.modlist": "The following shows the state of your installed installed Mods.\n\nAll Mods that do not exist locally, or have a different version will on the Server will be synchronized.", - "title.bclib.modmissmatch": "Mod Version Conflict", - "message.bclib.modmissmatch": "Some Mods on this client do not match the version of Mods on the Server.\n\nMismatching Mods can result in odd game behavior or crashes. Please make sue that you use the same mods as the server.", + "message.bclib.syncfiles.modlist": "Im Folgenden wird der Status deiner installierten Mods angezeigt.\n\nAlle Mods, die lokal nicht vorhanden sind oder eine andere Version auf dem Server haben, werden synchronisiert.", + "title.bclib.modmissmatch": "Mod-Konflikt", + "message.bclib.modmissmatch": "Einige Mods auf diesem Rechner stimmen nicht mit der Version auf dem Server überein.\n\nNicht übereinstimmende Mods können zu merkwürdigem Spielverhalten oder Abstürzen führen. Bitte stellen Sie sicher, dass Sie die gleichen Mods wie auf dem Server verwenden.", - "message.bclib.datafixer.progress.waitbackup": "Waiting for Backup to finish. This may take a while!", - "message.bclib.datafixer.progress.reading": "Reading Data", - "message.bclib.datafixer.progress.players": "Fixing Players", - "message.bclib.datafixer.progress.level": "Applying Patches to level.dat", - "message.bclib.datafixer.progress.worlddata": "Patching Custom World-Data", - "message.bclib.datafixer.progress.regions": "Repairing all Regions", - "message.bclib.datafixer.progress.saving": "Saving Patch State", - "title.bclib.datafixer.progress": "Fixing World", - "message.bclib.datafixer.progress": "Applying all Patches to your World." + "message.bclib.datafixer.progress.waitbackup": "Ich warte auf das Ende der Sicherung. Dies kann eine Weile dauern!", + "message.bclib.datafixer.progress.reading": "Lese Daten", + "message.bclib.datafixer.progress.players": "Repariere Spieler", + "message.bclib.datafixer.progress.level": "Patches auf level.dat anwenden", + "message.bclib.datafixer.progress.worlddata": "Benutzerdefinierte Weltdaten patchen", + "message.bclib.datafixer.progress.regions": "Alle Regionen reparieren", + "message.bclib.datafixer.progress.saving": "Patch-Status speichern", + "title.bclib.datafixer.progress": "Welt in Ordnung bringen", + "message.bclib.datafixer.progress": "Anwenden aller Änderungen" } \ 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 120e0a5c..3ef32c1e 100644 --- a/src/main/resources/assets/bclib/lang/en_us.json +++ b/src/main/resources/assets/bclib/lang/en_us.json @@ -23,7 +23,7 @@ "message.bclib.filesync.progress.stage.empty": "", "title.config.bclib.client.auto_sync.enabled": "Enable Auto-Sync", - "title.config.bclib.client.auto_sync.acceptConfigs": "Accept incoming Confog Files", + "title.config.bclib.client.auto_sync.acceptConfigs": "Accept incoming Config Files", "title.config.bclib.client.auto_sync.acceptFiles": "Accept incoming Files", "title.config.bclib.client.auto_sync.acceptMods": "Accept incoming Mods", "title.config.bclib.client.auto_sync.displayModInfo": "Display warning when Serverside Mods differ from Client", @@ -31,7 +31,7 @@ "title.bclib.syncfiles.modInfo": "Mod Info", "title.bclib.syncfiles.modlist": "Mod Information", - "message.bclib.syncfiles.modlist": "The following shows the state of your installed installed Mods.\n\nAll Mods that do not exist locally, or have a different version will on the Server will be synchronized.", + "message.bclib.syncfiles.modlist": "The following shows the state of your installed installed Mods.\n\nAll Mods that do not exist locally, or have a different version on the Server will be synchronized.", "title.bclib.modmissmatch": "Mod Version Conflict", "message.bclib.modmissmatch": "Some Mods on this client do not match the version of Mods on the Server.\n\nMismatching Mods can result in odd game behavior or crashes. Please make sue that you use the same mods as the server.", From 57e2099650487baa28a806e052bb718aba6b2e9e Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 09:28:43 +0200 Subject: [PATCH 02/53] Added `IPNIgnore` for compat with *Inventory Profiles Next* --- src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java diff --git a/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java b/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java new file mode 100644 index 00000000..b01c8a3f --- /dev/null +++ b/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java @@ -0,0 +1,8 @@ +package org.anti_ad.mc.ipn.api; + +import java.lang.annotation.*; + +// Included from "Inventory Profiles Next" (https://github.com/blackd/Inventory-Profiles) +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface IPNIgnore {} \ No newline at end of file From 2674940c91cc68eaa2fbc397887c48dd967e43eb Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 12:26:35 +0200 Subject: [PATCH 03/53] Added AnvilReceipts from BE --- .../ru/bclib/blocks/LeveledAnvilBlock.java | 16 + .../AnvilScreenHandlerExtended.java | 36 ++ .../interfaces/UnknownReceipBookCategory.java | 4 + .../bclib/mixin/client/AnvilScreenMixin.java | 96 +++++ .../bclib/mixin/client/ClientLevelMixin.java | 2 - .../mixin/client/ClientRecipeBookMixin.java | 20 ++ .../client/ClientboundLoginPacketMixin.java | 18 - .../ru/bclib/mixin/common/AnvilMenuMixin.java | 137 ++++++- .../java/ru/bclib/recipes/AnvilRecipe.java | 335 ++++++++++++++++++ src/main/java/ru/bclib/util/ItemUtil.java | 76 ++++ src/main/java/ru/bclib/util/RecipeHelper.java | 25 ++ src/main/resources/bclib.mixins.client.json | 4 +- 12 files changed, 746 insertions(+), 23 deletions(-) create mode 100644 src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java create mode 100644 src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java create mode 100644 src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java create mode 100644 src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java delete mode 100644 src/main/java/ru/bclib/mixin/client/ClientLevelMixin.java create mode 100644 src/main/java/ru/bclib/mixin/client/ClientRecipeBookMixin.java delete mode 100644 src/main/java/ru/bclib/mixin/client/ClientboundLoginPacketMixin.java create mode 100644 src/main/java/ru/bclib/recipes/AnvilRecipe.java create mode 100644 src/main/java/ru/bclib/util/ItemUtil.java create mode 100644 src/main/java/ru/bclib/util/RecipeHelper.java diff --git a/src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java b/src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java new file mode 100644 index 00000000..6d71663a --- /dev/null +++ b/src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java @@ -0,0 +1,16 @@ +package ru.bclib.blocks; + +import net.minecraft.world.level.material.MaterialColor; + +public class LeveledAnvilBlock extends BaseAnvilBlock{ + protected final int level; + + public LeveledAnvilBlock(MaterialColor color, int level) { + super(color); + this.level = level; + } + + public int getCraftingLevel() { + return level; + } +} diff --git a/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java b/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java new file mode 100644 index 00000000..5194c1ef --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java @@ -0,0 +1,36 @@ +package ru.bclib.interfaces; + + +import java.util.List; + +import ru.bclib.recipes.AnvilRecipe; + +public interface AnvilScreenHandlerExtended { + void be_updateCurrentRecipe(AnvilRecipe recipe); + + AnvilRecipe be_getCurrentRecipe(); + + List be_getRecipes(); + + default void be_nextRecipe() { + List recipes = be_getRecipes(); + if (recipes.size() < 2) return; + AnvilRecipe current = be_getCurrentRecipe(); + int i = recipes.indexOf(current) + 1; + if (i >= recipes.size()) { + i = 0; + } + be_updateCurrentRecipe(recipes.get(i)); + } + + default void be_previousRecipe() { + List recipes = be_getRecipes(); + if (recipes.size() < 2) return; + AnvilRecipe current = be_getCurrentRecipe(); + int i = recipes.indexOf(current) - 1; + if (i <= 0) { + i = recipes.size() - 1; + } + be_updateCurrentRecipe(recipes.get(i)); + } +} diff --git a/src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java b/src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java new file mode 100644 index 00000000..e4a9300a --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces; + +public interface UnknownReceipBookCategory { +} diff --git a/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java b/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java new file mode 100644 index 00000000..9baa2237 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java @@ -0,0 +1,96 @@ +package ru.bclib.mixin.client; + +import java.util.List; + +import com.google.common.collect.Lists; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.screens.inventory.AnvilScreen; +import net.minecraft.client.gui.screens.inventory.ItemCombinerScreen; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.AnvilMenu; +import net.minecraft.world.item.ItemStack; +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.CallbackInfo; +import ru.bclib.interfaces.AnvilScreenHandlerExtended; + +@Mixin(AnvilScreen.class) +public class AnvilScreenMixin extends ItemCombinerScreen { + + @Shadow + private EditBox name; + + private final List be_buttons = Lists.newArrayList(); + + public AnvilScreenMixin(AnvilMenu handler, Inventory playerInventory, Component title, ResourceLocation texture) { + super(handler, playerInventory, title, texture); + } + + @Inject(method = "subInit", at = @At("TAIL")) + protected void be_subInit(CallbackInfo info) { + int x = (width - imageWidth) / 2; + int y = (height - imageHeight) / 2; + be_buttons.clear(); + be_buttons.add(new Button(x + 8, y + 45, 15, 20, new TextComponent("<"), b -> be_previousRecipe())); + be_buttons.add(new Button(x + 154, y + 45, 15, 20, new TextComponent(">"), b -> be_nextRecipe())); + } + + @Inject(method = "renderFg", at = @At("TAIL")) + protected void be_renderForeground(PoseStack matrices, int mouseX, int mouseY, float delta, CallbackInfo info) { + be_buttons.forEach(button -> { + button.render(matrices, mouseX, mouseY, delta); + }); + } + + @Inject(method = "slotChanged", at = @At("HEAD"), cancellable = true) + public void be_onSlotUpdate(AbstractContainerMenu handler, int slotId, ItemStack stack, CallbackInfo info) { + AnvilScreenHandlerExtended anvilHandler = (AnvilScreenHandlerExtended) handler; + if (anvilHandler.be_getCurrentRecipe() != null) { + if (anvilHandler.be_getRecipes().size() > 1) { + be_buttons.forEach(button -> button.visible = true); + } + else { + be_buttons.forEach(button -> button.visible = false); + } + name.setValue(""); + info.cancel(); + } + else { + be_buttons.forEach(button -> button.visible = false); + } + } + + private void be_nextRecipe() { + ((AnvilScreenHandlerExtended) menu).be_nextRecipe(); + } + + private void be_previousRecipe() { + ((AnvilScreenHandlerExtended) menu).be_previousRecipe(); + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (minecraft != null) { + for (AbstractWidget elem : be_buttons) { + if (elem.visible && elem.mouseClicked(mouseX, mouseY, button)) { + if (minecraft.gameMode != null) { + int i = be_buttons.indexOf(elem); + minecraft.gameMode.handleInventoryButtonClick(menu.containerId, i); + return true; + } + } + } + } + return super.mouseClicked(mouseX, mouseY, button); + } +} diff --git a/src/main/java/ru/bclib/mixin/client/ClientLevelMixin.java b/src/main/java/ru/bclib/mixin/client/ClientLevelMixin.java deleted file mode 100644 index 26061eda..00000000 --- a/src/main/java/ru/bclib/mixin/client/ClientLevelMixin.java +++ /dev/null @@ -1,2 +0,0 @@ -package ru.bclib.mixin.client;public class ClientLevelMixin { -} diff --git a/src/main/java/ru/bclib/mixin/client/ClientRecipeBookMixin.java b/src/main/java/ru/bclib/mixin/client/ClientRecipeBookMixin.java new file mode 100644 index 00000000..329573e3 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/client/ClientRecipeBookMixin.java @@ -0,0 +1,20 @@ +package ru.bclib.mixin.client; + +import net.minecraft.client.ClientRecipeBook; +import net.minecraft.client.RecipeBookCategories; +import net.minecraft.world.item.crafting.Recipe; +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.CallbackInfoReturnable; +import ru.bclib.interfaces.UnknownReceipBookCategory; + +@Mixin(ClientRecipeBook.class) +public abstract class ClientRecipeBookMixin { + @Inject(method = "getCategory", at = @At("HEAD"), cancellable = true) + private static void be_getGroupForRecipe(Recipe recipe, CallbackInfoReturnable info) { + if (recipe instanceof UnknownReceipBookCategory) { + info.setReturnValue(RecipeBookCategories.UNKNOWN); + } + } +} diff --git a/src/main/java/ru/bclib/mixin/client/ClientboundLoginPacketMixin.java b/src/main/java/ru/bclib/mixin/client/ClientboundLoginPacketMixin.java deleted file mode 100644 index 2bf2f0ed..00000000 --- a/src/main/java/ru/bclib/mixin/client/ClientboundLoginPacketMixin.java +++ /dev/null @@ -1,18 +0,0 @@ -package ru.bclib.mixin.client; - -import net.minecraft.network.protocol.game.ClientGamePacketListener; -import net.minecraft.network.protocol.game.ClientboundLoginPacket; -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; - -@Mixin(ClientboundLoginPacket.class) -public abstract class ClientboundLoginPacketMixin { - @Inject(method = "handle", cancellable = true, at=@At("HEAD")) - public void bclib_handle(ClientGamePacketListener clientGamePacketListener, CallbackInfo ci){ - //cLevel.setBCLibDidSendHello(); -// DataExchangeAPI.sendOnEnter(); -// ci.cancel(); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java index a8391228..85318e78 100644 --- a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java @@ -1,5 +1,11 @@ package ru.bclib.mixin.common; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.jetbrains.annotations.Nullable; + import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -9,18 +15,27 @@ import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.inventory.ItemCombinerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeManager; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; 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.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.blocks.BaseAnvilBlock; +import ru.bclib.blocks.LeveledAnvilBlock; +import ru.bclib.interfaces.AnvilScreenHandlerExtended; +import ru.bclib.recipes.AnvilRecipe; @Mixin(AnvilMenu.class) -public abstract class AnvilMenuMixin extends ItemCombinerMenu { +public abstract class AnvilMenuMixin extends ItemCombinerMenu implements AnvilScreenHandlerExtended { + private List be_recipes = Collections.emptyList(); + private AnvilRecipe be_currentRecipe; + private DataSlot anvilLevel; + @Shadow private int repairItemCountCost; @@ -31,9 +46,63 @@ public abstract class AnvilMenuMixin extends ItemCombinerMenu { public AnvilMenuMixin(@Nullable MenuType menuType, int i, Inventory inventory, ContainerLevelAccess containerLevelAccess) { super(menuType, i, inventory, containerLevelAccess); } + + @Inject(method = "(ILnet/minecraft/world/entity/player/Inventory;Lnet/minecraft/world/inventory/ContainerLevelAccess;)V", at = @At("TAIL")) + public void be_initAnvilLevel(int syncId, Inventory inventory, ContainerLevelAccess context, CallbackInfo info) { + this.anvilLevel = addDataSlot(DataSlot.standalone()); + if (context != ContainerLevelAccess.NULL) { + int level = context.evaluate((world, blockPos) -> { + Block anvilBlock = world.getBlockState(blockPos).getBlock(); + if (anvilBlock instanceof LeveledAnvilBlock) { + return ((LeveledAnvilBlock) anvilBlock).getCraftingLevel(); + } + return 1; + }, 1); + anvilLevel.set(level); + } + else { + anvilLevel.set(1); + } + } + + @Shadow + public abstract void createResult(); + + @Inject(method = "mayPickup", at = @At("HEAD"), cancellable = true) + protected void be_canTakeOutput(Player player, boolean present, CallbackInfoReturnable info) { + if (be_currentRecipe != null) { + info.setReturnValue(be_currentRecipe.checkHammerDurability(inputSlots, player)); + } + } @Inject(method = "onTake", at = @At("HEAD"), cancellable = true) protected void bclib_onTakeAnvilOutput(Player player, ItemStack stack, CallbackInfo info) { + if (be_currentRecipe != null) { + inputSlots.getItem(0).shrink(be_currentRecipe.getInputCount()); + stack = be_currentRecipe.craft(inputSlots, player); + slotsChanged(inputSlots); + access.execute((world, blockPos) -> { + BlockState anvilState = world.getBlockState(blockPos); + BaseAnvilBlock anvil = (BaseAnvilBlock) anvilState.getBlock(); + if (!player.getAbilities().instabuild && anvilState.is(BlockTags.ANVIL) && player.getRandom().nextDouble() < 0.1) { + BlockState damagedState = anvil.damageAnvilUse(anvilState, player.getRandom()); + if (damagedState == null) { + world.removeBlock(blockPos, false); + world.levelEvent(1029, blockPos, 0); + } + else { + world.setBlock(blockPos, damagedState, 2); + world.levelEvent(1030, blockPos, 0); + } + } + else { + world.levelEvent(1030, blockPos, 0); + } + }); + info.cancel(); + return; + } + this.access.execute((level, blockPos) -> { BlockState blockState = level.getBlockState(blockPos); if (blockState.getBlock() instanceof BaseAnvilBlock) { @@ -77,4 +146,68 @@ public abstract class AnvilMenuMixin extends ItemCombinerMenu { } }); } + + @Inject(method = "createResult", at = @At("HEAD"), cancellable = true) + public void be_updateOutput(CallbackInfo info) { + RecipeManager recipeManager = this.player.level.getRecipeManager(); + be_recipes = recipeManager.getRecipesFor(AnvilRecipe.TYPE, inputSlots, player.level); + if (be_recipes.size() > 0) { + int anvilLevel = this.anvilLevel.get(); + be_recipes = be_recipes.stream() + .filter(recipe -> anvilLevel >= recipe.getAnvilLevel()) + .collect(Collectors.toList()); + if (be_recipes.size() > 0) { + if (be_currentRecipe == null || !be_recipes.contains(be_currentRecipe)) { + be_currentRecipe = be_recipes.get(0); + } + be_updateResult(); + info.cancel(); + } + else { + be_currentRecipe = null; + } + } + } + + @Inject(method = "setItemName", at = @At("HEAD"), cancellable = true) + public void be_setNewItemName(String string, CallbackInfo info) { + if (be_currentRecipe != null) { + info.cancel(); + } + } + + @Override + public boolean clickMenuButton(Player player, int id) { + if (id == 0) { + be_previousRecipe(); + return true; + } + else if (id == 1) { + be_nextRecipe(); + return true; + } + return super.clickMenuButton(player, id); + } + + private void be_updateResult() { + if (be_currentRecipe == null) return; + resultSlots.setItem(0, be_currentRecipe.assemble(inputSlots)); + broadcastChanges(); + } + + @Override + public void be_updateCurrentRecipe(AnvilRecipe recipe) { + this.be_currentRecipe = recipe; + be_updateResult(); + } + + @Override + public AnvilRecipe be_getCurrentRecipe() { + return be_currentRecipe; + } + + @Override + public List be_getRecipes() { + return be_recipes; + } } diff --git a/src/main/java/ru/bclib/recipes/AnvilRecipe.java b/src/main/java/ru/bclib/recipes/AnvilRecipe.java new file mode 100644 index 00000000..20e27f65 --- /dev/null +++ b/src/main/java/ru/bclib/recipes/AnvilRecipe.java @@ -0,0 +1,335 @@ +package ru.bclib.recipes; + +import java.util.Objects; + +import com.google.gson.JsonObject; + +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.core.NonNullList; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.TagParser; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.Tag; +import net.minecraft.util.GsonHelper; +import net.minecraft.world.Container; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TieredItem; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.Level; +import ru.bclib.BCLib; +import ru.bclib.api.TagAPI; +import ru.bclib.config.PathConfig; +import ru.bclib.interfaces.UnknownReceipBookCategory; +import ru.bclib.util.ItemUtil; +import ru.bclib.util.RecipeHelper; + +public class AnvilRecipe implements Recipe, UnknownReceipBookCategory { + public final static String GROUP = "smithing"; + public final static RecipeType TYPE = BCLRecipeManager.registerType(BCLib.MOD_ID, GROUP); + public final static Serializer SERIALIZER = BCLRecipeManager.registerSerializer( + BCLib.MOD_ID, + GROUP, + new Serializer() + ); + public final static ResourceLocation ID = BCLib.makeID(GROUP); + + private final ResourceLocation id; + private final Ingredient input; + private final ItemStack output; + private final int damage; + private final int toolLevel; + private final int anvilLevel; + private final int inputCount; + + public AnvilRecipe(ResourceLocation identifier, Ingredient input, ItemStack output, int inputCount, int toolLevel, int anvilLevel, int damage) { + this.id = identifier; + this.input = input; + this.output = output; + this.toolLevel = toolLevel; + this.anvilLevel = anvilLevel; + this.inputCount = inputCount; + this.damage = damage; + } + + public static Builder create(String id) { + return create(BCLib.makeID(id)); + } + + public static Builder create(ResourceLocation id) { + Builder.INSTANCE.id = id; + Builder.INSTANCE.input = null; + Builder.INSTANCE.output = null; + Builder.INSTANCE.inputCount = 1; + Builder.INSTANCE.toolLevel = 1; + Builder.INSTANCE.anvilLevel = 1; + Builder.INSTANCE.damage = 1; + Builder.INSTANCE.alright = true; + Builder.INSTANCE.exist = true; + + return Builder.INSTANCE; + } + + @Override + public RecipeSerializer getSerializer() { + return SERIALIZER; + } + + @Override + public ItemStack getResultItem() { + return this.output; + } + + @Override + public boolean matches(Container craftingInventory, Level world) { + return this.matches(craftingInventory); + } + + @Override + public ItemStack assemble(Container craftingInventory) { + return this.output.copy(); + } + + public ItemStack craft(Container craftingInventory, Player player) { + if (!player.isCreative()) { + if (!checkHammerDurability(craftingInventory, player)) return ItemStack.EMPTY; + ItemStack hammer = craftingInventory.getItem(1); + hammer.hurtAndBreak(this.damage, player, entity -> entity.broadcastBreakEvent((InteractionHand) null)); + } + return this.assemble(craftingInventory); + } + + public boolean checkHammerDurability(Container craftingInventory, Player player) { + if (player.isCreative()) return true; + ItemStack hammer = craftingInventory.getItem(1); + int damage = hammer.getDamageValue() + this.damage; + return damage < hammer.getMaxDamage(); + } + + public boolean matches(Container craftingInventory) { + ItemStack hammer = craftingInventory.getItem(1); + if (hammer.isEmpty() || !TagAPI.ITEM_HAMMERS.contains(hammer.getItem())) { + return false; + } + ItemStack material = craftingInventory.getItem(0); + int materialCount = material.getCount(); + int level = ((TieredItem) hammer.getItem()).getTier().getLevel(); + return this.input.test(craftingInventory.getItem(0)) && materialCount >= this.inputCount && level >= this.toolLevel; + } + + public int getDamage() { + return this.damage; + } + + public int getInputCount() { + return this.inputCount; + } + + public int getAnvilLevel() { + return this.anvilLevel; + } + + @Override + public NonNullList getIngredients() { + NonNullList defaultedList = NonNullList.create(); + defaultedList.add(Ingredient.of(TagAPI.ITEM_HAMMERS.getValues() + .stream() + .filter(hammer -> ((TieredItem) hammer).getTier() + .getLevel() >= toolLevel) + .map(ItemStack::new))); + defaultedList.add(input); + + return defaultedList; + } + + @Override + @Environment(EnvType.CLIENT) + public boolean canCraftInDimensions(int width, int height) { + return true; + } + + @Override + public ResourceLocation getId() { + return this.id; + } + + @Override + public RecipeType getType() { + return TYPE; + } + + @Override + public boolean isSpecial() { + return true; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AnvilRecipe that = (AnvilRecipe) o; + return damage == that.damage && toolLevel == that.toolLevel && id.equals(that.id) && input.equals(that.input) && output + .equals(that.output); + } + + @Override + public int hashCode() { + return Objects.hash(id, input, output, damage, toolLevel); + } + + @Override + public String toString() { + return "AnvilRecipe [" + id + "]"; + } + + public static class Builder { + private final static Builder INSTANCE = new Builder(); + + private ResourceLocation id; + private Ingredient input; + private ItemStack output; + private int inputCount = 1; + private int toolLevel = 1; + private int anvilLevel = 1; + private int damage = 1; + private boolean alright; + private boolean exist; + + private Builder() { } + + public Builder setInput(ItemLike... inputItems) { + this.alright &= RecipeHelper.exists(inputItems); + this.setInput(Ingredient.of(inputItems)); + return this; + } + + public Builder setInput(Tag inputTag) { + this.setInput(Ingredient.of(inputTag)); + return this; + } + + public Builder setInput(Ingredient ingredient) { + this.input = ingredient; + return this; + } + + public Builder setInputCount(int count) { + this.inputCount = count; + return this; + } + + public Builder setOutput(ItemLike output) { + return this.setOutput(output, 1); + } + + public Builder setOutput(ItemLike output, int amount) { + this.alright &= RecipeHelper.exists(output); + this.output = new ItemStack(output, amount); + return this; + } + + public Builder setToolLevel(int level) { + this.toolLevel = level; + return this; + } + + public Builder setAnvilLevel(int level) { + this.anvilLevel = level; + return this; + } + + public Builder setDamage(int damage) { + this.damage = damage; + return this; + } + + public Builder checkConfig(PathConfig config) { + exist |= config.getBoolean("anvil", id.getPath(), true); + return this; + } + + public void build() { + if (exist) { + if (input == null) { + BCLib.LOGGER.warning("Input for Anvil recipe can't be 'null', recipe {} will be ignored!", id); + return; + } + if (output == null) { + BCLib.LOGGER.warning("Output for Anvil recipe can't be 'null', recipe {} will be ignored!", id); + return; + } + if (BCLRecipeManager.getRecipe(TYPE, id) != null) { + BCLib.LOGGER.warning("Can't add Anvil recipe! Id {} already exists!", id); + return; + } + if (!alright) { + BCLib.LOGGER.debug("Can't add Anvil recipe {}! Ingeredient or output not exists.", id); + return; + } + BCLRecipeManager.addRecipe( + TYPE, + new AnvilRecipe(id, input, output, inputCount, toolLevel, anvilLevel, damage) + ); + } + } + } + + public static class Serializer implements RecipeSerializer { + @Override + public AnvilRecipe fromJson(ResourceLocation id, JsonObject json) { + Ingredient input = Ingredient.fromJson(json.get("input")); + JsonObject result = GsonHelper.getAsJsonObject(json, "result"); + ItemStack output = ItemUtil.fromJsonRecipe(result); + if (output == null) { + throw new IllegalStateException("Output item does not exists!"); + } + if (result.has("nbt")) { + try { + String nbtData = GsonHelper.getAsString(result, "nbt"); + CompoundTag nbt = TagParser.parseTag(nbtData); + output.setTag(nbt); + } + catch (CommandSyntaxException ex) { + BCLib.LOGGER.warning("Error parse nbt data for output.", ex); + } + } + int inputCount = GsonHelper.getAsInt(json, "inputCount", 1); + int toolLevel = GsonHelper.getAsInt(json, "toolLevel", 1); + int anvilLevel = GsonHelper.getAsInt(json, "anvilLevel", 1); + int damage = GsonHelper.getAsInt(json, "damage", 1); + + return new AnvilRecipe(id, input, output, inputCount, toolLevel, anvilLevel, damage); + } + + @Override + public AnvilRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf packetBuffer) { + Ingredient input = Ingredient.fromNetwork(packetBuffer); + ItemStack output = packetBuffer.readItem(); + int inputCount = packetBuffer.readVarInt(); + int toolLevel = packetBuffer.readVarInt(); + int anvilLevel = packetBuffer.readVarInt(); + int damage = packetBuffer.readVarInt(); + + return new AnvilRecipe(id, input, output, inputCount, toolLevel, anvilLevel, damage); + } + + @Override + public void toNetwork(FriendlyByteBuf packetBuffer, AnvilRecipe recipe) { + recipe.input.toNetwork(packetBuffer); + packetBuffer.writeItem(recipe.output); + packetBuffer.writeVarInt(recipe.inputCount); + packetBuffer.writeVarInt(recipe.toolLevel); + packetBuffer.writeVarInt(recipe.anvilLevel); + packetBuffer.writeVarInt(recipe.damage); + } + } +} diff --git a/src/main/java/ru/bclib/util/ItemUtil.java b/src/main/java/ru/bclib/util/ItemUtil.java new file mode 100644 index 00000000..c3535ccd --- /dev/null +++ b/src/main/java/ru/bclib/util/ItemUtil.java @@ -0,0 +1,76 @@ +package ru.bclib.util; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.google.gson.JsonObject; + +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.GsonHelper; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import ru.bclib.BCLib; + +public class ItemUtil { + + public static String toStackString(@NotNull ItemStack stack) { + try { + if (stack == null) { + throw new IllegalStateException("Stack can't be null!"); + } + Item item = stack.getItem(); + return Registry.ITEM.getKey(item) + ":" + stack.getCount(); + } + catch (Exception ex) { + BCLib.LOGGER.error("ItemStack serialization error!", ex); + } + return ""; + } + + @Nullable + public static ItemStack fromStackString(String stackString) { + if (stackString == null || stackString.equals("")) { + return null; + } + try { + String[] parts = stackString.split(":"); + if (parts.length < 2) return null; + if (parts.length == 2) { + ResourceLocation itemId = new ResourceLocation(stackString); + Item item = Registry.ITEM.getOptional(itemId).orElseThrow(() -> { + return new IllegalStateException("Output item " + itemId + " does not exists!"); + }); + return new ItemStack(item); + } + ResourceLocation itemId = new ResourceLocation(parts[0], parts[1]); + Item item = Registry.ITEM.getOptional(itemId).orElseThrow(() -> { + return new IllegalStateException("Output item " + itemId + " does not exists!"); + }); + return new ItemStack(item, Integer.valueOf(parts[2])); + } + catch (Exception ex) { + BCLib.LOGGER.error("ItemStack deserialization error!", ex); + } + return null; + } + + @Nullable + public static ItemStack fromJsonRecipe(JsonObject recipe) { + try { + if (!recipe.has("item")) { + throw new IllegalStateException("Invalid JsonObject. Entry 'item' does not exists!"); + } + ResourceLocation itemId = new ResourceLocation(GsonHelper.getAsString(recipe, "item")); + Item item = Registry.ITEM.getOptional(itemId).orElseThrow(() -> { + return new IllegalStateException("Output item " + itemId + " does not exists!"); + }); + int count = GsonHelper.getAsInt(recipe, "count", 1); + return new ItemStack(item, count); + } + catch (Exception ex) { + BCLib.LOGGER.error("ItemStack deserialization error!", ex); + } + return null; + } +} diff --git a/src/main/java/ru/bclib/util/RecipeHelper.java b/src/main/java/ru/bclib/util/RecipeHelper.java new file mode 100644 index 00000000..82527011 --- /dev/null +++ b/src/main/java/ru/bclib/util/RecipeHelper.java @@ -0,0 +1,25 @@ +package ru.bclib.util; + +import net.minecraft.core.Registry; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; + +public class RecipeHelper { + public static boolean exists(ItemLike item) { + if (item instanceof Block) { + return Registry.BLOCK.getKey((Block) item) != Registry.BLOCK.getDefaultKey(); + } + else { + return Registry.ITEM.getKey(item.asItem()) != Registry.ITEM.getDefaultKey(); + } + } + + public static boolean exists(ItemLike... items) { + for (ItemLike item : items) { + if (!exists(item)) { + return false; + } + } + return true; + } +} diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index 83b869c2..677e5ede 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -11,7 +11,9 @@ "TextureAtlasMixin", "ModelBakeryMixin", "MinecraftMixin", - "GameMixin" + "GameMixin", + "AnvilScreenMixin", + "ClientRecipeBookMixin" ], "injectors": { "defaultRequire": 1 From c0810fd7fff122b26addb14b0b5dd54500b25947 Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 12:40:33 +0200 Subject: [PATCH 04/53] add dev-configuration to build-system --- bclib.gradle | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/bclib.gradle b/bclib.gradle index a65ff5d4..2f8a64ae 100644 --- a/bclib.gradle +++ b/bclib.gradle @@ -171,3 +171,14 @@ publishing { } } } + +configurations { + dev { + canBeResolved = false + canBeConsumed = true + } +} + +artifacts { + dev jar +} From 06df39445c42f2aca5042d6736f2416fc40f2b85 Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 12:44:45 +0200 Subject: [PATCH 05/53] removed unneeded import --- src/main/java/ru/bclib/BCLib.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index f5f6eb3c..d413f140 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -1,5 +1,7 @@ package ru.bclib; +import java.util.List; + import net.fabricmc.api.EnvType; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; @@ -23,8 +25,6 @@ import ru.bclib.world.generator.BCLibNetherBiomeSource; import ru.bclib.world.generator.GeneratorOptions; import ru.bclib.world.surface.BCLSurfaceBuilders; -import java.util.List; - public class BCLib implements ModInitializer { public static final String MOD_ID = "bclib"; public static final Logger LOGGER = new Logger(MOD_ID); From a52b18ba9b7ac4597e920c8d9b76a8a190f966cb Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 19:26:10 +0200 Subject: [PATCH 06/53] `MultiPartBuilder.create` returns an Instance not a globa Object (improves thread safety, fixes paulevsGitch/BetterEnd#316) --- .../ru/bclib/client/models/ModelsHelper.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index a27ab958..267345ea 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -1,6 +1,11 @@ package ru.bclib.client.models; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + import com.google.common.collect.Lists; + import com.mojang.math.Transformation; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -17,10 +22,6 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - @Environment(EnvType.CLIENT) public class ModelsHelper { public static BlockModel fromPattern(Optional pattern) { @@ -88,18 +89,21 @@ public class ModelsHelper { public static class MultiPartBuilder { - private final static MultiPartBuilder BUILDER = new MultiPartBuilder(); + //private final static MultiPartBuilder BUILDER = new MultiPartBuilder(); public static MultiPartBuilder create(StateDefinition stateDefinition) { - BUILDER.stateDefinition = stateDefinition; - BUILDER.modelParts.clear(); - return BUILDER; + // BUILDER.stateDefinition = stateDefinition; + //BUILDER.modelParts.clear(); + // return BUILDER; + return new MultiPartBuilder(stateDefinition); } private final List modelParts = Lists.newArrayList(); private StateDefinition stateDefinition; - private MultiPartBuilder() {} + private MultiPartBuilder(StateDefinition stateDefinition) { + this.stateDefinition = stateDefinition; + } public ModelPart part(ResourceLocation modelId) { ModelPart part = new ModelPart(modelId); From 073b4738401ae7a6343e6c62eeebe75c28fc2950 Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 19:38:31 +0200 Subject: [PATCH 07/53] Preparing common Tags (paulevsGitch/BetterEnd#303) --- src/main/java/ru/bclib/api/TagAPI.java | 26 +- .../WoodenComplexMaterial.java | 722 +++++++++--------- 2 files changed, 387 insertions(+), 361 deletions(-) diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index c3b04638..215c060b 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,7 +1,12 @@ package ru.bclib.api; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + import com.google.common.collect.Maps; import com.google.common.collect.Sets; + import net.fabricmc.fabric.api.tag.TagRegistry; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; @@ -18,10 +23,6 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; - public class TagAPI { private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); @@ -33,9 +34,14 @@ public class TagAPI { public static final Tag.Named BLOCK_END_GROUND = makeBlockTag(BCLib.MOD_ID, "end_ground"); public static final Tag.Named BLOCK_CHEST = makeCommonBlockTag("chest"); + public static final Tag.Named BLOCK_WOODEN_CHEST = makeCommonBlockTag("wooden_chests"); + public static final Tag.Named BLOCK_BARREL = makeCommonBlockTag("barrel"); + public static final Tag.Named BLOCK_WOODEN_BARREL = makeCommonBlockTag("wooden_barrels"); public static final Tag.Named BLOCK_END_STONES = makeCommonBlockTag("end_stones"); public static final Tag.Named BLOCK_NETHER_STONES = makeCommonBlockTag("nether_stones"); - public static final Tag.Named BLOCK_WORKBENCHES = makeCommonBlockTag("workbenches"); + public static final Tag.Named BLOCK_WORKBENCHES = makeCommonBlockTag("workbench"); + public static final Tag.Named BLOCK_SAPLINGS = makeCommonBlockTag("saplings"); + public static final Tag.Named BLOCK_LEAVES = makeCommonBlockTag("leaves"); public static final Tag.Named BLOCK_DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); @@ -46,11 +52,17 @@ public class TagAPI { // Item Tags public static final Tag.Named ITEM_CHEST = makeCommonItemTag("chest"); + public static final Tag.Named ITEM_WOODEN_CHEST = makeCommonItemTag("wooden_chests"); + public static final Tag.Named ITEM_BARREL = makeCommonItemTag("barrel"); + public static final Tag.Named ITEM_WOODEN_BARREL = makeCommonItemTag("wooden_barrels"); public static final Tag.Named ITEM_IRON_INGOTS = makeCommonItemTag("iron_ingots"); public static final Tag.Named ITEM_FURNACES = makeCommonItemTag("furnaces"); - public static final Tag.Named ITEM_WORKBENCHES = makeCommonItemTag("workbenches"); + public static final Tag.Named ITEM_WORKBENCHES = makeCommonItemTag("workbench"); public final static Tag.Named ITEM_HAMMERS = makeCommonItemTag("hammers"); - + public static final Tag.Named ITEM_SAPLINGS = makeCommonItemTag("saplings"); + public static final Tag.Named ITEM_LEAVES = makeCommonItemTag("leaves"); + + /** * Get or create {@link Tag.Named}. * diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index 97a54004..ba329585 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -39,358 +39,372 @@ import ru.bclib.complexmaterials.entry.RecipeEntry; import ru.bclib.recipes.GridRecipe; public class WoodenComplexMaterial extends ComplexMaterial { - public static final ResourceLocation MATERIAL_ID = BCLib.makeID("wooden_material"); - - public static final String BLOCK_CRAFTING_TABLE = "crafting_table"; - public static final String BLOCK_STRIPPED_BARK = "stripped_bark"; - public static final String BLOCK_STRIPPED_LOG = "stripped_log"; - public static final String BLOCK_PRESSURE_PLATE = "plate"; - public static final String BLOCK_BOOKSHELF = "bookshelf"; - public static final String BLOCK_COMPOSTER = "composter"; - public static final String BLOCK_TRAPDOOR = "trapdoor"; - public static final String BLOCK_BARREL = "barrel"; - public static final String BLOCK_BUTTON = "button"; - public static final String BLOCK_LADDER = "ladder"; - public static final String BLOCK_PLANKS = "planks"; - public static final String BLOCK_STAIRS = "stairs"; - public static final String BLOCK_CHEST = "chest"; - public static final String BLOCK_FENCE = "fence"; - public static final String BLOCK_BARK = "bark"; - public static final String BLOCK_DOOR = "door"; - public static final String BLOCK_GATE = "gate"; - public static final String BLOCK_SIGN = "sign"; - public static final String BLOCK_SLAB = "slab"; - public static final String BLOCK_LOG = "log"; - - public static final String TAG_LOGS = "logs"; - - public final MaterialColor planksColor; - public final MaterialColor woodColor; - - public WoodenComplexMaterial(String modID, String baseName, String receipGroupPrefix, MaterialColor woodColor, MaterialColor planksColor) { - super(modID, baseName, receipGroupPrefix); - this.planksColor = planksColor; - this.woodColor = woodColor; - } - - @Override - protected FabricBlockSettings getBlockSettings() { - return FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).materialColor(planksColor); - } - - @Override - public ResourceLocation getMaterialID() { - return MATERIAL_ID; - } - - @Override - protected void initTags() { - addBlockTag(TagAPI.makeBlockTag(getModID(), getBaseName() + "_logs")); - addItemTag(TagAPI.makeItemTag(getModID(), getBaseName() + "_logs")); - } - - @Override - protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - initBase(blockSettings, itemSettings); - initStorage(blockSettings, itemSettings); - initDecorations(blockSettings, itemSettings); - } - - final protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); - Tag.Named tagItemLog = getItemTag(TAG_LOGS); - - addBlockEntry( - new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> { - return new BaseRotatedPillarBlock(settings); - }) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - addBlockEntry( - new BlockEntry(BLOCK_STRIPPED_BARK, (complexMaterial, settings) -> { - return new BaseBarkBlock(settings); - }) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - - addBlockEntry( - new BlockEntry(BLOCK_LOG, (complexMaterial, settings) -> { - return new BaseStripableLogBlock(woodColor, getBlock(BLOCK_STRIPPED_LOG)); - }) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - addBlockEntry( - new BlockEntry(BLOCK_BARK, (complexMaterial, settings) -> { - return new StripableBarkBlock(woodColor, getBlock(BLOCK_STRIPPED_BARK)); - }) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - addBlockEntry(new BlockEntry(BLOCK_PLANKS, (complexMaterial, settings) -> { - return new BaseBlock(settings); - }).setBlockTags(BlockTags.PLANKS).setItemTags(ItemTags.PLANKS)); - - addBlockEntry(new BlockEntry(BLOCK_STAIRS, (complexMaterial, settings) -> { - return new BaseStairsBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS).setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); - addBlockEntry(new BlockEntry(BLOCK_SLAB, (complexMaterial, settings) -> { - return new BaseSlabBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS).setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); - addBlockEntry(new BlockEntry(BLOCK_FENCE, (complexMaterial, settings) -> { - return new BaseFenceBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES).setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); - addBlockEntry(new BlockEntry(BLOCK_GATE, (complexMaterial, settings) -> { - return new BaseGateBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.FENCE_GATES)); - addBlockEntry(new BlockEntry(BLOCK_BUTTON, (complexMaterial, settings) -> { - return new BaseWoodenButtonBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.BUTTONS, BlockTags.WOODEN_BUTTONS).setItemTags(ItemTags.BUTTONS, ItemTags.WOODEN_BUTTONS)); - addBlockEntry(new BlockEntry(BLOCK_PRESSURE_PLATE, (complexMaterial, settings) -> { - return new WoodenPressurePlateBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.PRESSURE_PLATES, BlockTags.WOODEN_PRESSURE_PLATES).setItemTags(ItemTags.WOODEN_PRESSURE_PLATES)); - addBlockEntry(new BlockEntry(BLOCK_TRAPDOOR, (complexMaterial, settings) -> { - return new BaseTrapdoorBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS).setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); - addBlockEntry(new BlockEntry(BLOCK_DOOR, (complexMaterial, settings) -> { - return new BaseDoorBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS).setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); - - - addBlockEntry(new BlockEntry(BLOCK_LADDER, (complexMaterial, settings) -> { - return new BaseLadderBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.CLIMBABLE)); - addBlockEntry(new BlockEntry(BLOCK_SIGN, (complexMaterial, settings) -> { - return new BaseSignBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.SIGNS).setItemTags(ItemTags.SIGNS)); - - - } - - final protected void initStorage(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ - addBlockEntry(new BlockEntry(BLOCK_CHEST, (complexMaterial, settings) -> { - return new BaseChestBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_CHEST).setItemTags(TagAPI.ITEM_CHEST)); - addBlockEntry(new BlockEntry(BLOCK_BARREL, (complexMaterial, settings) -> { - return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); - })); - } - - final protected void initDecorations(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ - addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { - return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); - - addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { - return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); - - addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { - return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); - })); - } - - @Override - protected void initFlammable(FlammableBlockRegistry registry) { - getBlocks().forEach(block -> { - registry.add(block, 5, 20); - }); - - registry.add(getBlock(BLOCK_LOG), 5, 5); - registry.add(getBlock(BLOCK_BARK), 5, 5); - registry.add(getBlock(BLOCK_STRIPPED_LOG), 5, 5); - registry.add(getBlock(BLOCK_STRIPPED_BARK), 5, 5); - } - - @Override - public void initDefaultRecipes() { - Block planks = getBlock(BLOCK_PLANKS); - addRecipeEntry(new RecipeEntry("planks", (material, config, id) -> { - Block log_stripped = getBlock(BLOCK_STRIPPED_LOG); - Block bark_stripped = getBlock(BLOCK_STRIPPED_BARK); - Block log = getBlock(BLOCK_LOG); - Block bark = getBlock(BLOCK_BARK); - GridRecipe.make(id, planks) - .checkConfig(config) - .setOutputCount(4) - .setList("#") - .addMaterial('#', log, bark, log_stripped, bark_stripped) - .setGroup(receipGroupPrefix +"_planks") - .build(); - })); - addRecipeEntry(new RecipeEntry("stairs", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_STAIRS)) - .checkConfig(config) - .setOutputCount(4) - .setShape("# ", "## ", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_planks_stairs") - .build(); - })); - addRecipeEntry(new RecipeEntry("slab", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_SLAB)) - .checkConfig(config) - .setOutputCount(6) - .setShape("###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_planks_slabs") - .build(); - })); - addRecipeEntry(new RecipeEntry("fence", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_FENCE)) - .checkConfig(config) - .setOutputCount(3) - .setShape("#I#", "#I#") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix +"_planks_fences") - .build(); - })); - addRecipeEntry(new RecipeEntry("gate", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_GATE)) - .checkConfig(config) - .setShape("I#I", "I#I") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix +"_planks_gates") - .build(); - })); - addRecipeEntry(new RecipeEntry("button", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_BUTTON)) - .checkConfig(config) - .setList("#") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_planks_buttons") - .build(); - })); - addRecipeEntry(new RecipeEntry("pressure_plate", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_PRESSURE_PLATE)) - .checkConfig(config) - .setShape("##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_planks_plates") - .build(); - })); - addRecipeEntry(new RecipeEntry("trapdoor", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_TRAPDOOR)) - .checkConfig(config) - .setOutputCount(2) - .setShape("###", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_trapdoors") - .build(); - })); - addRecipeEntry(new RecipeEntry("door", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_DOOR)) - .checkConfig(config) - .setOutputCount(3) - .setShape("##", "##", "##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_doors") - .build(); - })); - addRecipeEntry(new RecipeEntry("crafting_table", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_CRAFTING_TABLE)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_tables") - .build(); - })); - addRecipeEntry(new RecipeEntry("ladder", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_LADDER)) - .checkConfig(config) - .setOutputCount(3) - .setShape("I I", "I#I", "I I") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix +"_ladders") - .build(); - })); - addRecipeEntry(new RecipeEntry("sign", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_SIGN)) - .checkConfig(config) - .setOutputCount(3) - .setShape("###", "###", " I ") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix +"_signs") - .build(); - })); - addRecipeEntry(new RecipeEntry("chest", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_CHEST)) - .checkConfig(config) - .setShape("###", "# #", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix +"_chests") - .build(); - })); - addRecipeEntry(new RecipeEntry("barrel", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_BARREL)) - .checkConfig(config) - .setShape("#S#", "# #", "#S#") - .addMaterial('#', planks) - .addMaterial('S', getBlock(BLOCK_SLAB)) - .setGroup(receipGroupPrefix +"_barrels") - .build(); - })); - addRecipeEntry(new RecipeEntry("bookshelf", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_BOOKSHELF)) - .checkConfig(config) - .setShape("###", "PPP", "###") - .addMaterial('#', planks) - .addMaterial('P', Items.BOOK) - .setGroup(receipGroupPrefix +"_bookshelves") - .build(); - })); - addRecipeEntry(new RecipeEntry("bark", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_BARK)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_LOG)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("log", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_LOG)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_BARK)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("stripped_bark", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_STRIPPED_BARK)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_STRIPPED_LOG)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("stripped_log", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_STRIPPED_LOG)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_STRIPPED_BARK)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("composter", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_COMPOSTER)) - .checkConfig(config) - .setShape("# #", "# #", "###") - .addMaterial('#', getBlock(BLOCK_SLAB)) - .build(); - })); - addRecipeEntry(new RecipeEntry("shulker", (material, config, id) -> { - GridRecipe.make(id, Blocks.SHULKER_BOX) - .checkConfig(config) - .setShape("S", "#", "S") - .addMaterial('S', Items.SHULKER_SHELL) - .addMaterial('#', getBlock(BLOCK_CHEST)) - .build(); - })); - } + public static final ResourceLocation MATERIAL_ID = BCLib.makeID("wooden_material"); + + public static final String BLOCK_CRAFTING_TABLE = "crafting_table"; + public static final String BLOCK_STRIPPED_BARK = "stripped_bark"; + public static final String BLOCK_STRIPPED_LOG = "stripped_log"; + public static final String BLOCK_PRESSURE_PLATE = "plate"; + public static final String BLOCK_BOOKSHELF = "bookshelf"; + public static final String BLOCK_COMPOSTER = "composter"; + public static final String BLOCK_TRAPDOOR = "trapdoor"; + public static final String BLOCK_BARREL = "barrel"; + public static final String BLOCK_BUTTON = "button"; + public static final String BLOCK_LADDER = "ladder"; + public static final String BLOCK_PLANKS = "planks"; + public static final String BLOCK_STAIRS = "stairs"; + public static final String BLOCK_CHEST = "chest"; + public static final String BLOCK_FENCE = "fence"; + public static final String BLOCK_BARK = "bark"; + public static final String BLOCK_DOOR = "door"; + public static final String BLOCK_GATE = "gate"; + public static final String BLOCK_SIGN = "sign"; + public static final String BLOCK_SLAB = "slab"; + public static final String BLOCK_LOG = "log"; + + public static final String TAG_LOGS = "logs"; + + public final MaterialColor planksColor; + public final MaterialColor woodColor; + + public WoodenComplexMaterial(String modID, String baseName, String receipGroupPrefix, MaterialColor woodColor, MaterialColor planksColor) { + super(modID, baseName, receipGroupPrefix); + this.planksColor = planksColor; + this.woodColor = woodColor; + } + + @Override + protected FabricBlockSettings getBlockSettings() { + return FabricBlockSettings.copyOf(Blocks.OAK_PLANKS) + .materialColor(planksColor); + } + + @Override + public ResourceLocation getMaterialID() { + return MATERIAL_ID; + } + + @Override + protected void initTags() { + addBlockTag(TagAPI.makeBlockTag(getModID(), getBaseName() + "_logs")); + addItemTag(TagAPI.makeItemTag(getModID(), getBaseName() + "_logs")); + } + + @Override + protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + initBase(blockSettings, itemSettings); + initStorage(blockSettings, itemSettings); + initDecorations(blockSettings, itemSettings); + } + + final protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); + Tag.Named tagItemLog = getItemTag(TAG_LOGS); + + addBlockEntry( + new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> { + return new BaseRotatedPillarBlock(settings); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + addBlockEntry( + new BlockEntry(BLOCK_STRIPPED_BARK, (complexMaterial, settings) -> { + return new BaseBarkBlock(settings); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + + addBlockEntry( + new BlockEntry(BLOCK_LOG, (complexMaterial, settings) -> { + return new BaseStripableLogBlock(woodColor, getBlock(BLOCK_STRIPPED_LOG)); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + addBlockEntry( + new BlockEntry(BLOCK_BARK, (complexMaterial, settings) -> { + return new StripableBarkBlock(woodColor, getBlock(BLOCK_STRIPPED_BARK)); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + addBlockEntry(new BlockEntry(BLOCK_PLANKS, (complexMaterial, settings) -> { + return new BaseBlock(settings); + }).setBlockTags(BlockTags.PLANKS) + .setItemTags(ItemTags.PLANKS)); + + addBlockEntry(new BlockEntry(BLOCK_STAIRS, (complexMaterial, settings) -> { + return new BaseStairsBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS) + .setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); + addBlockEntry(new BlockEntry(BLOCK_SLAB, (complexMaterial, settings) -> { + return new BaseSlabBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS) + .setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); + addBlockEntry(new BlockEntry(BLOCK_FENCE, (complexMaterial, settings) -> { + return new BaseFenceBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES) + .setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); + addBlockEntry(new BlockEntry(BLOCK_GATE, (complexMaterial, settings) -> { + return new BaseGateBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.FENCE_GATES)); + addBlockEntry(new BlockEntry(BLOCK_BUTTON, (complexMaterial, settings) -> { + return new BaseWoodenButtonBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.BUTTONS, BlockTags.WOODEN_BUTTONS) + .setItemTags(ItemTags.BUTTONS, ItemTags.WOODEN_BUTTONS)); + addBlockEntry(new BlockEntry(BLOCK_PRESSURE_PLATE, (complexMaterial, settings) -> { + return new WoodenPressurePlateBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.PRESSURE_PLATES, BlockTags.WOODEN_PRESSURE_PLATES) + .setItemTags(ItemTags.WOODEN_PRESSURE_PLATES)); + addBlockEntry(new BlockEntry(BLOCK_TRAPDOOR, (complexMaterial, settings) -> { + return new BaseTrapdoorBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS) + .setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); + addBlockEntry(new BlockEntry(BLOCK_DOOR, (complexMaterial, settings) -> { + return new BaseDoorBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS) + .setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); + + + addBlockEntry(new BlockEntry(BLOCK_LADDER, (complexMaterial, settings) -> { + return new BaseLadderBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.CLIMBABLE)); + addBlockEntry(new BlockEntry(BLOCK_SIGN, (complexMaterial, settings) -> { + return new BaseSignBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(BlockTags.SIGNS) + .setItemTags(ItemTags.SIGNS)); + + + } + + final protected void initStorage(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + addBlockEntry(new BlockEntry(BLOCK_CHEST, (complexMaterial, settings) -> { + return new BaseChestBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_CHEST, TagAPI.BLOCK_WOODEN_CHEST) + .setItemTags(TagAPI.ITEM_CHEST, TagAPI.ITEM_WOODEN_CHEST)); + + addBlockEntry(new BlockEntry(BLOCK_BARREL, (complexMaterial, settings) -> { + return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_BARREL, TagAPI.BLOCK_WOODEN_BARREL) + .setItemTags(TagAPI.ITEM_BARREL, TagAPI.ITEM_WOODEN_BARREL)); + } + + final protected void initDecorations(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { + return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_WORKBENCHES) + .setItemTags(TagAPI.ITEM_WORKBENCHES)); + + addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { + return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); + + addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { + return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); + })); + } + + @Override + protected void initFlammable(FlammableBlockRegistry registry) { + getBlocks().forEach(block -> { + registry.add(block, 5, 20); + }); + + registry.add(getBlock(BLOCK_LOG), 5, 5); + registry.add(getBlock(BLOCK_BARK), 5, 5); + registry.add(getBlock(BLOCK_STRIPPED_LOG), 5, 5); + registry.add(getBlock(BLOCK_STRIPPED_BARK), 5, 5); + } + + @Override + public void initDefaultRecipes() { + Block planks = getBlock(BLOCK_PLANKS); + addRecipeEntry(new RecipeEntry("planks", (material, config, id) -> { + Block log_stripped = getBlock(BLOCK_STRIPPED_LOG); + Block bark_stripped = getBlock(BLOCK_STRIPPED_BARK); + Block log = getBlock(BLOCK_LOG); + Block bark = getBlock(BLOCK_BARK); + GridRecipe.make(id, planks) + .checkConfig(config) + .setOutputCount(4) + .setList("#") + .addMaterial('#', log, bark, log_stripped, bark_stripped) + .setGroup(receipGroupPrefix + "_planks") + .build(); + })); + addRecipeEntry(new RecipeEntry("stairs", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_STAIRS)) + .checkConfig(config) + .setOutputCount(4) + .setShape("# ", "## ", "###") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_planks_stairs") + .build(); + })); + addRecipeEntry(new RecipeEntry("slab", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_SLAB)) + .checkConfig(config) + .setOutputCount(6) + .setShape("###") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_planks_slabs") + .build(); + })); + addRecipeEntry(new RecipeEntry("fence", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_FENCE)) + .checkConfig(config) + .setOutputCount(3) + .setShape("#I#", "#I#") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup(receipGroupPrefix + "_planks_fences") + .build(); + })); + addRecipeEntry(new RecipeEntry("gate", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_GATE)) + .checkConfig(config) + .setShape("I#I", "I#I") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup(receipGroupPrefix + "_planks_gates") + .build(); + })); + addRecipeEntry(new RecipeEntry("button", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BUTTON)) + .checkConfig(config) + .setList("#") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_planks_buttons") + .build(); + })); + addRecipeEntry(new RecipeEntry("pressure_plate", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_PRESSURE_PLATE)) + .checkConfig(config) + .setShape("##") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_planks_plates") + .build(); + })); + addRecipeEntry(new RecipeEntry("trapdoor", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_TRAPDOOR)) + .checkConfig(config) + .setOutputCount(2) + .setShape("###", "###") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_trapdoors") + .build(); + })); + addRecipeEntry(new RecipeEntry("door", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_DOOR)) + .checkConfig(config) + .setOutputCount(3) + .setShape("##", "##", "##") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_doors") + .build(); + })); + addRecipeEntry(new RecipeEntry("crafting_table", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_CRAFTING_TABLE)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_tables") + .build(); + })); + addRecipeEntry(new RecipeEntry("ladder", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_LADDER)) + .checkConfig(config) + .setOutputCount(3) + .setShape("I I", "I#I", "I I") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup(receipGroupPrefix + "_ladders") + .build(); + })); + addRecipeEntry(new RecipeEntry("sign", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_SIGN)) + .checkConfig(config) + .setOutputCount(3) + .setShape("###", "###", " I ") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup(receipGroupPrefix + "_signs") + .build(); + })); + addRecipeEntry(new RecipeEntry("chest", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_CHEST)) + .checkConfig(config) + .setShape("###", "# #", "###") + .addMaterial('#', planks) + .setGroup(receipGroupPrefix + "_chests") + .build(); + })); + addRecipeEntry(new RecipeEntry("barrel", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BARREL)) + .checkConfig(config) + .setShape("#S#", "# #", "#S#") + .addMaterial('#', planks) + .addMaterial('S', getBlock(BLOCK_SLAB)) + .setGroup(receipGroupPrefix + "_barrels") + .build(); + })); + addRecipeEntry(new RecipeEntry("bookshelf", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BOOKSHELF)) + .checkConfig(config) + .setShape("###", "PPP", "###") + .addMaterial('#', planks) + .addMaterial('P', Items.BOOK) + .setGroup(receipGroupPrefix + "_bookshelves") + .build(); + })); + addRecipeEntry(new RecipeEntry("bark", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BARK)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_LOG)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("log", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_LOG)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_BARK)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("stripped_bark", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_STRIPPED_BARK)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_STRIPPED_LOG)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("stripped_log", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_STRIPPED_LOG)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_STRIPPED_BARK)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("composter", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_COMPOSTER)) + .checkConfig(config) + .setShape("# #", "# #", "###") + .addMaterial('#', getBlock(BLOCK_SLAB)) + .build(); + })); + addRecipeEntry(new RecipeEntry("shulker", (material, config, id) -> { + GridRecipe.make(id, Blocks.SHULKER_BOX) + .checkConfig(config) + .setShape("S", "#", "S") + .addMaterial('S', Items.SHULKER_SHELL) + .addMaterial('#', getBlock(BLOCK_CHEST)) + .build(); + })); + } } \ No newline at end of file From c2452ebcc3c11c8ff5b541056236861a10959ceb Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 19:52:32 +0200 Subject: [PATCH 08/53] Added common leaves Tag (paulevsGitch/BetterEnd#303) --- gradle.properties | 2 +- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 22 ++++++++++++++----- .../ru/bclib/blocks/SimpleLeavesBlock.java | 5 +++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/gradle.properties b/gradle.properties index c44ce364..34e75d23 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ loader_version= 0.11.6 fabric_version = 0.39.1+1.17 # Mod Properties -mod_version = 0.4.1 +mod_version = 0.4.2 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 4c6861bf..3ac139bf 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -1,6 +1,11 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + 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.client.renderer.block.model.BlockModel; @@ -15,17 +20,14 @@ import net.minecraft.world.level.block.state.BlockState; 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.TagAPI; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.util.MHelper; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider { - private final Block sapling; + protected final Block sapling; private static FabricBlockSettings makeLeaves(MaterialColor color) { return FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) @@ -37,25 +39,33 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, .suffocates((state, world, pos) -> false) .blockVision((state, world, pos) -> false); } + + private void init(Block sapling) { + TagAPI.addTags(this, TagAPI.BLOCK_LEAVES); + } public BaseLeavesBlock(Block sapling, MaterialColor color, Consumer customizeProperties) { super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color))); this.sapling = sapling; + init(sapling); } - + public BaseLeavesBlock(Block sapling, MaterialColor color, int light, Consumer customizeProperties) { super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color).luminance(light))); this.sapling = sapling; + init(sapling); } public BaseLeavesBlock(Block sapling, MaterialColor color) { super(makeLeaves(color)); this.sapling = sapling; + init(sapling); } public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { super(makeLeaves(color).lightLevel(light)); this.sapling = sapling; + init(sapling); } @Override diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index 47195b4f..4f4d1128 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -4,6 +4,7 @@ import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; +import ru.bclib.api.TagAPI; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; @@ -17,6 +18,8 @@ public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerPr .isValidSpawn((state, world, pos, type) -> false) .isSuffocating((state, world, pos) -> false) .isViewBlocking((state, world, pos) -> false)); + + TagAPI.addTags(this, TagAPI.BLOCK_LEAVES); } public SimpleLeavesBlock(MaterialColor color, int light) { @@ -29,6 +32,8 @@ public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerPr .isValidSpawn((state, world, pos, type) -> false) .isSuffocating((state, world, pos) -> false) .isViewBlocking((state, world, pos) -> false)); + + TagAPI.addTags(this, TagAPI.BLOCK_LEAVES); } @Override From 3683ebd97aa4b9bf6eadd597595d20cd2e0bf0ac Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 20:09:41 +0200 Subject: [PATCH 09/53] Auto-Add Block/Item Tags for `BaseLeavesBlock` and `FeatureSaplingBlock` (paulevsGitch/BetterEnd#303) --- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 9 --------- .../java/ru/bclib/registry/BlockRegistry.java | 20 ++++++++++++++++++- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 3ac139bf..2ded221e 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -20,7 +20,6 @@ import net.minecraft.world.level.block.state.BlockState; 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.TagAPI; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.RenderLayerProvider; @@ -40,32 +39,24 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, .blockVision((state, world, pos) -> false); } - private void init(Block sapling) { - TagAPI.addTags(this, TagAPI.BLOCK_LEAVES); - } - public BaseLeavesBlock(Block sapling, MaterialColor color, Consumer customizeProperties) { super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color))); this.sapling = sapling; - init(sapling); } public BaseLeavesBlock(Block sapling, MaterialColor color, int light, Consumer customizeProperties) { super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color).luminance(light))); this.sapling = sapling; - init(sapling); } public BaseLeavesBlock(Block sapling, MaterialColor color) { super(makeLeaves(color)); this.sapling = sapling; - init(sapling); } public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { super(makeLeaves(color).lightLevel(light)); this.sapling = sapling; - init(sapling); } @Override diff --git a/src/main/java/ru/bclib/registry/BlockRegistry.java b/src/main/java/ru/bclib/registry/BlockRegistry.java index 80ee433b..ce9d941e 100644 --- a/src/main/java/ru/bclib/registry/BlockRegistry.java +++ b/src/main/java/ru/bclib/registry/BlockRegistry.java @@ -7,6 +7,9 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; +import ru.bclib.api.TagAPI; +import ru.bclib.blocks.BaseLeavesBlock; +import ru.bclib.blocks.FeatureSaplingBlock; import ru.bclib.interfaces.CustomItemProvider; public abstract class BlockRegistry extends BaseRegistry { @@ -29,7 +32,22 @@ public abstract class BlockRegistry extends BaseRegistry { .getBurnChance() == 0) { FlammableBlockRegistry.getDefaultInstance().add(block, 5, 5); } - return Registry.register(Registry.BLOCK, id, block); + + block = Registry.register(Registry.BLOCK, id, block); + + if (block instanceof BaseLeavesBlock){ + TagAPI.addTags(block, TagAPI.BLOCK_LEAVES); + if (item != null){ + TagAPI.addTags(item, TagAPI.ITEM_LEAVES); + } + } else if (block instanceof FeatureSaplingBlock){ + TagAPI.addTags(block, TagAPI.BLOCK_SAPLINGS); + if (item != null){ + TagAPI.addTags(item, TagAPI.ITEM_SAPLINGS); + } + } + + return block; } public Block registerBlockOnly(ResourceLocation id, Block block) { From bd4e61f14f40cfa39c53e736b54f830a95d34d3f Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 18 Oct 2021 22:53:53 +0200 Subject: [PATCH 10/53] Add support for hanging saplings --- .../blocks/FeatureHangingSaplingBlock.java | 32 +++++ .../ru/bclib/blocks/FeatureSaplingBlock.java | 84 +---------- .../blocks/FeatureSaplingBlockCommon.java | 133 ++++++++++++++++++ 3 files changed, 168 insertions(+), 81 deletions(-) create mode 100644 src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java create mode 100644 src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java diff --git a/src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java new file mode 100644 index 00000000..049f8c10 --- /dev/null +++ b/src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java @@ -0,0 +1,32 @@ +package ru.bclib.blocks; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.LevelReader; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; + +public abstract class FeatureHangingSaplingBlock extends FeatureSaplingBlockCommon{ + private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); + public FeatureHangingSaplingBlock() { + super(); + } + + public FeatureHangingSaplingBlock(int light) { + super(light); + } + + @Override + public boolean canSurvive(BlockState blockState, LevelReader levelReader, BlockPos blockPos) { + final BlockPos target = blockPos.above(); + return this.mayPlaceOn(levelReader.getBlockState(target), levelReader, target); + } + + @Override + public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { + return SHAPE; + } + +} diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index 40ea6e02..670d041c 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -37,97 +37,19 @@ import java.util.Optional; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class FeatureSaplingBlock extends SaplingBlock implements RenderLayerProvider, BlockModelProvider { +public abstract class FeatureSaplingBlock extends FeatureSaplingBlockCommon { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public FeatureSaplingBlock() { - super( - null, - FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) - .collidable(false) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks() - ); + super(); } public FeatureSaplingBlock(int light) { - super( - null, - FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) - .collidable(false) - .luminance(light) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks() - ); - } - - protected abstract Feature getFeature(); - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); + super(light); } @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPE; } - - @Override - public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { - if (!canSurvive(state, world, pos)) return Blocks.AIR.defaultBlockState(); - else return state; - } - - @Override - public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { - return random.nextInt(16) == 0; - } - - @Override - public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { - FeaturePlaceContext context = new FeaturePlaceContext( - world, - world.getChunkSource().getGenerator(), - random, - pos, - null - ); - getFeature().place(context); - } - - @Override - public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { - this.tick(state, world, pos, random); - } - - @Override - public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { - super.tick(state, world, pos, random); - if (isBonemealSuccess(world, random, pos, state)) { - performBonemeal(world, random, pos, state); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createBlockItem(resourceLocation); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS, resourceLocation); - return ModelsHelper.fromPattern(pattern); - } } diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java new file mode 100644 index 00000000..032424d4 --- /dev/null +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java @@ -0,0 +1,133 @@ +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.client.renderer.block.model.BlockModel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.SaplingBlock; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.phys.shapes.CollisionContext; +import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; +import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.ModelsHelper; +import ru.bclib.client.models.PatternsHelper; +import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Random; + +abstract class FeatureSaplingBlockCommon extends SaplingBlock implements RenderLayerProvider, BlockModelProvider { + public FeatureSaplingBlockCommon() { + super( + null, + FabricBlockSettings.of(Material.PLANT) + .breakByHand(true) + .collidable(false) + .instabreak() + .sound(SoundType.GRASS) + .randomTicks() + ); + } + + public FeatureSaplingBlockCommon(int light) { + super( + null, + FabricBlockSettings.of(Material.PLANT) + .breakByHand(true) + .collidable(false) + .luminance(light) + .instabreak() + .sound(SoundType.GRASS) + .randomTicks() + ); + } + + @Deprecated + /** + * Override {@link #getFeature(BlockState)} directly. Will be removed in 5.x + */ + protected Feature getFeature() { return null; } + + protected Feature getFeature(BlockState state){ + return getFeature(); + } + + @Override + public List getDrops(BlockState state, LootContext.Builder builder) { + return Collections.singletonList(new ItemStack(this)); + } + + @Override + public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { + if (!canSurvive(state, world, pos)) return Blocks.AIR.defaultBlockState(); + else return state; + } + + @Override + public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { + return random.nextInt(16) == 0; + } + + @Override + public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { + FeaturePlaceContext context = new FeaturePlaceContext( + world, + world.getChunkSource().getGenerator(), + random, + pos, + null + ); + getFeature(blockState).place(context); + } + + @Override + public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { + this.tick(state, world, pos, random); + } + + @Override + public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { + super.tick(state, world, pos, random); + if (isBonemealSuccess(world, random, pos, state)) { + performBonemeal(world, random, pos, state); + } + } + + @Override + public BCLRenderLayer getRenderLayer() { + return BCLRenderLayer.CUTOUT; + } + + @Override + @Environment(EnvType.CLIENT) + public BlockModel getItemModel(ResourceLocation resourceLocation) { + return ModelsHelper.createBlockItem(resourceLocation); + } + + @Override + @Environment(EnvType.CLIENT) + public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { + Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS, resourceLocation); + return ModelsHelper.fromPattern(pattern); + } +} From da0d1221662615b1bfa000042165589fe1b8a1d8 Mon Sep 17 00:00:00 2001 From: Frank Date: Tue, 19 Oct 2021 09:58:41 +0200 Subject: [PATCH 11/53] Added Function that allows developers to manually fix nbts --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 2 +- .../bclib/api/datafixer/MigrationProfile.java | 57 +++++++++++++++++-- .../java/ru/bclib/api/datafixer/Patch.java | 14 ++++- 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index c0116bdb..6f52ad33 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -463,7 +463,7 @@ public class DataFixerAPI { e.printStackTrace(); } } - + static CompoundTag patchConfTag = null; static CompoundTag getPatchData(){ if (patchConfTag==null) { diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java index 24e5e8ad..2cf92fdd 100644 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -12,6 +12,7 @@ import ru.bclib.util.ModUtil; import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; @@ -34,7 +35,7 @@ public class MigrationProfile { private boolean didRunPrePatch; private Exception prePatchException; - MigrationProfile(CompoundTag config) { + MigrationProfile(CompoundTag config, boolean applyAll) { this.config = config; this.mods = Collections.unmodifiableSet(Patch.getALL() @@ -55,7 +56,7 @@ public class MigrationProfile { List paths = patch.getWorldDataIDPaths(); if (paths!=null) worldDataIDPaths.put(modID, paths); - if (currentPatchLevel(modID) < patch.level) { + if (applyAll || currentPatchLevel(modID) < patch.level) { replacements.putAll(patch.getIDReplacements()); if (patch.getLevelDatPatcher()!=null) levelPatches.add(patch.getLevelDatPatcher()); @@ -75,6 +76,53 @@ public class MigrationProfile { this.worldDataPatchers = Collections.unmodifiableList(worldDataPatches); } + /** + * This method is supposed to be used by developers to apply id-patches to custom nbt structures. It is only + * available in Developer-Mode + * + */ + public static void fixCustomFolder(File dir){ + if (!BCLib.isDevEnvironment()) return; + MigrationProfile profile = Patch.createMigrationData(); + List nbts = getAllNbts(dir, null); + nbts.parallelStream().forEach((file) -> { + DataFixerAPI.LOGGER.info("Loading NBT " + file); + try { + CompoundTag root = NbtIo.readCompressed(file); + boolean[] changed = {false}; + if (root.contains("palette")){ + ListTag items = root.getList("palette", Tag.TAG_COMPOUND); + items.forEach(inTag -> { + CompoundTag tag = (CompoundTag)inTag; + changed[0] |= profile.replaceStringFromIDs(tag, "Name"); + }); + } + + if (changed[0]){ + DataFixerAPI.LOGGER.info("Writing NBT " + file); + NbtIo.writeCompressed(root, file); + } + } + catch (IOException e) { + e.printStackTrace(); + } + }); + } + + private static List getAllNbts(File dir, List list) { + if (list == null) { + list = new ArrayList<>(); + } + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + getAllNbts(file, list); + } else if (file.isFile() && file.getName().endsWith(".nbt")) { + list.add(file); + } + } + return list; + } + final public CompoundTag getLevelDat(File levelBaseDir){ if (level == null || this.levelBaseDir==null || !this.levelBaseDir.equals(levelBaseDir)){ runPrePatches(levelBaseDir); @@ -125,12 +173,13 @@ public class MigrationProfile { final public void markApplied() { for (String modID : mods) { DataFixerAPI.LOGGER.info("Updating Patch-Level for '{}' from {} to {}", modID, ModUtil.convertModVersion(currentPatchLevel(modID)), ModUtil.convertModVersion(Patch.maxPatchLevel(modID))); - config.putString(modID, Patch.maxPatchVersion(modID)); + if (config!=null) + config.putString(modID, Patch.maxPatchVersion(modID)); } } public String currentPatchVersion(@NotNull String modID) { - if (!config.contains(modID)) return "0.0.0"; + if (config==null || !config.contains(modID)) return "0.0.0"; return config.getString(modID); } diff --git a/src/main/java/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java index 4b742f5a..fe025d9e 100644 --- a/src/main/java/ru/bclib/api/datafixer/Patch.java +++ b/src/main/java/ru/bclib/api/datafixer/Patch.java @@ -151,12 +151,20 @@ public abstract class Patch { *

* A {@link #Patch} with a given {@link #level} is only included if the patch-level of the * world is less - * @param config The current patch-level configuration - * @param levelBaseDir The location of the level + * @param config The current patch-level configuration* * @return a new {@link MigrationProfile} Object. */ static MigrationProfile createMigrationData(CompoundTag config) { - return new MigrationProfile(config); + return new MigrationProfile(config, false); + } + + /** + * This method is supposed to be used by developers to apply id-patches to custom nbt structures. It is only + * available in Developer-Mode + * + */ + static MigrationProfile createMigrationData() { + return new MigrationProfile(null, true); } /** From e37d03fa778c6339a4f801c0016e0744dd176b0c Mon Sep 17 00:00:00 2001 From: Frank Date: Tue, 12 Oct 2021 22:04:45 +0200 Subject: [PATCH 12/53] replaced accesswidener with simple reflection (cherry picked from commit 18a64c267dad24f5afa6cea124c45fb310487ca9) --- bclib.gradle | 4 -- .../ru/bclib/mixin/client/MinecraftMixin.java | 52 ++++++++++++++++--- src/main/resources/bclib.accesswidener | 4 -- src/main/resources/fabric.mod.json | 3 +- 4 files changed, 47 insertions(+), 16 deletions(-) delete mode 100644 src/main/resources/bclib.accesswidener diff --git a/bclib.gradle b/bclib.gradle index 2f8a64ae..3ff8796e 100644 --- a/bclib.gradle +++ b/bclib.gradle @@ -23,10 +23,6 @@ repositories { maven { url 'https://jitpack.io' } } -minecraft { - accessWidener = file("src/main/resources/bclib.accesswidener") -} - dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings minecraft.officialMojangMappings() diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 76d00a4d..3499016a 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -2,7 +2,6 @@ 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; import net.minecraft.client.color.item.ItemColors; import net.minecraft.client.main.GameConfig; @@ -26,6 +25,11 @@ import ru.bclib.api.dataexchange.DataExchangeAPI; import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.interfaces.CustomColorProvider; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; import java.util.function.Function; @Mixin(Minecraft.class) @@ -49,19 +53,55 @@ public abstract class MinecraftMixin { }); } - @Shadow - protected abstract void doLoadLevel(String string, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl, ExperimentalDialogType experimentalDialogType); - +// @Shadow +// protected abstract void doLoadLevel(String string, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl, ExperimentalDialogType experimentalDialogType); +// @Shadow @Final private LevelStorageSource levelSource; - + Method doLoadLevel = null; + Object experimentalDialogType_BACKUP = null; + + private void bclib_doLoadLevel_BACKUP(String levelID, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl){ + if (experimentalDialogType_BACKUP==null) { + try { + Class experimentalDialogType = Class.forName("net.minecraft.client.Minecraft$ExperimentalDialogType"); + Field f = experimentalDialogType.getDeclaredField("$VALUES"); + f.setAccessible(true); + experimentalDialogType_BACKUP = Array.get(f.get(null), 2); + } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) { + e.printStackTrace(); + } + } + + if (doLoadLevel==null) { + for (Method m : Minecraft.class.getDeclaredMethods()) { + if (m.getName().equals("doLoadLevel")) { + doLoadLevel = m; + break; + } + } + } + + if (doLoadLevel!=null && experimentalDialogType_BACKUP!=null){ + doLoadLevel.setAccessible(true); + try { + doLoadLevel.invoke(this, new Object[]{levelID, registryHolder, function, function4, bl, experimentalDialogType_BACKUP}); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + } + @Inject(method = "loadLevel", cancellable = true, at = @At("HEAD")) private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci) { DataExchangeAPI.prepareServerside(); if (DataFixerAPI.fixData(this.levelSource, levelID, true, (appliedFixes) -> { - this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, Minecraft.ExperimentalDialogType.BACKUP); + bclib_doLoadLevel_BACKUP(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false); + //this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, Minecraft.ExperimentalDialogType.BACKUP); })) { ci.cancel(); } diff --git a/src/main/resources/bclib.accesswidener b/src/main/resources/bclib.accesswidener deleted file mode 100644 index 3efe4455..00000000 --- a/src/main/resources/bclib.accesswidener +++ /dev/null @@ -1,4 +0,0 @@ -accessWidener v1 named - -# Classes -accessible class net/minecraft/client/Minecraft$ExperimentalDialogType \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 9ec07e33..f7563925 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,8 +28,7 @@ ], "modmenu": [ "ru.bclib.gui.modmenu.EntryPoint::entrypointObject" ] }, - "accessWidener" : "bclib.accesswidener", - "mixins": [ + "mixins": [ "bclib.mixins.common.json", "bclib.mixins.client.json" ], From 52146286fef963e86f3cadbedaa796c1de8d116a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 22 Oct 2021 13:50:07 +0300 Subject: [PATCH 13/53] Thick fog rendering fixes --- .../render/CustomBackgroundRenderer.java | 81 +++++++++++-------- .../mixin/client/BackgroundRendererMixin.java | 1 + 2 files changed, 50 insertions(+), 32 deletions(-) diff --git a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java index f8b75a5a..536a0f81 100644 --- a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java +++ b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java @@ -3,6 +3,7 @@ package ru.bclib.client.render; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Camera; import net.minecraft.client.renderer.FogRenderer; +import net.minecraft.client.renderer.FogRenderer.FogMode; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.util.Mth; import net.minecraft.world.effect.MobEffectInstance; @@ -22,46 +23,62 @@ public class CustomBackgroundRenderer { private static final MutableBlockPos MUT_POS = new MutableBlockPos(); private static final float[] FOG_DENSITY = new float[8]; private static final int GRID_SIZE = 32; + private static float fogStart = 0; + private static float fogEnd = 192; public static boolean applyFogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog) { - Entity entity = camera.getEntity(); FogType fogType = camera.getFluidInCamera(); - if (fogType != FogType.WATER) { - if (shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { - return false; - } - float fog = getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); - BackgroundInfo.fogDensity = fog; - float start = viewDistance * 0.75F / fog; - float end = viewDistance / fog; - - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - MobEffectInstance effect = livingEntity.getEffect(MobEffects.BLINDNESS); - if (effect != null) { - int duration = effect.getDuration(); - if (duration > 20) { - start = 0; - end *= 0.03F; - BackgroundInfo.blindness = 1; - } - else { - float delta = (float) duration / 20F; - BackgroundInfo.blindness = delta; - start = Mth.lerp(delta, start, 0); - end = Mth.lerp(delta, end, end * 0.03F); - } + + if (fogType == FogType.WATER || fogType == FogType.LAVA || fogMode != FogMode.FOG_SKY) { + return false; + } + + Entity entity = camera.getEntity(); + + if (shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { + return false; + } + + float fog = getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); + BackgroundInfo.fogDensity = fog; + + System.out.println(thickFog); + + if (thickFog) { + fogStart = viewDistance * 0.05F / fog; + fogEnd = Math.min(viewDistance, 192.0F) * 0.5F / fog; + } + else { + fogStart = viewDistance * 0.75F / fog; + fogEnd = viewDistance / fog; + } + + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + MobEffectInstance effect = livingEntity.getEffect(MobEffects.BLINDNESS); + if (effect != null) { + int duration = effect.getDuration(); + if (duration > 20) { + fogStart = 0; + fogEnd *= 0.03F; + BackgroundInfo.blindness = 1; } else { - BackgroundInfo.blindness = 0; + float delta = (float) duration / 20F; + BackgroundInfo.blindness = delta; + fogStart = Mth.lerp(delta, fogStart, 0); + fogEnd = Mth.lerp(delta, fogEnd, fogEnd * 0.03F); } } - - RenderSystem.setShaderFogStart(start); - RenderSystem.setShaderFogEnd(end); - return true; + else { + BackgroundInfo.blindness = 0; + } } - return false; + + RenderSystem.setShaderFogStart(fogStart); + RenderSystem.setShaderFogEnd(fogEnd); + + return true; } private static boolean shouldIgnore(Level level, int x, int y, int z) { diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index 916619e5..d6f109ce 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -23,6 +23,7 @@ public class BackgroundRendererMixin { private static final MutableBlockPos BCLIB_LAST_POS = new MutableBlockPos(0, -100, 0); private static final MutableBlockPos BCLIB_MUT_POS = new MutableBlockPos(); private static final float[] BCLIB_FOG_DENSITY = new float[8]; + //private static boolean isEnd; @Shadow private static float fogRed; From 9b312bf4defd89e4d1b15faa9da58e0e5f4ed20d Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 22 Oct 2021 13:53:37 +0300 Subject: [PATCH 14/53] Debug removal --- .../java/ru/bclib/client/render/CustomBackgroundRenderer.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java index 536a0f81..3285dbb9 100644 --- a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java +++ b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java @@ -42,8 +42,6 @@ public class CustomBackgroundRenderer { float fog = getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); BackgroundInfo.fogDensity = fog; - System.out.println(thickFog); - if (thickFog) { fogStart = viewDistance * 0.05F / fog; fogEnd = Math.min(viewDistance, 192.0F) * 0.5F / fog; From f88506f654610fe9112143fcb1f80979af1d3829 Mon Sep 17 00:00:00 2001 From: Frank Date: Fri, 22 Oct 2021 15:28:37 +0200 Subject: [PATCH 15/53] Revert "Merge remote-tracking branch 'origin/main'" This reverts commit ff8b366eb92ce8c6bfb41a15fe3d7021c2d851e3, reversing changes made to 52146286fef963e86f3cadbedaa796c1de8d116a. --- bclib.gradle | 4 ++ .../ru/bclib/mixin/client/MinecraftMixin.java | 52 +++---------------- src/main/resources/bclib.accesswidener | 4 ++ src/main/resources/fabric.mod.json | 3 +- 4 files changed, 16 insertions(+), 47 deletions(-) create mode 100644 src/main/resources/bclib.accesswidener diff --git a/bclib.gradle b/bclib.gradle index 3ff8796e..2f8a64ae 100644 --- a/bclib.gradle +++ b/bclib.gradle @@ -23,6 +23,10 @@ repositories { maven { url 'https://jitpack.io' } } +minecraft { + accessWidener = file("src/main/resources/bclib.accesswidener") +} + dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings minecraft.officialMojangMappings() diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 3499016a..76d00a4d 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -2,6 +2,7 @@ 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; import net.minecraft.client.color.item.ItemColors; import net.minecraft.client.main.GameConfig; @@ -25,11 +26,6 @@ import ru.bclib.api.dataexchange.DataExchangeAPI; import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.interfaces.CustomColorProvider; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; import java.util.function.Function; @Mixin(Minecraft.class) @@ -53,55 +49,19 @@ public abstract class MinecraftMixin { }); } -// @Shadow -// protected abstract void doLoadLevel(String string, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl, ExperimentalDialogType experimentalDialogType); -// + @Shadow + protected abstract void doLoadLevel(String string, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl, ExperimentalDialogType experimentalDialogType); + @Shadow @Final private LevelStorageSource levelSource; - Method doLoadLevel = null; - Object experimentalDialogType_BACKUP = null; - - private void bclib_doLoadLevel_BACKUP(String levelID, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl){ - if (experimentalDialogType_BACKUP==null) { - try { - Class experimentalDialogType = Class.forName("net.minecraft.client.Minecraft$ExperimentalDialogType"); - Field f = experimentalDialogType.getDeclaredField("$VALUES"); - f.setAccessible(true); - experimentalDialogType_BACKUP = Array.get(f.get(null), 2); - } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) { - e.printStackTrace(); - } - } - - if (doLoadLevel==null) { - for (Method m : Minecraft.class.getDeclaredMethods()) { - if (m.getName().equals("doLoadLevel")) { - doLoadLevel = m; - break; - } - } - } - - if (doLoadLevel!=null && experimentalDialogType_BACKUP!=null){ - doLoadLevel.setAccessible(true); - try { - doLoadLevel.invoke(this, new Object[]{levelID, registryHolder, function, function4, bl, experimentalDialogType_BACKUP}); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - } - + @Inject(method = "loadLevel", cancellable = true, at = @At("HEAD")) private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci) { DataExchangeAPI.prepareServerside(); if (DataFixerAPI.fixData(this.levelSource, levelID, true, (appliedFixes) -> { - bclib_doLoadLevel_BACKUP(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false); - //this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, Minecraft.ExperimentalDialogType.BACKUP); + this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, Minecraft.ExperimentalDialogType.BACKUP); })) { ci.cancel(); } diff --git a/src/main/resources/bclib.accesswidener b/src/main/resources/bclib.accesswidener new file mode 100644 index 00000000..3efe4455 --- /dev/null +++ b/src/main/resources/bclib.accesswidener @@ -0,0 +1,4 @@ +accessWidener v1 named + +# Classes +accessible class net/minecraft/client/Minecraft$ExperimentalDialogType \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index f7563925..9ec07e33 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -28,7 +28,8 @@ ], "modmenu": [ "ru.bclib.gui.modmenu.EntryPoint::entrypointObject" ] }, - "mixins": [ + "accessWidener" : "bclib.accesswidener", + "mixins": [ "bclib.mixins.common.json", "bclib.mixins.client.json" ], From 69ae8ed33effc9de9a5c9704bdfb9712a8f45c2a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 22 Oct 2021 21:59:56 +0300 Subject: [PATCH 16/53] Small change --- .../java/ru/bclib/client/render/CustomBackgroundRenderer.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java index 3285dbb9..fe92ef7c 100644 --- a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java +++ b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java @@ -30,12 +30,14 @@ public class CustomBackgroundRenderer { FogType fogType = camera.getFluidInCamera(); if (fogType == FogType.WATER || fogType == FogType.LAVA || fogMode != FogMode.FOG_SKY) { + BackgroundInfo.fogDensity = 1; return false; } Entity entity = camera.getEntity(); if (shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { + BackgroundInfo.fogDensity = 1; return false; } From d47321c0f7e385d7c6ead6e5378c32d27afda237 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 23 Oct 2021 19:49:02 +0200 Subject: [PATCH 17/53] Prepared state fixer --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 15 ++++++++++++--- .../bclib/api/datafixer/MigrationProfile.java | 13 +++++++++++++ src/main/java/ru/bclib/api/datafixer/Patch.java | 17 +++++++++++++++++ .../ru/bclib/api/datafixer/PatchBiFunction.java | 6 ++++++ 4 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 6f52ad33..088a01ba 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -416,7 +416,7 @@ public class DataFixerAPI { for (int z = 0; z < 32; z++) { ChunkPos pos = new ChunkPos(x, z); changed[0] = false; - if (region.hasChunk(pos)) { + if (region.hasChunk(pos) && !state.didFail) { DataInputStream input = region.getChunkDataInputStream(pos); CompoundTag root = NbtIo.read(input); // if ((root.toString().contains("betternether:chest") || root.toString().contains("bclib:chest"))) { @@ -442,6 +442,16 @@ public class DataFixerAPI { CompoundTag blockTagCompound = ((CompoundTag) blockTag); changed[0] |= data.replaceStringFromIDs(blockTagCompound, "Name"); }); + + try { + changed[0] |= data.patchBlockState(palette, ((CompoundTag) tag).getList("BlockStates", Tag.TAG_LONG)); + } + catch (PatchDidiFailException e) { + BCLib.LOGGER.error("Failed fixing BlockState in " + pos); + state.didFail = true; + changed[0] = false; + e.printStackTrace(); + } }); if (changed[0]) { @@ -450,7 +460,6 @@ public class DataFixerAPI { DataOutputStream output = region.getChunkDataOutputStream(pos); NbtIo.write(root, output); output.close(); - } } } @@ -458,7 +467,7 @@ public class DataFixerAPI { region.close(); } catch (Exception e) { - BCLib.LOGGER.error("Failed fixing Player Data."); + BCLib.LOGGER.error("Failed fixing Region."); state.didFail = true; e.printStackTrace(); } diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java index 2cf92fdd..3cc514ce 100644 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -25,6 +25,7 @@ public class MigrationProfile { final Set mods; final Map idReplacements; final List> levelPatchers; + final List> statePatchers; final List worldDataPatchers; final Map> worldDataIDPaths; @@ -46,6 +47,7 @@ public class MigrationProfile { HashMap replacements = new HashMap(); List> levelPatches = new LinkedList<>(); List worldDataPatches = new LinkedList<>(); + List> statePatches = new LinkedList<>(); HashMap> worldDataIDPaths = new HashMap<>(); for (String modID : mods) { @@ -62,6 +64,8 @@ public class MigrationProfile { levelPatches.add(patch.getLevelDatPatcher()); if (patch.getWorldDataPatcher()!=null) worldDataPatches.add(patch); + if (patch.getBlockStatePatcher()!=null) + statePatches.add(patch.getBlockStatePatcher()); DataFixerAPI.LOGGER.info("Applying " + patch); } else { @@ -74,6 +78,7 @@ public class MigrationProfile { this.idReplacements = Collections.unmodifiableMap(replacements); this.levelPatchers = Collections.unmodifiableList(levelPatches); this.worldDataPatchers = Collections.unmodifiableList(worldDataPatches); + this.statePatchers = Collections.unmodifiableList(statePatches); } /** @@ -305,4 +310,12 @@ public class MigrationProfile { } } } + + public boolean patchBlockState(ListTag palette, ListTag states) throws PatchDidiFailException{ + boolean changed = false; + for (PatchBiFunction f : statePatchers) { + changed |= f.apply(palette, states, this); + } + return changed; + } } diff --git a/src/main/java/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java index fe025d9e..dafa6dd3 100644 --- a/src/main/java/ru/bclib/api/datafixer/Patch.java +++ b/src/main/java/ru/bclib/api/datafixer/Patch.java @@ -1,6 +1,7 @@ package ru.bclib.api.datafixer; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; import org.jetbrains.annotations.NotNull; import ru.bclib.util.ModUtil; @@ -145,6 +146,22 @@ public abstract class Patch { */ public PatchFunction getWorldDataPatcher() { return null; } + /** + * Return a {@link PatchBiFunction} that is called with pallette and blockstate of + * each chunk in every region. This method is called AFTER all ID replacements + * from {@link #getIDReplacements()} were applied to the pallete. + * + * The first parameter is the palette and the second is the blockstate. + * + * The function needs to return {@code true}, if changes were made to the data. + * If an error occurs, the method should throw a {@link PatchDidiFailException} + * + * The default implementation of this method returns null. + * + * @return {@code true} if changes were applied and we need to save the data + */ + public PatchBiFunction getBlockStatePatcher() { return null; } + /** * Generates ready to use data for all currently registered patches. The list of * patches is selected by the current patch-level of the world. diff --git a/src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java b/src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java new file mode 100644 index 00000000..6bd8da12 --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java @@ -0,0 +1,6 @@ +package ru.bclib.api.datafixer; + +@FunctionalInterface +public interface PatchBiFunction { + R apply(U t, V v, MigrationProfile profile) throws PatchDidiFailException; +} \ No newline at end of file From 3888998aff6d370e22253098020b96cb90c8eebb Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 25 Oct 2021 16:20:06 +0300 Subject: [PATCH 18/53] Generator config fix --- src/main/java/ru/bclib/config/Configs.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/config/Configs.java b/src/main/java/ru/bclib/config/Configs.java index 5779a954..2926b235 100644 --- a/src/main/java/ru/bclib/config/Configs.java +++ b/src/main/java/ru/bclib/config/Configs.java @@ -12,7 +12,7 @@ public class Configs { public static final ServerConfig SERVER_CONFIG = new ServerConfig(); - public static final PathConfig GENERATOR_CONFIG = new PathConfig(BCLib.MOD_ID, "generator"); + public static final PathConfig GENERATOR_CONFIG = new PathConfig(BCLib.MOD_ID, "generator", false); public static final PathConfig MAIN_CONFIG = new PathConfig(BCLib.MOD_ID, "main", true, true); public static final String MAIN_PATCH_CATEGORY = "patches"; @@ -23,5 +23,6 @@ public class Configs { public static void save() { MAIN_CONFIG.saveChanges(); RECIPE_CONFIG.saveChanges(); + GENERATOR_CONFIG.saveChanges(); } } From 7f7e4bfa4c619b9681b43c5dcfc322f0979a9074 Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 25 Oct 2021 15:32:17 +0200 Subject: [PATCH 19/53] Better Shears Integration --- src/main/java/ru/bclib/api/TagAPI.java | 14 +++++++++++++ .../ru/bclib/items/tool/BaseShearsItem.java | 21 +++++++++++++++++++ .../common/shears/BeehiveBlockMixin.java | 17 +++++++++++++++ .../shears/DiggingEnchantmentMixin.java | 17 +++++++++++++++ .../mixin/common/shears/MushroomCowMixin.java | 17 +++++++++++++++ .../common/shears/PumpkinBlockMixin.java | 17 +++++++++++++++ .../bclib/mixin/common/shears/SheepMixin.java | 17 +++++++++++++++ .../mixin/common/shears/SnowGolemMixin.java | 17 +++++++++++++++ .../common/shears/TripWireBlockMixi.java | 17 +++++++++++++++ .../java/ru/bclib/registry/ItemRegistry.java | 9 ++++++-- src/main/resources/bclib.mixins.common.json | 9 +++++++- 11 files changed, 169 insertions(+), 3 deletions(-) create mode 100644 src/main/java/ru/bclib/items/tool/BaseShearsItem.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixi.java diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 215c060b..f27570f4 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -61,6 +61,8 @@ public class TagAPI { public final static Tag.Named ITEM_HAMMERS = makeCommonItemTag("hammers"); public static final Tag.Named ITEM_SAPLINGS = makeCommonItemTag("saplings"); public static final Tag.Named ITEM_LEAVES = makeCommonItemTag("leaves"); + public static final Tag.Named ITEM_SHEARS = getMCItemTag("shears"); + public static final Tag.Named ITEM_COMMON_SHEARS = makeCommonItemTag("shears"); /** @@ -131,6 +133,18 @@ public class TagAPI { return tag == null ? (Named) TagRegistry.block(id) : (Named) tag; } + /** + * Get or create Minecraft {@link Item} {@link Tag.Named}. + * + * @param name - {@link String} tag name. + * @return {@link Item} {@link Tag.Named}. + */ + public static Tag.Named getMCItemTag(String name) { + ResourceLocation id = new ResourceLocation(name); + Tag tag = ItemTags.getAllTags().getTag(id); + return tag == null ? (Named) TagRegistry.item(id) : (Named) tag; + } + /** * Adds {@link Block} to NETHER_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. * diff --git a/src/main/java/ru/bclib/items/tool/BaseShearsItem.java b/src/main/java/ru/bclib/items/tool/BaseShearsItem.java new file mode 100644 index 00000000..90af703f --- /dev/null +++ b/src/main/java/ru/bclib/items/tool/BaseShearsItem.java @@ -0,0 +1,21 @@ +package ru.bclib.items.tool; + +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.TagAPI; + +public class BaseShearsItem extends ShearsItem { + public BaseShearsItem(Properties properties) { + super(properties); + } + + public static boolean isShear(ItemStack itemStack, Item item){ + if (item == Items.SHEARS){ + return itemStack.is(item) | itemStack.is(TagAPI.ITEM_COMMON_SHEARS) || itemStack.is(TagAPI.ITEM_SHEARS); + } else { + return itemStack.is(item); + } + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java b/src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java new file mode 100644 index 00000000..9dc7ed3f --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.BeehiveBlock; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(BeehiveBlock.class) +public class BeehiveBlockMixin { + @Redirect(method="use", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_useProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java b/src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java new file mode 100644 index 00000000..47354537 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.DiggingEnchantment; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(DiggingEnchantment.class) +public class DiggingEnchantmentMixin { + @Redirect(method="canEnchant", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java b/src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java new file mode 100644 index 00000000..d58d93c1 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.entity.animal.MushroomCow; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(MushroomCow.class) +public class MushroomCowMixin { + @Redirect(method="mobInteract", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java b/src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java new file mode 100644 index 00000000..deb7fc08 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.PumpkinBlock; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(PumpkinBlock.class) +public abstract class PumpkinBlockMixin { + @Redirect(method="use", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_useProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java b/src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java new file mode 100644 index 00000000..77e42736 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.entity.animal.Sheep; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(Sheep.class) +public class SheepMixin { + @Redirect(method="mobInteract", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java b/src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java new file mode 100644 index 00000000..f6fc2f6a --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.entity.animal.SnowGolem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(SnowGolem.class) +public class SnowGolemMixin { + @Redirect(method="mobInteract", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixi.java b/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixi.java new file mode 100644 index 00000000..1f3bfb1c --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixi.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common.shears; + +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.TripWireBlock; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.items.tool.BaseShearsItem; + +@Mixin(TripWireBlock.class) +public class TripWireBlockMixi { + @Redirect(method="playerWillDestroy", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) + public boolean bn_useProxy(ItemStack itemStack, Item item){ + return BaseShearsItem.isShear(itemStack, item); + } +} diff --git a/src/main/java/ru/bclib/registry/ItemRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java index 270e06da..c406faf3 100644 --- a/src/main/java/ru/bclib/registry/ItemRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemRegistry.java @@ -4,6 +4,7 @@ import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockSource; import net.minecraft.core.Direction; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; +import net.minecraft.core.dispenser.ShearsDispenseItemBehavior; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import net.minecraft.tags.Tag; @@ -18,11 +19,11 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShovelItem; import net.minecraft.world.item.SpawnEggItem; import net.minecraft.world.item.SwordItem; -import net.minecraft.world.item.TieredItem; import net.minecraft.world.level.block.DispenserBlock; import ru.bclib.api.TagAPI; import ru.bclib.items.BaseDiscItem; import ru.bclib.items.BaseDrinkItem; +import ru.bclib.items.tool.BaseShearsItem; import ru.bclib.items.BaseSpawnEggItem; import ru.bclib.items.ModelProviderItem; import ru.bclib.items.tool.BaseAxeItem; @@ -49,7 +50,7 @@ public abstract class ItemRegistry extends BaseRegistry { return item; } - public TieredItem registerTool(String name, TieredItem item) { + public Item registerTool(String name, Item item) { ResourceLocation id = createModId(name); registerItem(id, item, BaseRegistry.getModItems(id.getNamespace())); @@ -68,6 +69,10 @@ public abstract class ItemRegistry extends BaseRegistry { else if (item instanceof BaseHoeItem) { TagAPI.addTag((Tag.Named) FabricToolTags.HOES, item); } + else if (item instanceof BaseShearsItem) { + TagAPI.addTags(item, (Tag.Named) FabricToolTags.SHEARS, TagAPI.ITEM_SHEARS, TagAPI.ITEM_COMMON_SHEARS); + DispenserBlock.registerBehavior(item.asItem(), new ShearsDispenseItemBehavior()); + } return item; } diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index f430772b..978e39a7 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -20,7 +20,14 @@ "AnvilMenuMixin", "TagLoaderMixin", "BiomeMixin", - "MainMixin" + "MainMixin", + "shears.BeehiveBlockMixin", + "shears.DiggingEnchantmentMixin", + "shears.MushroomCowMixin", + "shears.PumpkinBlockMixin", + "shears.SheepMixin", + "shears.SnowGolemMixin", + "shears.TripWireBlockMixi" ], "injectors": { "defaultRequire": 1 From a5bf1ea3e6c497a7cd122dcc0583760f5f90fa93 Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 25 Oct 2021 15:32:36 +0200 Subject: [PATCH 20/53] Create Ores with custom properties --- src/main/java/ru/bclib/blocks/BaseOreBlock.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index 168c5bce..f529c082 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -9,6 +9,7 @@ import net.minecraft.world.item.Item; 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.ItemLike; import net.minecraft.world.level.block.OreBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; @@ -28,11 +29,16 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider { private final int maxCount; public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) { - super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) + this(drop, minCount, maxCount, experience, FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) .hardness(3F) .resistance(9F) .requiresCorrectToolForDrops() - .sound(SoundType.STONE), UniformInt.of(1, experience)); + .sound(SoundType.STONE)); + + } + + public BaseOreBlock(Item drop, int minCount, int maxCount, int experience, Properties properties) { + super(properties, UniformInt.of(experience>0?1:0, experience)); this.dropItem = drop; this.minCount = minCount; this.maxCount = maxCount; @@ -41,10 +47,14 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider { @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { + return getDroppedItems(this, dropItem, maxCount, minCount, state, builder); + } + + public static List getDroppedItems(ItemLike block, Item dropItem, int maxCount, int minCount, 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(this)); + return Collections.singletonList(new ItemStack(block)); } int count; int enchantment = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); From 102f80c62ee7b31a25f4bfb512b1702b0329c223 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 25 Oct 2021 17:37:36 +0300 Subject: [PATCH 21/53] Fog rendering fixes --- .../render/CustomBackgroundRenderer.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java index fe92ef7c..5a37032b 100644 --- a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java +++ b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java @@ -12,6 +12,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.material.FogType; import ru.bclib.api.BiomeAPI; import ru.bclib.util.BackgroundInfo; @@ -36,7 +37,7 @@ public class CustomBackgroundRenderer { Entity entity = camera.getEntity(); - if (shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { + if (!isForcedDimension(entity.level) && shouldIgnoreArea(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { BackgroundInfo.fogDensity = 1; return false; } @@ -81,6 +82,21 @@ public class CustomBackgroundRenderer { return true; } + private static boolean isForcedDimension(Level level) { + return level.dimension() == Level.END || level.dimension() == Level.NETHER; + } + + private static boolean shouldIgnoreArea(Level level, int x, int y, int z) { + for (int i = -8; i <= 8; i += 8) { + for (int j = -8; j <= 8; j += 8) { + if (!shouldIgnore(level, x + i, y, z + j)) { + return false; + } + } + } + return true; + } + private static boolean shouldIgnore(Level level, int x, int y, int z) { Biome biome = level.getBiome(MUT_POS.set(x, y, z)); return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; From 8c535be429a11c5783344531fd5d6a4aaa6d1586 Mon Sep 17 00:00:00 2001 From: Frank Date: Tue, 26 Oct 2021 10:20:25 +0200 Subject: [PATCH 22/53] Added support for custom nether-portal frames (common Tag c:nether_pframe (TagAPI.BLOCK_NETHER_PORTAL_FRAME) --- src/main/java/ru/bclib/api/TagAPI.java | 1 + .../bclib/mixin/common/PortalShapeMixin.java | 33 +++++++++++++++++++ src/main/resources/bclib.mixins.common.json | 3 +- 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index f27570f4..1832ec67 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -39,6 +39,7 @@ public class TagAPI { public static final Tag.Named BLOCK_WOODEN_BARREL = makeCommonBlockTag("wooden_barrels"); public static final Tag.Named BLOCK_END_STONES = makeCommonBlockTag("end_stones"); public static final Tag.Named BLOCK_NETHER_STONES = makeCommonBlockTag("nether_stones"); + public static final Tag.Named BLOCK_NETHER_PORTAL_FRAME = makeCommonBlockTag("nether_pframe"); public static final Tag.Named BLOCK_WORKBENCHES = makeCommonBlockTag("workbench"); public static final Tag.Named BLOCK_SAPLINGS = makeCommonBlockTag("saplings"); public static final Tag.Named BLOCK_LEAVES = makeCommonBlockTag("leaves"); diff --git a/src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java b/src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java new file mode 100644 index 00000000..b4cd38e7 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java @@ -0,0 +1,33 @@ +package ru.bclib.mixin.common; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.state.BlockBehaviour.StatePredicate; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.portal.PortalShape; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; +import ru.bclib.api.TagAPI; + +@Mixin(PortalShape.class) +public class PortalShapeMixin { + @Redirect(method="getDistanceUntilEdgeAboveFrame", at=@At(value="INVOKE", target="Lnet/minecraft/world/level/block/state/BlockBehaviour$StatePredicate;test(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z")) + private boolean be_getDistanceUntilEdgeAboveFrame(StatePredicate statePredicate, BlockState blockState, BlockGetter blockGetter, BlockPos blockPos){ + return be_FRAME(statePredicate, blockState, blockGetter, blockPos); + } + + @Redirect(method="hasTopFrame", at=@At(value="INVOKE", target="Lnet/minecraft/world/level/block/state/BlockBehaviour$StatePredicate;test(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z")) + private boolean be_hasTopFrame(StatePredicate statePredicate, BlockState blockState, BlockGetter blockGetter, BlockPos blockPos){ + return be_FRAME(statePredicate, blockState, blockGetter, blockPos); + } + + @Redirect(method="getDistanceUntilTop", at=@At(value="INVOKE", target="Lnet/minecraft/world/level/block/state/BlockBehaviour$StatePredicate;test(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z")) + private boolean be_getDistanceUntilTop(StatePredicate statePredicate, BlockState blockState, BlockGetter blockGetter, BlockPos blockPos){ + return be_FRAME(statePredicate, blockState, blockGetter, blockPos); + } + + private static boolean be_FRAME(StatePredicate FRAME, BlockState state, BlockGetter getter, BlockPos pos){ + return state.is(TagAPI.BLOCK_NETHER_PORTAL_FRAME) || FRAME.test(state, getter, pos); + } +} diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 978e39a7..f312d6ec 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -27,7 +27,8 @@ "shears.PumpkinBlockMixin", "shears.SheepMixin", "shears.SnowGolemMixin", - "shears.TripWireBlockMixi" + "shears.TripWireBlockMixi", + "PortalShapeMixin" ], "injectors": { "defaultRequire": 1 From 449d7cc0d02526b344a37ae43e5cbe40d71fc384 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 26 Oct 2021 15:00:09 +0300 Subject: [PATCH 23/53] No-abstract registry --- src/main/java/ru/bclib/registry/BlockRegistry.java | 2 +- src/main/java/ru/bclib/registry/ItemRegistry.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/registry/BlockRegistry.java b/src/main/java/ru/bclib/registry/BlockRegistry.java index ce9d941e..cdf44f64 100644 --- a/src/main/java/ru/bclib/registry/BlockRegistry.java +++ b/src/main/java/ru/bclib/registry/BlockRegistry.java @@ -12,7 +12,7 @@ import ru.bclib.blocks.BaseLeavesBlock; import ru.bclib.blocks.FeatureSaplingBlock; import ru.bclib.interfaces.CustomItemProvider; -public abstract class BlockRegistry extends BaseRegistry { +public class BlockRegistry extends BaseRegistry { protected BlockRegistry(CreativeModeTab creativeTab) { super(creativeTab); } diff --git a/src/main/java/ru/bclib/registry/ItemRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java index c406faf3..bc5be078 100644 --- a/src/main/java/ru/bclib/registry/ItemRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemRegistry.java @@ -30,7 +30,7 @@ import ru.bclib.items.tool.BaseAxeItem; import ru.bclib.items.tool.BaseHoeItem; import ru.bclib.items.tool.BasePickaxeItem; -public abstract class ItemRegistry extends BaseRegistry { +public class ItemRegistry extends BaseRegistry { protected ItemRegistry(CreativeModeTab creativeTab) { super(creativeTab); From b66c8cd5a68d4a389179a6245c68781144f96977 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 26 Oct 2021 16:12:10 +0300 Subject: [PATCH 24/53] Registry changes (WIP) --- .../java/ru/bclib/registry/BaseRegistry.java | 51 +++++------ .../java/ru/bclib/registry/BlockRegistry.java | 27 ++++-- .../java/ru/bclib/registry/ItemRegistry.java | 84 +++++++++++++------ 3 files changed, 98 insertions(+), 64 deletions(-) diff --git a/src/main/java/ru/bclib/registry/BaseRegistry.java b/src/main/java/ru/bclib/registry/BaseRegistry.java index a6e985d8..8e61ebe7 100644 --- a/src/main/java/ru/bclib/registry/BaseRegistry.java +++ b/src/main/java/ru/bclib/registry/BaseRegistry.java @@ -3,12 +3,10 @@ package ru.bclib.registry; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; -import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import ru.bclib.BCLib; +import ru.bclib.config.PathConfig; import java.util.List; import java.util.Map; @@ -19,6 +17,24 @@ public abstract class BaseRegistry { private static final Map> MOD_ITEMS = Maps.newHashMap(); protected final CreativeModeTab creativeTab; + protected final PathConfig config; + + protected BaseRegistry(CreativeModeTab creativeTab, PathConfig config) { + this.creativeTab = creativeTab; + this.config = config; + REGISTRIES.add(this); + } + + public abstract T register(ResourceLocation objId, T obj); + + public abstract void registerItem(ResourceLocation id, Item item); + + public FabricItemSettings makeItemSettings() { + FabricItemSettings properties = new FabricItemSettings(); + return (FabricItemSettings) properties.tab(creativeTab); + } + + private void registerInternal() {} public static Map> getRegisteredBlocks() { return MOD_BLOCKS; @@ -49,33 +65,4 @@ public abstract class BaseRegistry { public static void register() { REGISTRIES.forEach(BaseRegistry::registerInternal); } - - protected BaseRegistry(CreativeModeTab creativeTab) { - this.creativeTab = creativeTab; - REGISTRIES.add(this); - } - - public T register(String name, T obj) { - return register(createModId(name), obj); - } - - public abstract T register(ResourceLocation objId, T obj); - - public ResourceLocation createModId(String name) { - return BCLib.makeID(name); - } - - public void registerItem(ResourceLocation id, Item item, List registry) { - if (item != Items.AIR) { - Registry.register(Registry.ITEM, id, item); - registry.add(item); - } - } - - public FabricItemSettings makeItemSettings() { - FabricItemSettings properties = new FabricItemSettings(); - return (FabricItemSettings) properties.tab(creativeTab); - } - - private void registerInternal() {} } diff --git a/src/main/java/ru/bclib/registry/BlockRegistry.java b/src/main/java/ru/bclib/registry/BlockRegistry.java index cdf44f64..f071ad0d 100644 --- a/src/main/java/ru/bclib/registry/BlockRegistry.java +++ b/src/main/java/ru/bclib/registry/BlockRegistry.java @@ -6,19 +6,25 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import ru.bclib.api.TagAPI; import ru.bclib.blocks.BaseLeavesBlock; import ru.bclib.blocks.FeatureSaplingBlock; +import ru.bclib.config.PathConfig; import ru.bclib.interfaces.CustomItemProvider; public class BlockRegistry extends BaseRegistry { - protected BlockRegistry(CreativeModeTab creativeTab) { - super(creativeTab); + public BlockRegistry(CreativeModeTab creativeTab, PathConfig config) { + super(creativeTab, config); } @Override public Block register(ResourceLocation id, Block block) { + if (!config.getBooleanRoot(id.getNamespace(), true)) { + return block; + } + BlockItem item = null; if (block instanceof CustomItemProvider) { item = ((CustomItemProvider) block).getCustomItem(id, makeItemSettings()); @@ -27,9 +33,7 @@ public class BlockRegistry extends BaseRegistry { item = new BlockItem(block, makeItemSettings()); } registerBlockItem(id, item); - if (block.defaultBlockState().getMaterial().isFlammable() && FlammableBlockRegistry.getDefaultInstance() - .get(block) - .getBurnChance() == 0) { + if (block.defaultBlockState().getMaterial().isFlammable() && FlammableBlockRegistry.getDefaultInstance().get(block).getBurnChance() == 0) { FlammableBlockRegistry.getDefaultInstance().add(block, 5, 5); } @@ -51,11 +55,22 @@ public class BlockRegistry extends BaseRegistry { } public Block registerBlockOnly(ResourceLocation id, Block block) { + if (!config.getBooleanRoot(id.getNamespace(), true)) { + return block; + } return Registry.register(Registry.BLOCK, id, block); } private Item registerBlockItem(ResourceLocation id, Item item) { - registerItem(id, item, BaseRegistry.getModBlocks(id.getNamespace())); + registerItem(id, item); return item; } + + @Override + public void registerItem(ResourceLocation id, Item item) { + if (item != null && item != Items.AIR) { + Registry.register(Registry.ITEM, id, item); + getModBlocks(id.getNamespace()).add(item); + } + } } diff --git a/src/main/java/ru/bclib/registry/ItemRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java index bc5be078..fddeacb4 100644 --- a/src/main/java/ru/bclib/registry/ItemRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemRegistry.java @@ -3,6 +3,7 @@ package ru.bclib.registry; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockSource; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; import net.minecraft.core.dispenser.ShearsDispenseItemBehavior; import net.minecraft.resources.ResourceLocation; @@ -16,43 +17,58 @@ import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import net.minecraft.world.item.ShovelItem; import net.minecraft.world.item.SpawnEggItem; import net.minecraft.world.item.SwordItem; import net.minecraft.world.level.block.DispenserBlock; import ru.bclib.api.TagAPI; +import ru.bclib.config.PathConfig; import ru.bclib.items.BaseDiscItem; import ru.bclib.items.BaseDrinkItem; -import ru.bclib.items.tool.BaseShearsItem; import ru.bclib.items.BaseSpawnEggItem; import ru.bclib.items.ModelProviderItem; import ru.bclib.items.tool.BaseAxeItem; import ru.bclib.items.tool.BaseHoeItem; import ru.bclib.items.tool.BasePickaxeItem; +import ru.bclib.items.tool.BaseShearsItem; public class ItemRegistry extends BaseRegistry { - - protected ItemRegistry(CreativeModeTab creativeTab) { - super(creativeTab); + public ItemRegistry(CreativeModeTab creativeTab, PathConfig config) { + super(creativeTab, config); } - public Item registerDisc(String name, int power, SoundEvent sound) { - return register(name, new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1))); + public Item registerDisc(ResourceLocation itemId, int power, SoundEvent sound) { + BaseDiscItem item = new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1)); + + if (!config.getBoolean("musicDiscs", itemId.getPath(), true)) { + return item; + } + + return register(itemId, new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1))); } - public Item registerItem(String name) { - return register(name, new ModelProviderItem(makeItemSettings())); + public Item register(ResourceLocation itemId) { + return register(itemId, new ModelProviderItem(makeItemSettings())); } @Override public Item register(ResourceLocation itemId, Item item) { - registerItem(itemId, item, BaseRegistry.getModItems(itemId.getNamespace())); + if (!config.getBoolean("items", itemId.getPath(), true)) { + return item; + } + + registerItem(itemId, item); + return item; } - public Item registerTool(String name, Item item) { - ResourceLocation id = createModId(name); - registerItem(id, item, BaseRegistry.getModItems(id.getNamespace())); + public Item registerTool(ResourceLocation itemId, Item item) { + if (!config.getBoolean("tools", itemId.getPath(), true)) { + return item; + } + + registerItem(itemId, item); if (item instanceof ShovelItem) { TagAPI.addTag((Tag.Named) FabricToolTags.SHOVELS, item); @@ -77,8 +93,13 @@ public class ItemRegistry extends BaseRegistry { return item; } - public Item registerEgg(String name, EntityType type, int background, int dots) { + public Item registerEgg(ResourceLocation itemId, EntityType type, int background, int dots) { SpawnEggItem item = new BaseSpawnEggItem(type, background, dots, makeItemSettings()); + + if (!config.getBoolean("spawnEggs", itemId.getPath(), true)) { + return item; + } + DefaultDispenseItemBehavior behavior = new DefaultDispenseItemBehavior() { public ItemStack execute(BlockSource pointer, ItemStack stack) { Direction direction = pointer.getBlockState().getValue(DispenserBlock.FACING); @@ -97,31 +118,42 @@ public class ItemRegistry extends BaseRegistry { } }; DispenserBlock.registerBehavior(item, behavior); - return register(name, item); + return register(itemId, item); } - public Item registerFood(String name, int hunger, float saturation, MobEffectInstance... effects) { + public Item registerFood(ResourceLocation itemId, int hunger, float saturation, MobEffectInstance... effects) { FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); for (MobEffectInstance effect : effects) { builder.effect(effect, 1F); } - return registerFood(name, builder.build()); + return registerFood(itemId, builder.build()); } - public Item registerFood(String name, FoodProperties foodComponent) { - return register(name, new ModelProviderItem(makeItemSettings().food(foodComponent))); + public Item registerFood(ResourceLocation itemId, FoodProperties foodComponent) { + return register(itemId, new ModelProviderItem(makeItemSettings().food(foodComponent))); } - public Item registerDrink(String name) { - return register(name, new BaseDrinkItem(makeItemSettings().stacksTo(1))); + public Item registerDrink(ResourceLocation itemId, FoodProperties foodComponent) { + return register(itemId, new BaseDrinkItem(makeItemSettings().stacksTo(1).food(foodComponent))); } - public Item registerDrink(String name, FoodProperties foodComponent) { - return register(name, new BaseDrinkItem(makeItemSettings().stacksTo(1).food(foodComponent))); - } - - public Item registerDrink(String name, int hunger, float saturation) { + public Item registerDrink(ResourceLocation itemId, int hunger, float saturation) { FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); - return registerDrink(name, builder.build()); + return registerDrink(itemId, builder.build()); + } + + @Override + public void registerItem(ResourceLocation id, Item item) { + if (item != null && item != Items.AIR) { + Registry.register(Registry.ITEM, id, item); + getModItems(id.getNamespace()).add(item); + } + } + + public Item register(ResourceLocation itemId, Item item, String category) { + if (config.getBoolean(category, itemId.getPath(), true)) { + registerItem(itemId, item); + } + return item; } } From d33cb707fd03459f8e447933ac3a7d469ec9e24c Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 28 Oct 2021 17:37:58 +0300 Subject: [PATCH 25/53] Biome def sky color --- .../ru/bclib/world/biomes/BCLBiomeDef.java | 41 +++++++++++++------ 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java index bd661334..11751e55 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java @@ -65,6 +65,7 @@ public class BCLBiomeDef { private int waterFogColor = 329011; private int waterColor = 4159204; private int fogColor = 10518688; + private int skyColor = 0; private float fogDensity = 1F; private float depth = 0.1F; @@ -242,11 +243,24 @@ public class BCLBiomeDef { return ColorUtil.color(r, g, b); } - public BCLBiomeDef setFogColor(int r, int g, int b) { - this.fogColor = getColor(r, g, b); + public BCLBiomeDef setSkyColor(int rgb) { + this.skyColor = rgb; return this; } + public BCLBiomeDef setSkyColor(int r, int g, int b) { + return setSkyColor(getColor(r, g, b)); + } + + public BCLBiomeDef setFogColor(int rgb) { + this.fogColor = rgb; + return this; + } + + public BCLBiomeDef setFogColor(int r, int g, int b) { + return setFogColor(getColor(r, g, b)); + } + public BCLBiomeDef setFogDensity(float density) { this.fogDensity = density; return this; @@ -327,7 +341,7 @@ public class BCLBiomeDef { addCustomToBuild(generationSettings); - effects.skyColor(0) + effects.skyColor(skyColor) .waterColor(waterColor) .waterFogColor(waterFogColor) .fogColor(fogColor) @@ -339,16 +353,17 @@ public class BCLBiomeDef { if (particleConfig != null) effects.ambientParticle(particleConfig); effects.backgroundMusic(music != null ? new Music(music, 600, 2400, true) : Musics.END); - return new Biome.BiomeBuilder().precipitation(precipitation) - .biomeCategory(category) - .depth(depth) - .scale(0.2F) - .temperature(temperature) - .downfall(downfall) - .specialEffects(effects.build()) - .mobSpawnSettings(spawnSettings.build()) - .generationSettings(generationSettings.build()) - .build(); + return new Biome.BiomeBuilder() + .precipitation(precipitation) + .biomeCategory(category) + .depth(depth) + .scale(0.2F) + .temperature(temperature) + .downfall(downfall) + .specialEffects(effects.build()) + .mobSpawnSettings(spawnSettings.build()) + .generationSettings(generationSettings.build()) + .build(); } private static final class SpawnInfo { From cf31d76ee1494741be6c32d1179593ff13be224e Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 30 Oct 2021 15:00:43 +0200 Subject: [PATCH 26/53] added `c:immobile` for unmovable blocks like obsidian --- src/main/java/ru/bclib/api/TagAPI.java | 1 + .../mixin/common/PistonBaseBlockMixin.java | 23 +++++++++++++++++++ ...BlockMixi.java => TripWireBlockMixin.java} | 0 src/main/resources/bclib.mixins.common.json | 5 ++-- 4 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java rename src/main/java/ru/bclib/mixin/common/shears/{TripWireBlockMixi.java => TripWireBlockMixin.java} (100%) diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 1832ec67..a3956e46 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -43,6 +43,7 @@ public class TagAPI { public static final Tag.Named BLOCK_WORKBENCHES = makeCommonBlockTag("workbench"); public static final Tag.Named BLOCK_SAPLINGS = makeCommonBlockTag("saplings"); public static final Tag.Named BLOCK_LEAVES = makeCommonBlockTag("leaves"); + public static final Tag.Named BLOCK_IMMOBILE = makeCommonBlockTag("immobile"); public static final Tag.Named BLOCK_DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); diff --git a/src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java b/src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java new file mode 100644 index 00000000..ae2d3a02 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java @@ -0,0 +1,23 @@ +package ru.bclib.mixin.common; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; +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.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import ru.bclib.api.TagAPI; + +@Mixin(PistonBaseBlock.class) +public class PistonBaseBlockMixin { + @Inject(method="isPushable", at=@At("HEAD"), cancellable = true) + private static void bclib_isPushable(BlockState blockState, Level level, BlockPos blockPos, Direction direction, boolean bl, Direction direction2, CallbackInfoReturnable cir){ + if (blockState.is(TagAPI.BLOCK_IMMOBILE)){ + cir.setReturnValue(false); + cir.cancel(); + } + } +} diff --git a/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixi.java b/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java similarity index 100% rename from src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixi.java rename to src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index f312d6ec..cda8afe9 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -27,8 +27,9 @@ "shears.PumpkinBlockMixin", "shears.SheepMixin", "shears.SnowGolemMixin", - "shears.TripWireBlockMixi", - "PortalShapeMixin" + "shears.TripWireBlockMixin", + "PortalShapeMixin", + "PistonBaseBlockMixin" ], "injectors": { "defaultRequire": 1 From 2518759f7b09f8dd4e3fe8e4684caa5a49756c58 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 30 Oct 2021 15:00:52 +0200 Subject: [PATCH 27/53] Fixed name --- .../java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java b/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java index 1f3bfb1c..acc98049 100644 --- a/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java +++ b/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java @@ -9,7 +9,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import ru.bclib.items.tool.BaseShearsItem; @Mixin(TripWireBlock.class) -public class TripWireBlockMixi { +public class TripWireBlockMixin { @Redirect(method="playerWillDestroy", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) public boolean bn_useProxy(ItemStack itemStack, Item item){ return BaseShearsItem.isShear(itemStack, item); From 8eba063b403be6c9e79a3485ce48416c7cb253cf Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 1 Nov 2021 14:16:17 +0300 Subject: [PATCH 28/53] Import optimisation, carver adding fix --- .../org/anti_ad/mc/ipn/api/IPNIgnore.java | 5 +++- src/main/java/ru/bclib/BCLib.java | 4 +-- src/main/java/ru/bclib/api/TagAPI.java | 9 +++--- .../handler/autosync/Chunker.java | 2 +- .../bclib/api/datafixer/MigrationProfile.java | 1 - .../java/ru/bclib/blocks/BaseLeavesBlock.java | 9 +++--- .../ru/bclib/blocks/FeatureSaplingBlock.java | 29 ------------------- .../blocks/FeatureSaplingBlockCommon.java | 4 --- .../ru/bclib/client/models/ModelsHelper.java | 9 +++--- .../render/CustomBackgroundRenderer.java | 1 - .../ru/bclib/gui/gridlayout/GridScreen.java | 2 -- .../ru/bclib/gui/screens/BCLibScreen.java | 1 - .../gui/screens/WarnBCLibVersionMismatch.java | 1 - .../AnvilScreenHandlerExtended.java | 4 +-- .../bclib/mixin/client/AnvilScreenMixin.java | 5 ++-- .../ru/bclib/mixin/common/AnvilMenuMixin.java | 11 ++++--- .../java/ru/bclib/recipes/AnvilRecipe.java | 5 ++-- src/main/java/ru/bclib/util/ItemUtil.java | 6 ++-- src/main/java/ru/bclib/util/ModUtil.java | 1 - .../ru/bclib/world/biomes/BCLBiomeDef.java | 6 ++-- src/main/resources/bclib.mixins.client.json | 6 ++-- src/main/resources/bclib.mixins.common.json | 22 +++++++------- 22 files changed, 49 insertions(+), 94 deletions(-) diff --git a/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java b/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java index b01c8a3f..9cc8f4fa 100644 --- a/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java +++ b/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java @@ -1,6 +1,9 @@ package org.anti_ad.mc.ipn.api; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; // Included from "Inventory Profiles Next" (https://github.com/blackd/Inventory-Profiles) @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index d413f140..f5f6eb3c 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -1,7 +1,5 @@ package ru.bclib; -import java.util.List; - import net.fabricmc.api.EnvType; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; @@ -25,6 +23,8 @@ import ru.bclib.world.generator.BCLibNetherBiomeSource; import ru.bclib.world.generator.GeneratorOptions; import ru.bclib.world.surface.BCLSurfaceBuilders; +import java.util.List; + public class BCLib implements ModInitializer { public static final String MOD_ID = "bclib"; public static final Logger LOGGER = new Logger(MOD_ID); diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index a3956e46..6da6e070 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,12 +1,7 @@ package ru.bclib.api; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; - import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import net.fabricmc.fabric.api.tag.TagRegistry; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; @@ -23,6 +18,10 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + public class TagAPI { private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/Chunker.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/Chunker.java index 19b3f1e7..33a16719 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/Chunker.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/Chunker.java @@ -4,10 +4,10 @@ import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.client.Minecraft; -import net.minecraft.util.ProgressListener; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.ProgressListener; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java index 3cc514ce..6ad9dd58 100644 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -1,6 +1,5 @@ package ru.bclib.api.datafixer; -import net.fabricmc.loom.util.ModUtils; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtIo; diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 2ded221e..3dd32197 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -1,11 +1,6 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - 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.client.renderer.block.model.BlockModel; @@ -25,6 +20,10 @@ import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.util.MHelper; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider { protected final Block sapling; diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index 670d041c..f0045a0e 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -1,40 +1,11 @@ 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.client.renderer.block.model.BlockModel; import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.SaplingBlock; -import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import org.jetbrains.annotations.Nullable; -import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.ModelsHelper; -import ru.bclib.client.models.PatternsHelper; -import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Random; @SuppressWarnings("deprecation") public abstract class FeatureSaplingBlock extends FeatureSaplingBlockCommon { diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java index 032424d4..fcc7f3af 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java @@ -9,10 +9,8 @@ import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.SaplingBlock; import net.minecraft.world.level.block.SoundType; @@ -21,8 +19,6 @@ import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index 267345ea..8b99b720 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -1,11 +1,6 @@ package ru.bclib.client.models; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - import com.google.common.collect.Lists; - import com.mojang.math.Transformation; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -22,6 +17,10 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + @Environment(EnvType.CLIENT) public class ModelsHelper { public static BlockModel fromPattern(Optional pattern) { diff --git a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java index 5a37032b..1828ad51 100644 --- a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java +++ b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java @@ -12,7 +12,6 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.material.FogType; import ru.bclib.api.BiomeAPI; import ru.bclib.util.BackgroundInfo; diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java b/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java index 73f4d0f5..663ca0dd 100644 --- a/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java +++ b/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java @@ -9,8 +9,6 @@ import com.mojang.blaze3d.vertex.VertexFormat; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.components.AbstractSelectionList; -import net.minecraft.client.gui.components.OptionsList; import net.minecraft.client.gui.components.Widget; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.narration.NarratableEntry; diff --git a/src/main/java/ru/bclib/gui/screens/BCLibScreen.java b/src/main/java/ru/bclib/gui/screens/BCLibScreen.java index b25c3bbe..bf95d7c4 100644 --- a/src/main/java/ru/bclib/gui/screens/BCLibScreen.java +++ b/src/main/java/ru/bclib/gui/screens/BCLibScreen.java @@ -1,6 +1,5 @@ package ru.bclib.gui.screens; -import com.mojang.blaze3d.vertex.PoseStack; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.gui.screens.Screen; diff --git a/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java b/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java index 05b48c4d..37d3f1c6 100644 --- a/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java +++ b/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java @@ -7,7 +7,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import ru.bclib.gui.gridlayout.GridLayout.Alignment; import ru.bclib.gui.gridlayout.GridRow; -import ru.bclib.gui.gridlayout.GridScreen; @Environment(EnvType.CLIENT) public class WarnBCLibVersionMismatch extends BCLibScreen { diff --git a/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java b/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java index 5194c1ef..c7d3637e 100644 --- a/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java +++ b/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java @@ -1,10 +1,10 @@ package ru.bclib.interfaces; -import java.util.List; - import ru.bclib.recipes.AnvilRecipe; +import java.util.List; + public interface AnvilScreenHandlerExtended { void be_updateCurrentRecipe(AnvilRecipe recipe); diff --git a/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java b/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java index 9baa2237..b60df8b4 100644 --- a/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java +++ b/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java @@ -1,9 +1,6 @@ package ru.bclib.mixin.client; -import java.util.List; - import com.google.common.collect.Lists; - import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.Button; @@ -24,6 +21,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.interfaces.AnvilScreenHandlerExtended; +import java.util.List; + @Mixin(AnvilScreen.class) public class AnvilScreenMixin extends ItemCombinerScreen { diff --git a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java index 85318e78..5d5d9218 100644 --- a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java @@ -1,11 +1,5 @@ package ru.bclib.mixin.common; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.jetbrains.annotations.Nullable; - import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -18,6 +12,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -30,6 +25,10 @@ import ru.bclib.blocks.LeveledAnvilBlock; import ru.bclib.interfaces.AnvilScreenHandlerExtended; import ru.bclib.recipes.AnvilRecipe; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + @Mixin(AnvilMenu.class) public abstract class AnvilMenuMixin extends ItemCombinerMenu implements AnvilScreenHandlerExtended { private List be_recipes = Collections.emptyList(); diff --git a/src/main/java/ru/bclib/recipes/AnvilRecipe.java b/src/main/java/ru/bclib/recipes/AnvilRecipe.java index 20e27f65..378a7fd9 100644 --- a/src/main/java/ru/bclib/recipes/AnvilRecipe.java +++ b/src/main/java/ru/bclib/recipes/AnvilRecipe.java @@ -1,9 +1,6 @@ package ru.bclib.recipes; -import java.util.Objects; - import com.google.gson.JsonObject; - import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -33,6 +30,8 @@ import ru.bclib.interfaces.UnknownReceipBookCategory; import ru.bclib.util.ItemUtil; import ru.bclib.util.RecipeHelper; +import java.util.Objects; + public class AnvilRecipe implements Recipe, UnknownReceipBookCategory { public final static String GROUP = "smithing"; public final static RecipeType TYPE = BCLRecipeManager.registerType(BCLib.MOD_ID, GROUP); diff --git a/src/main/java/ru/bclib/util/ItemUtil.java b/src/main/java/ru/bclib/util/ItemUtil.java index c3535ccd..fd639a3b 100644 --- a/src/main/java/ru/bclib/util/ItemUtil.java +++ b/src/main/java/ru/bclib/util/ItemUtil.java @@ -1,15 +1,13 @@ package ru.bclib.util; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - import com.google.gson.JsonObject; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.GsonHelper; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; public class ItemUtil { diff --git a/src/main/java/ru/bclib/util/ModUtil.java b/src/main/java/ru/bclib/util/ModUtil.java index db873bc5..f7d0c1f1 100644 --- a/src/main/java/ru/bclib/util/ModUtil.java +++ b/src/main/java/ru/bclib/util/ModUtil.java @@ -19,7 +19,6 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; -import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java index 11751e55..60ced512 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java @@ -378,9 +378,9 @@ public class BCLBiomeDef { ConfiguredFeature feature; } - private static final class CarverInfo { + private static final class CarverInfo { Carving carverStep; - ConfiguredWorldCarver carver; + ConfiguredWorldCarver carver; } public ResourceLocation getID() { @@ -399,7 +399,7 @@ public class BCLBiomeDef { return edgeSize; } - public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { + public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { CarverInfo info = new CarverInfo(); info.carverStep = carverStep; info.carver = carver; diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index 677e5ede..b3aebf4a 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -7,13 +7,13 @@ "SimpleReloadableResourceManagerMixin", "EnchantingTableBlockMixin", "BackgroundRendererMixin", + "ClientRecipeBookMixin", "ModelManagerMixin", "TextureAtlasMixin", + "AnvilScreenMixin", "ModelBakeryMixin", "MinecraftMixin", - "GameMixin", - "AnvilScreenMixin", - "ClientRecipeBookMixin" + "GameMixin" ], "injectors": { "defaultRequire": 1 diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index cda8afe9..c449923b 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -5,31 +5,31 @@ "compatibilityLevel": "JAVA_16", "mixins": [ "SimpleReloadableResourceManagerMixin", - "InternalBiomeDataMixin", + "shears.DiggingEnchantmentMixin", + "shears.TripWireBlockMixin", + "shears.BeehiveBlockMixin", + "shears.PumpkinBlockMixin", + "shears.MushroomCowMixin", + "shears.SnowGolemMixin", "ComposterBlockAccessor", + "InternalBiomeDataMixin", "PotionBrewingAccessor", "RecipeManagerAccessor", "EnchantmentMenuMixin", "MinecraftServerMixin", + "PistonBaseBlockMixin", "WorldGenRegionMixin", "DimensionTypeMixin", "RecipeManagerMixin", "BoneMealItemMixin", + "shears.SheepMixin", + "PortalShapeMixin", "ServerLevelMixin", "AnvilBlockMixin", "AnvilMenuMixin", "TagLoaderMixin", "BiomeMixin", - "MainMixin", - "shears.BeehiveBlockMixin", - "shears.DiggingEnchantmentMixin", - "shears.MushroomCowMixin", - "shears.PumpkinBlockMixin", - "shears.SheepMixin", - "shears.SnowGolemMixin", - "shears.TripWireBlockMixin", - "PortalShapeMixin", - "PistonBaseBlockMixin" + "MainMixin" ], "injectors": { "defaultRequire": 1 From 3efa71b08af84027178f51432bf60b023024910f Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 2 Nov 2021 15:25:08 +0300 Subject: [PATCH 29/53] Null pointer translation fix --- src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java | 2 +- src/main/java/ru/bclib/gui/gridlayout/GridCell.java | 2 +- src/main/java/ru/bclib/gui/gridlayout/GridLayout.java | 2 +- src/main/java/ru/bclib/{util => interfaces}/TriConsumer.java | 2 +- src/main/java/ru/bclib/util/TranslationHelper.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) rename src/main/java/ru/bclib/{util => interfaces}/TriConsumer.java (76%) diff --git a/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java index d91a7ca8..d3c08420 100644 --- a/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java +++ b/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java @@ -3,7 +3,7 @@ package ru.bclib.complexmaterials.entry; import net.minecraft.resources.ResourceLocation; import ru.bclib.complexmaterials.ComplexMaterial; import ru.bclib.config.PathConfig; -import ru.bclib.util.TriConsumer; +import ru.bclib.interfaces.TriConsumer; public class RecipeEntry extends ComplexMaterialEntry { final TriConsumer initFunction; diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridCell.java index f3912879..6e99bbea 100644 --- a/src/main/java/ru/bclib/gui/gridlayout/GridCell.java +++ b/src/main/java/ru/bclib/gui/gridlayout/GridCell.java @@ -3,7 +3,7 @@ package ru.bclib.gui.gridlayout; import com.mojang.blaze3d.vertex.PoseStack; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import ru.bclib.util.TriConsumer; +import ru.bclib.interfaces.TriConsumer; import java.util.List; import java.util.function.Function; diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java index a44cf0f0..4a2b50d1 100644 --- a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java +++ b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java @@ -6,7 +6,7 @@ import net.fabricmc.api.Environment; import net.minecraft.client.gui.components.AbstractWidget; import ru.bclib.gui.gridlayout.GridLayout.GridValueType; import ru.bclib.util.Pair; -import ru.bclib.util.TriConsumer; +import ru.bclib.interfaces.TriConsumer; import java.util.LinkedList; import java.util.List; diff --git a/src/main/java/ru/bclib/util/TriConsumer.java b/src/main/java/ru/bclib/interfaces/TriConsumer.java similarity index 76% rename from src/main/java/ru/bclib/util/TriConsumer.java rename to src/main/java/ru/bclib/interfaces/TriConsumer.java index 6e5ac17c..dab5678f 100644 --- a/src/main/java/ru/bclib/util/TriConsumer.java +++ b/src/main/java/ru/bclib/interfaces/TriConsumer.java @@ -1,4 +1,4 @@ -package ru.bclib.util; +package ru.bclib.interfaces; @FunctionalInterface public interface TriConsumer { diff --git a/src/main/java/ru/bclib/util/TranslationHelper.java b/src/main/java/ru/bclib/util/TranslationHelper.java index bb1b5735..d85a07ba 100644 --- a/src/main/java/ru/bclib/util/TranslationHelper.java +++ b/src/main/java/ru/bclib/util/TranslationHelper.java @@ -30,7 +30,7 @@ public class TranslationHelper { Gson gson = new Gson(); InputStream inputStream = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/" + languageCode + ".json"); - JsonObject translation = gson.fromJson(new InputStreamReader(inputStream), JsonObject.class); + JsonObject translation = inputStream == null ? new JsonObject() : gson.fromJson(new InputStreamReader(inputStream), JsonObject.class); Registry.BLOCK.forEach(block -> { if (Registry.BLOCK.getKey(block).getNamespace().equals(modID)) { From b7c83923ea70de3e59fdd8364df4bfb03a32cbdc Mon Sep 17 00:00:00 2001 From: Frank Date: Wed, 3 Nov 2021 15:44:25 +0100 Subject: [PATCH 30/53] Using latest fabric API --- gradle.properties | 4 ++-- src/main/java/ru/bclib/util/ModUtil.java | 17 ++++++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/gradle.properties b/gradle.properties index 34e75d23..7b851705 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,8 +7,8 @@ loom_version=0.8-SNAPSHOT # Fabric Properties # check these on https://fabricmc.net/versions.html minecraft_version= 1.17.1 -loader_version= 0.11.6 -fabric_version = 0.39.1+1.17 +loader_version= 0.12.4 +fabric_version = 0.41.3+1.17 # Mod Properties mod_version = 0.4.2 diff --git a/src/main/java/ru/bclib/util/ModUtil.java b/src/main/java/ru/bclib/util/ModUtil.java index f7d0c1f1..0dd8e733 100644 --- a/src/main/java/ru/bclib/util/ModUtil.java +++ b/src/main/java/ru/bclib/util/ModUtil.java @@ -5,17 +5,18 @@ import net.fabricmc.loader.api.ModContainer; import net.fabricmc.loader.api.SemanticVersion; import net.fabricmc.loader.api.Version; import net.fabricmc.loader.api.metadata.ModMetadata; -import net.fabricmc.loader.metadata.ModMetadataParser; -import net.fabricmc.loader.metadata.ParseMetadataException; +import net.fabricmc.loader.impl.metadata.ModMetadataParser; import org.apache.logging.log4j.LogManager; import ru.bclib.BCLib; -import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.nio.file.FileSystem; import java.nio.file.FileSystems; +import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; +import java.util.LinkedList; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -55,15 +56,17 @@ public class ModUtil { try { Path modMetaFile = fs.getPath("fabric.mod.json"); if (modMetaFile != null) { - ModMetadata mc = ModMetadataParser.parseMetadata(logger, modMetaFile); - mods.put(mc.getId(), new ModInfo(mc, file)); + try (InputStream is = Files.newInputStream(modMetaFile)) { + ModMetadata mc = ModMetadataParser.parseMetadata(is, uri.toString(), new LinkedList()); + mods.put(mc.getId(), new ModInfo(mc, file)); + } } - } catch (ParseMetadataException e) { + } catch (Exception e) { BCLib.LOGGER.error(e.getMessage()); } } } - catch (IOException e) { + catch (Exception e) { BCLib.LOGGER.error(e.getMessage()); } })); From 383346942f6679a5108e435acc25e919b3c18246 Mon Sep 17 00:00:00 2001 From: Frank Date: Wed, 3 Nov 2021 15:45:34 +0100 Subject: [PATCH 31/53] Updated fabric dependencies --- src/main/resources/fabric.mod.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 9ec07e33..1399c672 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -34,8 +34,8 @@ "bclib.mixins.client.json" ], "depends": { - "fabricloader": ">=0.11.6", - "fabric": ">=0.36.0", + "fabricloader": ">=0.12.0", + "fabric": ">=0.41.0", "minecraft": ">=1.17.1" }, "custom":{ From cca21cd727b1fdce43018ae6c09b752d3e97273c Mon Sep 17 00:00:00 2001 From: Frank Date: Wed, 3 Nov 2021 16:08:58 +0100 Subject: [PATCH 32/53] Bumped Version and reduced loader dependency (#34) --- gradle.properties | 2 +- src/main/resources/fabric.mod.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 7b851705..0dfe5a9f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ loader_version= 0.12.4 fabric_version = 0.41.3+1.17 # Mod Properties -mod_version = 0.4.2 +mod_version = 0.4.3 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 1399c672..d49eb0a9 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -34,7 +34,7 @@ "bclib.mixins.client.json" ], "depends": { - "fabricloader": ">=0.12.0", + "fabricloader": ">=0.11.6", "fabric": ">=0.41.0", "minecraft": ">=1.17.1" }, From dfad74f4a07faa562211cefbee5462447aeb1af2 Mon Sep 17 00:00:00 2001 From: Frank Date: Wed, 3 Nov 2021 16:35:52 +0100 Subject: [PATCH 33/53] Remove BCLib Version Warning screen when user clicks NO --- .../bclib/api/dataexchange/handler/autosync/HelloClient.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java index 1c25eb37..0d24997c 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java @@ -394,6 +394,9 @@ public class HelloClient extends DataHandler.FromServer { requestBCLibDownload(); this.onCloseSyncFilesScreen(); + } else { + Minecraft.getInstance() + .setScreen(null); } })); } From 9a237f52f56238ef595c57e54f6e7e573ba1e2d6 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 4 Nov 2021 00:53:10 +0100 Subject: [PATCH 34/53] increased fabricloader version (#36, #34) --- src/main/resources/fabric.mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index d49eb0a9..c059350d 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -34,7 +34,7 @@ "bclib.mixins.client.json" ], "depends": { - "fabricloader": ">=0.11.6", + "fabricloader": ">=0.12.4", "fabric": ">=0.41.0", "minecraft": ">=1.17.1" }, From 143653e2b65b24373377d30cb1d0fd71aad6b252 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 4 Nov 2021 02:18:33 +0100 Subject: [PATCH 35/53] Custom parsing of relevant Mod-Info. Should make it compatible with loader 0.11.x and 0.12.x (#34, #36) --- src/main/java/ru/bclib/util/ModUtil.java | 179 ++++++++++++++++++++++- src/main/resources/fabric.mod.json | 2 +- 2 files changed, 176 insertions(+), 5 deletions(-) diff --git a/src/main/java/ru/bclib/util/ModUtil.java b/src/main/java/ru/bclib/util/ModUtil.java index 0dd8e733..05c0b596 100644 --- a/src/main/java/ru/bclib/util/ModUtil.java +++ b/src/main/java/ru/bclib/util/ModUtil.java @@ -1,22 +1,36 @@ package ru.bclib.util; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.stream.JsonReader; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; import net.fabricmc.loader.api.SemanticVersion; import net.fabricmc.loader.api.Version; +import net.fabricmc.loader.api.VersionParsingException; +import net.fabricmc.loader.api.metadata.ContactInformation; +import net.fabricmc.loader.api.metadata.CustomValue; +import net.fabricmc.loader.api.metadata.ModDependency; +import net.fabricmc.loader.api.metadata.ModEnvironment; import net.fabricmc.loader.api.metadata.ModMetadata; -import net.fabricmc.loader.impl.metadata.ModMetadataParser; +import net.fabricmc.loader.api.metadata.Person; +import net.fabricmc.loader.util.version.SemanticVersionImpl; import org.apache.logging.log4j.LogManager; import ru.bclib.BCLib; +import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; -import java.util.LinkedList; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -57,8 +71,11 @@ public class ModUtil { Path modMetaFile = fs.getPath("fabric.mod.json"); if (modMetaFile != null) { try (InputStream is = Files.newInputStream(modMetaFile)) { - ModMetadata mc = ModMetadataParser.parseMetadata(is, uri.toString(), new LinkedList()); - mods.put(mc.getId(), new ModInfo(mc, file)); + //ModMetadata mc = ModMetadataParser.parseMetadata(is, uri.toString(), new LinkedList()); + ModMetadata mc = readJSON(is, uri.toString()); + if (mc!=null){ + mods.put(mc.getId(), new ModInfo(mc, file)); + } } } } catch (Exception e) { @@ -74,6 +91,160 @@ public class ModUtil { return mods; } + private static ModMetadata readJSON(InputStream is, String sourceFile) throws IOException { + try (com.google.gson.stream.JsonReader reader = new JsonReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + JsonObject data = new JsonParser().parse(reader).getAsJsonObject(); + Version ver; + try { + ver = new SemanticVersionImpl(data.get("version").getAsString(), false); + } + catch (VersionParsingException e) { + BCLib.LOGGER.error("Unable to parse Version in " + sourceFile); + return null; + } + + if (data.get("id") == null){ + BCLib.LOGGER.error("Unable to read ID in " + sourceFile); + return null; + } + + if (data.get("name") == null){ + BCLib.LOGGER.error("Unable to read name in " + sourceFile); + return null; + } + + return new ModMetadata() { + @Override + public Version getVersion() { + return ver; + } + @Override + public String getType() { + return "fabric"; + } + + @Override + public String getId() { + return data.get("id").getAsString(); + } + + @Override + public Collection getProvides() { + return new ArrayList<>(); + } + + @Override + public ModEnvironment getEnvironment() { + JsonElement env = data.get("environment"); + if (env==null) { + BCLib.LOGGER.error("No environment specified in " + sourceFile); + return ModEnvironment.UNIVERSAL; + } + final String environment = env.getAsString().toLowerCase(Locale.ROOT); + + if (environment.isEmpty() || environment.equals("*") || environment.equals("common")) { + return ModEnvironment.UNIVERSAL; + } else if (environment.equals("client")) { + return ModEnvironment.CLIENT; + } else if (environment.equals("server")) { + return ModEnvironment.SERVER; + } else { + BCLib.LOGGER.error("Unable to read environment in " + sourceFile); + return ModEnvironment.UNIVERSAL; + } + } + + @Override + public Collection getDepends() { + return new ArrayList<>(); + } + + @Override + public Collection getRecommends() { + return new ArrayList<>(); + } + + @Override + public Collection getSuggests() { + return new ArrayList<>(); + } + + @Override + public Collection getConflicts() { + return new ArrayList<>(); + } + + @Override + public Collection getBreaks() { + return new ArrayList<>(); + } + + public Collection getDependencies() { + return new ArrayList<>(); + } + + @Override + public String getName() { + return data.get("name").getAsString(); + } + + @Override + public String getDescription() { + return ""; + } + + @Override + public Collection getAuthors() { + return new ArrayList<>(); + } + + @Override + public Collection getContributors() { + return new ArrayList<>(); + } + + @Override + public ContactInformation getContact() { + return null; + } + + @Override + public Collection getLicense() { + return new ArrayList<>(); + } + + @Override + public Optional getIconPath(int size) { + return Optional.empty(); + } + + @Override + public boolean containsCustomValue(String key) { + return false; + } + + @Override + public CustomValue getCustomValue(String key) { + return null; + } + + @Override + public Map getCustomValues() { + return new HashMap<>(); + } + + @Override + public boolean containsCustomElement(String key) { + return false; + } + + public JsonElement getCustomElement(String key) { + return null; + } + }; + } + } + /** * Returns the {@link ModInfo} or {@code null} if the mod was not found. *

diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index c059350d..d49eb0a9 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -34,7 +34,7 @@ "bclib.mixins.client.json" ], "depends": { - "fabricloader": ">=0.12.4", + "fabricloader": ">=0.11.6", "fabric": ">=0.41.0", "minecraft": ">=1.17.1" }, From 03bef36a45ce71537e9d014bd2c1ac044b39054b Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 4 Nov 2021 02:34:41 +0100 Subject: [PATCH 36/53] Updated Version --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 0dfe5a9f..096d2710 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ loader_version= 0.12.4 fabric_version = 0.41.3+1.17 # Mod Properties -mod_version = 0.4.3 +mod_version = 0.4.4 maven_group = ru.bclib archives_base_name = bclib From 03e8733ba0f95fc20672348eafec515e1362af0c Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 11:25:48 +0100 Subject: [PATCH 37/53] Add UI that presents Fixer Errors to the User(paulevsGitch/BetterNether#436) --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 69 ++++++++++++++++--- .../gui/screens/LevelFixErrorScreen.java | 60 ++++++++++++++++ .../ru/bclib/gui/screens/ModListScreen.java | 1 - .../ru/bclib/mixin/client/MinecraftMixin.java | 2 +- .../resources/assets/bclib/lang/de_de.json | 5 +- .../resources/assets/bclib/lang/en_us.json | 5 +- 6 files changed, 127 insertions(+), 15 deletions(-) create mode 100644 src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 088a01ba..b58f0f5b 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -25,6 +25,7 @@ import ru.bclib.api.WorldDataAPI; import ru.bclib.config.Configs; import ru.bclib.gui.screens.AtomicProgressListener; import ru.bclib.gui.screens.ConfirmFixScreen; +import ru.bclib.gui.screens.LevelFixErrorScreen; import ru.bclib.gui.screens.ProgressScreen; import ru.bclib.util.Logger; @@ -47,6 +48,24 @@ public class DataFixerAPI { static final Logger LOGGER = new Logger("DataFixerAPI"); static class State { public boolean didFail = false; + protected ArrayList errors = new ArrayList<>(); + + public void addError(String s){ + errors.add(s); + } + + public boolean hasError(){ + return errors.size()>0; + } + + public String getErrorMessage(){ + return errors.stream().reduce("", (a, b) -> a + " - " + b + "\n"); + } + + public String[] getErrorMessages(){ + String[] res = new String[errors.size()]; + return errors.toArray(res); + } } @FunctionalInterface @@ -200,30 +219,51 @@ public class DataFixerAPI { progress = null; } - Runnable runner = () -> { + Supplier runner = () -> { if (createBackup) { progress.progressStage(new TranslatableComponent("message.bclib.datafixer.progress.waitbackup")); EditWorldScreen.makeBackupAndShowToast(Minecraft.getInstance().getLevelSource(), levelID); } if (applyFixes) { - runDataFixes(dir, profile, progress); + return runDataFixes(dir, profile, progress); } + + return new State(); }; if (showUI) { Thread fixerThread = new Thread(() -> { - runner.run(); - - Minecraft.getInstance().execute(() -> { - if (profile != null && showUI) { - onResume.accept(applyFixes); - } - }); + State state = runner.get(); + for (int i=0; i<20; i++) + state.addError("Hello World"); + + Minecraft.getInstance() + .execute(() -> { + if (profile != null && showUI) { + //something went wrong, show the user our error + if (state.didFail || state.hasError()){ + Minecraft.getInstance() + .setScreen(new LevelFixErrorScreen(Minecraft.getInstance().screen, state.getErrorMessages(), (markFixed)->{ + if (markFixed) { + profile.markApplied(); + } + onResume.accept(applyFixes); + })); + } else { + onResume.accept(applyFixes); + } + } + }); + }); fixerThread.start(); } else { - runner.run(); + State state = runner.get(); + if (state.hasError()){ + LOGGER.error("There were Errors while fixing the Level:"); + LOGGER.error(state.getErrorMessage()); + } } }; @@ -270,7 +310,7 @@ public class DataFixerAPI { Minecraft.getInstance().setScreen(new ConfirmFixScreen((Screen) null, whenFinished::accept)); } - private static void runDataFixes(File dir, MigrationProfile profile, AtomicProgressListener progress) { + private static State runDataFixes(File dir, MigrationProfile profile, AtomicProgressListener progress) { State state = new State(); progress.resetAtomic(); @@ -295,6 +335,7 @@ public class DataFixerAPI { profile.patchWorldData(); } catch (PatchDidiFailException e){ state.didFail = true; + state.addError("Failed fixing worldconfig (" + e.getMessage() + ")"); BCLib.LOGGER.error(e.getMessage()); } progress.incAtomic(maxProgress); @@ -313,6 +354,8 @@ public class DataFixerAPI { progress.incAtomic(maxProgress); progress.stop(); + + return state; } private static void fixLevel(MigrationProfile profile, State state, File levelBaseDir) { @@ -342,6 +385,7 @@ public class DataFixerAPI { } catch (Exception e) { BCLib.LOGGER.error("Failed fixing Level-Data."); + state.addError("Failed fixing Level-Data in level.dat (" + e.getMessage() + ")"); state.didFail = true; e.printStackTrace(); } @@ -361,6 +405,7 @@ public class DataFixerAPI { } catch (Exception e) { BCLib.LOGGER.error("Failed fixing Player-Data."); + state.addError("Failed fixing Player-Data in " + file.getName() + " (" + e.getMessage() + ")"); state.didFail = true; e.printStackTrace(); } @@ -448,6 +493,7 @@ public class DataFixerAPI { } catch (PatchDidiFailException e) { BCLib.LOGGER.error("Failed fixing BlockState in " + pos); + state.addError("Failed fixing BlockState in " + pos + " (" + e.getMessage() + ")"); state.didFail = true; changed[0] = false; e.printStackTrace(); @@ -468,6 +514,7 @@ public class DataFixerAPI { } catch (Exception e) { BCLib.LOGGER.error("Failed fixing Region."); + state.addError("Failed fixing Region in " + file.getName() + " (" + e.getMessage() + ")"); state.didFail = true; e.printStackTrace(); } diff --git a/src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java b/src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java new file mode 100644 index 00000000..1615c0f2 --- /dev/null +++ b/src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java @@ -0,0 +1,60 @@ +package ru.bclib.gui.screens; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import ru.bclib.gui.gridlayout.GridColumn; +import ru.bclib.gui.gridlayout.GridLayout; +import ru.bclib.gui.gridlayout.GridRow; + +@Environment(EnvType.CLIENT) +public class LevelFixErrorScreen extends BCLibScreen { + private final String[] errors; + final Listener onContinue; + + public LevelFixErrorScreen(Screen parent, String[] errors, Listener onContinue) { + super(parent, new TranslatableComponent("title.bclib.datafixer.error"), 10, true); + this.errors = errors; + this.onContinue = onContinue; + } + + @Override + protected void initLayout() { + grid.addSpacerRow(); + grid.addRow().addMessage(new TranslatableComponent("message.bclib.datafixer.error"), font, GridLayout.Alignment.CENTER); + grid.addSpacerRow(8); + + GridRow row = grid.addRow(); + row.addSpacer(10); + GridColumn col = row.addColumn(300, GridLayout.GridValueType.CONSTANT); + for (String error : errors){ + TextComponent dash = new TextComponent("-"); + row = col.addRow(); + row.addString(dash, this); + + row.addSpacer(4); + row.addString(new TextComponent(error), this); + } + + grid.addSpacerRow(8); + row = grid.addRow(); + row.addFiller(); + row.addButton(new TranslatableComponent("title.bclib.datafixer.error.continue"), 0.5f, 20, font, (n)-> { + onClose(); + onContinue.doContinue(true); + }); + row.addSpacer(); + row.addButton(CommonComponents.GUI_CANCEL, 20, font, (n)-> { + this.minecraft.setScreen(null); + }); + row.addFiller(); + } + + @Environment(EnvType.CLIENT) + public interface Listener { + void doContinue(boolean markFixed); + } +} diff --git a/src/main/java/ru/bclib/gui/screens/ModListScreen.java b/src/main/java/ru/bclib/gui/screens/ModListScreen.java index 74ee4a33..2a54264b 100644 --- a/src/main/java/ru/bclib/gui/screens/ModListScreen.java +++ b/src/main/java/ru/bclib/gui/screens/ModListScreen.java @@ -208,7 +208,6 @@ public class ModListScreen extends BCLibScreen { row.addFiller(); row.addButton(buttonTitle, 20, font, (n)-> { onClose(); - System.out.println("Closing"); }); row.addFiller(); } diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 76d00a4d..f1cb2523 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -61,7 +61,7 @@ public abstract class MinecraftMixin { DataExchangeAPI.prepareServerside(); if (DataFixerAPI.fixData(this.levelSource, levelID, true, (appliedFixes) -> { - this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, Minecraft.ExperimentalDialogType.BACKUP); + this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, appliedFixes?ExperimentalDialogType.NONE:ExperimentalDialogType.BACKUP); })) { ci.cancel(); } diff --git a/src/main/resources/assets/bclib/lang/de_de.json b/src/main/resources/assets/bclib/lang/de_de.json index c9b2518e..7fcb0c99 100644 --- a/src/main/resources/assets/bclib/lang/de_de.json +++ b/src/main/resources/assets/bclib/lang/de_de.json @@ -43,5 +43,8 @@ "message.bclib.datafixer.progress.regions": "Alle Regionen reparieren", "message.bclib.datafixer.progress.saving": "Patch-Status speichern", "title.bclib.datafixer.progress": "Welt in Ordnung bringen", - "message.bclib.datafixer.progress": "Anwenden aller Änderungen" + "message.bclib.datafixer.progress": "Anwenden aller Änderungen", + "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" } \ 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 3ef32c1e..68aa85bc 100644 --- a/src/main/resources/assets/bclib/lang/en_us.json +++ b/src/main/resources/assets/bclib/lang/en_us.json @@ -43,5 +43,8 @@ "message.bclib.datafixer.progress.regions": "Repairing all Regions", "message.bclib.datafixer.progress.saving": "Saving Patch State", "title.bclib.datafixer.progress": "Fixing World", - "message.bclib.datafixer.progress": "Applying all Patches to your World." + "message.bclib.datafixer.progress": "Applying all Patches to your World.", + "title.bclib.datafixer.error": "Errors while fixing World", + "message.bclib.datafixer.error": "There were errors while repairing the world. This means that this level is probably in an inconsistent state and you should not play it. Please restore your backup and fix the errors below before trying again.", + "title.bclib.datafixer.error.continue": "Fortfahren und als behoben markieren" } \ No newline at end of file From f648669c95576b2e6734e956156f255eec5e5724 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 11:48:19 +0100 Subject: [PATCH 38/53] Removed errors created for debug purpose --- src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index b58f0f5b..d00391a1 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -234,9 +234,7 @@ public class DataFixerAPI { if (showUI) { Thread fixerThread = new Thread(() -> { - State state = runner.get(); - for (int i=0; i<20; i++) - state.addError("Hello World"); + final State state = runner.get(); Minecraft.getInstance() .execute(() -> { From d04d75222e26e5253b7f11111ac1323952319ff6 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 11:52:40 +0100 Subject: [PATCH 39/53] A `ForcedLevelPatch` is always executed against level.dat, (no matter what patchLevel is set for a world) --- src/main/java/ru/bclib/BCLib.java | 4 +- src/main/java/ru/bclib/BCLibPatch.java | 13 ++++- .../bclib/api/datafixer/ForcedLevelPatch.java | 47 +++++++++++++++++++ .../bclib/api/datafixer/MigrationProfile.java | 2 +- .../java/ru/bclib/api/datafixer/Patch.java | 21 ++++++++- 5 files changed, 80 insertions(+), 7 deletions(-) create mode 100644 src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index f5f6eb3c..1e450f96 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -12,7 +12,6 @@ import ru.bclib.api.dataexchange.handler.autosync.HelloClient; import ru.bclib.api.dataexchange.handler.autosync.HelloServer; import ru.bclib.api.dataexchange.handler.autosync.RequestFiles; import ru.bclib.api.dataexchange.handler.autosync.SendFiles; -import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.config.Configs; import ru.bclib.recipes.CraftingRecipes; import ru.bclib.registry.BaseBlockEntities; @@ -50,8 +49,7 @@ public class BCLib implements ModInitializer { Chunker.DESCRIPTOR )); - DataFixerAPI.registerPatch(() -> new BCLibPatch()); - + BCLibPatch.register(); Configs.save(); } diff --git a/src/main/java/ru/bclib/BCLibPatch.java b/src/main/java/ru/bclib/BCLibPatch.java index d05bf60a..d7db7d40 100644 --- a/src/main/java/ru/bclib/BCLibPatch.java +++ b/src/main/java/ru/bclib/BCLibPatch.java @@ -1,14 +1,23 @@ package ru.bclib; import net.minecraft.nbt.CompoundTag; +import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.api.datafixer.Patch; import ru.bclib.api.datafixer.PatchFunction; -public final class BCLibPatch extends Patch { + + +public final class BCLibPatch { + public static void register(){ + DataFixerAPI.registerPatch(BiomeSourcePatch::new); + } +} + +final class BiomeSourcePatch extends Patch { private static final String NETHER_BIOME_SOURCE = "bclib:nether_biome_source"; private static final String END_BIOME_SOURCE = "bclib:end_biome_source"; - protected BCLibPatch() { + protected BiomeSourcePatch() { super(BCLib.MOD_ID, "0.4.0"); } diff --git a/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java b/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java new file mode 100644 index 00000000..c6ec75dc --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java @@ -0,0 +1,47 @@ +package ru.bclib.api.datafixer; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * A Patch for level.dat that is always executed no matter what Patchlevel is set in a world. + */ +public abstract class ForcedLevelPatch extends Patch { + protected ForcedLevelPatch(@NotNull String modID, String version) { + super(modID, version, true); + } + + @Override + public final Map getIDReplacements() { + return new HashMap(); + } + + @Override + public final PatchFunction getWorldDataPatcher() { return null; } + + @Override + public final PatchBiFunction getBlockStatePatcher() { return null; } + + @Override + public final List getWorldDataIDPaths() { + return null; + } + + @Override + public PatchFunction getLevelDatPatcher() { return this::runLevelDatPatch; } + + /** + * Called with the contents of level.dat in {@Code root} + * @param root The contents of level.dat + * @param profile The active migration profile + * @return true, if the run did change the contents of root + */ + abstract protected Boolean runLevelDatPatch(CompoundTag root, MigrationProfile profile); +} + diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java index 6ad9dd58..26065093 100644 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -57,7 +57,7 @@ public class MigrationProfile { List paths = patch.getWorldDataIDPaths(); if (paths!=null) worldDataIDPaths.put(modID, paths); - if (applyAll || currentPatchLevel(modID) < patch.level) { + if (applyAll || currentPatchLevel(modID) < patch.level || patch.alwaysApply) { replacements.putAll(patch.getIDReplacements()); if (patch.getLevelDatPatcher()!=null) levelPatches.add(patch.getLevelDatPatcher()); diff --git a/src/main/java/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java index dafa6dd3..bc64e3c5 100644 --- a/src/main/java/ru/bclib/api/datafixer/Patch.java +++ b/src/main/java/ru/bclib/api/datafixer/Patch.java @@ -31,6 +31,11 @@ public abstract class Patch { @NotNull public final String modID; + /** + * This Mod is tested for each level start + */ + public final boolean alwaysApply; + static List getALL() { return ALL; } @@ -82,6 +87,19 @@ public abstract class Patch { * {@link Patch#maxPatchVersion(String)} */ protected Patch(@NotNull String modID, String version) { + this(modID, version, false); + } + + /** + * Internal Constructor used to create patches that can allways run (no matter what patchlevel a level has) + * @param modID The ID of the Mod + * @param version The mod-version that introduces the patch. When {@Code runAllways} is set, this version will + * determine the patchlevel that is written to the level + * @param alwaysApply When true, this patch is always active, no matter the patchlevel of the world. + * This should be used sparingly and just for patches that apply to level.dat (as they only take + * effect when changes are detected). Use {@link ForcedLevelPatch} to instatiate. + */ + Patch(@NotNull String modID, String version, boolean alwaysApply) { //Patchlevels need to be unique and registered in ascending order if (modID == null || "".equals(modID)) { throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); @@ -92,6 +110,7 @@ public abstract class Patch { } this.version = version; + this.alwaysApply = alwaysApply; this.level = ModUtil.convertModVersion(version); if (!ALL.stream() .filter(p -> p.modID @@ -185,7 +204,7 @@ public abstract class Patch { } /** - * Returns a list of paths,where your mod may IDs in your {@link ru.bclib.api.WorldDataAPI}-File. + * Returns a list of paths where your mod stores IDs in your {@link ru.bclib.api.WorldDataAPI}-File. *

* {@link DataFixerAPI} will use information from the latest patch that returns a non-null-result. This list is used * to automatically fix changed IDs from all active patches (see {@link Patch#getIDReplacements()} From 473029c31fa82559643c22679f4cb81529c5b3f4 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 11:59:13 +0100 Subject: [PATCH 40/53] Fixed JavaDoc error --- src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java b/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java index c6ec75dc..34951454 100644 --- a/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java +++ b/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java @@ -37,7 +37,7 @@ public abstract class ForcedLevelPatch extends Patch { public PatchFunction getLevelDatPatcher() { return this::runLevelDatPatch; } /** - * Called with the contents of level.dat in {@Code root} + * Called with the contents of level.dat in {@code root} * @param root The contents of level.dat * @param profile The active migration profile * @return true, if the run did change the contents of root From c61856cdba87912f3b4297e164ae0f654bba0c4a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 6 Nov 2021 15:41:20 +0300 Subject: [PATCH 41/53] Mod blocks in registry, version change --- gradle.properties | 2 +- .../java/ru/bclib/registry/BaseRegistry.java | 23 ++++++++++++++----- .../java/ru/bclib/registry/BlockRegistry.java | 4 +++- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/gradle.properties b/gradle.properties index 096d2710..a20ca271 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ loader_version= 0.12.4 fabric_version = 0.41.3+1.17 # Mod Properties -mod_version = 0.4.4 +mod_version = 0.5.0 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/registry/BaseRegistry.java b/src/main/java/ru/bclib/registry/BaseRegistry.java index 8e61ebe7..ea5a4fd7 100644 --- a/src/main/java/ru/bclib/registry/BaseRegistry.java +++ b/src/main/java/ru/bclib/registry/BaseRegistry.java @@ -6,6 +6,7 @@ import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; import ru.bclib.config.PathConfig; import java.util.List; @@ -13,7 +14,8 @@ import java.util.Map; public abstract class BaseRegistry { private static final List> REGISTRIES = Lists.newArrayList(); - private static final Map> MOD_BLOCKS = Maps.newHashMap(); + private static final Map> MOD_BLOCK_ITEMS = Maps.newHashMap(); + private static final Map> MOD_BLOCKS = Maps.newHashMap(); private static final Map> MOD_ITEMS = Maps.newHashMap(); protected final CreativeModeTab creativeTab; @@ -37,19 +39,19 @@ public abstract class BaseRegistry { private void registerInternal() {} public static Map> getRegisteredBlocks() { - return MOD_BLOCKS; + return MOD_BLOCK_ITEMS; } public static Map> getRegisteredItems() { return MOD_ITEMS; } - public static List getModBlocks(String modId) { - if (MOD_BLOCKS.containsKey(modId)) { - return MOD_BLOCKS.get(modId); + public static List getModBlockItems(String modId) { + if (MOD_BLOCK_ITEMS.containsKey(modId)) { + return MOD_BLOCK_ITEMS.get(modId); } List modBlocks = Lists.newArrayList(); - MOD_BLOCKS.put(modId, modBlocks); + MOD_BLOCK_ITEMS.put(modId, modBlocks); return modBlocks; } @@ -62,6 +64,15 @@ public abstract class BaseRegistry { return modBlocks; } + public static List getModBlocks(String modId) { + if (MOD_BLOCKS.containsKey(modId)) { + return MOD_BLOCKS.get(modId); + } + List modBlocks = Lists.newArrayList(); + MOD_BLOCKS.put(modId, modBlocks); + return modBlocks; + } + public static void register() { REGISTRIES.forEach(BaseRegistry::registerInternal); } diff --git a/src/main/java/ru/bclib/registry/BlockRegistry.java b/src/main/java/ru/bclib/registry/BlockRegistry.java index f071ad0d..608e9ca7 100644 --- a/src/main/java/ru/bclib/registry/BlockRegistry.java +++ b/src/main/java/ru/bclib/registry/BlockRegistry.java @@ -38,6 +38,7 @@ public class BlockRegistry extends BaseRegistry { } block = Registry.register(Registry.BLOCK, id, block); + getModBlocks(id.getNamespace()).add(block); if (block instanceof BaseLeavesBlock){ TagAPI.addTags(block, TagAPI.BLOCK_LEAVES); @@ -58,6 +59,7 @@ public class BlockRegistry extends BaseRegistry { if (!config.getBooleanRoot(id.getNamespace(), true)) { return block; } + getModBlocks(id.getNamespace()).add(block); return Registry.register(Registry.BLOCK, id, block); } @@ -70,7 +72,7 @@ public class BlockRegistry extends BaseRegistry { public void registerItem(ResourceLocation id, Item item) { if (item != null && item != Items.AIR) { Registry.register(Registry.ITEM, id, item); - getModBlocks(id.getNamespace()).add(item); + getModBlockItems(id.getNamespace()).add(item); } } } From 5247a80549e483752878b80e06ade1eacc54498f Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 6 Nov 2021 15:52:26 +0300 Subject: [PATCH 42/53] Biome changer mixin & interface --- .../java/ru/bclib/interfaces/BiomeSetter.java | 8 ++ .../common/ChunkBiomeContainerMixin.java | 134 ++++++++++++++++++ src/main/resources/bclib.mixins.common.json | 1 + 3 files changed, 143 insertions(+) create mode 100644 src/main/java/ru/bclib/interfaces/BiomeSetter.java create mode 100644 src/main/java/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java diff --git a/src/main/java/ru/bclib/interfaces/BiomeSetter.java b/src/main/java/ru/bclib/interfaces/BiomeSetter.java new file mode 100644 index 00000000..09a8e447 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/BiomeSetter.java @@ -0,0 +1,8 @@ +package ru.bclib.interfaces; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.biome.Biome; + +public interface BiomeSetter { + public void bclib_setBiome(Biome biome, BlockPos pos); +} diff --git a/src/main/java/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java b/src/main/java/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java new file mode 100644 index 00000000..3ad2c2a8 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java @@ -0,0 +1,134 @@ +package ru.bclib.mixin.common; + +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.core.BlockPos; +import net.minecraft.util.BitStorage; +import net.minecraft.util.Mth; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.chunk.ChunkBiomeContainer; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import ru.bclib.BCLib; +import ru.bclib.interfaces.BiomeSetter; + +import java.lang.reflect.Field; + +@Mixin(ChunkBiomeContainer.class) +public class ChunkBiomeContainerMixin implements BiomeSetter { + private static boolean bclib_hasHydrogen = FabricLoader.getInstance().isModLoaded("hydrogen"); + + @Final + @Shadow + private Biome[] biomes; + + @Final + @Shadow + private static int WIDTH_BITS; + + @Final + @Shadow + private static int HORIZONTAL_MASK; + + @Override + public void bclib_setBiome(Biome biome, BlockPos pos) { + int biomeX = pos.getX() >> 2; + int biomeY = pos.getY() >> 2; + int biomeZ = pos.getZ() >> 2; + int index = be_getArrayIndex(biomeX, biomeY, biomeZ); + + if (bclib_hasHydrogen && be_shouldWriteToHydrogen()) { + try { + ChunkBiomeContainer self = (ChunkBiomeContainer) (Object) this; + BitStorage storage = be_getHydrogenStorage(self); + Biome[] palette = be_getHydrogenPalette(self); + int paletteIndex = be_getHydrogenPaletteIndex(biome, palette); + if (paletteIndex == -1) { + Biome[] newPalette = new Biome[palette.length + 1]; + System.arraycopy(palette, 0, newPalette, 0, palette.length); + paletteIndex = palette.length; + palette = newPalette; + palette[paletteIndex] = biome; + be_setHydrogenPalette(self, palette); + } + try { + storage.set(index, paletteIndex); + } + catch (Exception e) { + int size = storage.getSize(); + int bits = Mth.ceillog2(palette.length); + BitStorage newStorage = new BitStorage(bits, size); + for (int i = 0; i < size; i++) { + newStorage.set(i, storage.get(i)); + } + storage = newStorage; + storage.set(index, paletteIndex); + be_setHydrogenStorage(self, storage); + } + } + catch (Exception e) { + BCLib.LOGGER.warning(e.getLocalizedMessage()); + } + return; + } + + biomes[index] = biome; + } + + @Shadow + @Final + private int quartMinY; + @Shadow + @Final + private int quartHeight; + + private boolean be_shouldWriteToHydrogen() { + try { + Field field = ChunkBiomeContainer.class.getDeclaredField("intArray"); + return field != null; + } + catch (NoSuchFieldException e) { + return false; + } + } + + private int be_getArrayIndex(int biomeX, int biomeY, int biomeZ) { + int i = biomeX & HORIZONTAL_MASK; + int j = Mth.clamp(biomeY - this.quartMinY, 0, this.quartHeight); + int k = biomeZ & HORIZONTAL_MASK; + return j << WIDTH_BITS + WIDTH_BITS | k << WIDTH_BITS | i; + } + + private Field be_getField(String name) throws Exception { + Field field = ChunkBiomeContainer.class.getDeclaredField(name); + field.setAccessible(true); + return field; + } + + private BitStorage be_getHydrogenStorage(ChunkBiomeContainer container) throws Exception { + return (BitStorage) be_getField("intArray").get(container); + } + + private Biome[] be_getHydrogenPalette(ChunkBiomeContainer container) throws Exception { + return (Biome[]) be_getField("palette").get(container); + } + + private int be_getHydrogenPaletteIndex(Biome biome, Biome[] palette) { + int index = -1; + for (int i = 0; i < palette.length; i++) { + if (palette[i] == biome) { + index = i; + break; + } + } + return index; + } + + private void be_setHydrogenPalette(ChunkBiomeContainer container, Biome[] palette) throws Exception { + be_getField("palette").set(container, palette); + } + + private void be_setHydrogenStorage(ChunkBiomeContainer container, BitStorage storage) throws Exception { + be_getField("intArray").set(container, storage); + } +} diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index c449923b..2ce54afa 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -7,6 +7,7 @@ "SimpleReloadableResourceManagerMixin", "shears.DiggingEnchantmentMixin", "shears.TripWireBlockMixin", + "ChunkBiomeContainerMixin", "shears.BeehiveBlockMixin", "shears.PumpkinBlockMixin", "shears.MushroomCowMixin", From 1b683b5564516f5d64481566e2e8e35ad9bda4d0 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 19:16:20 +0100 Subject: [PATCH 43/53] Fixed crash on server --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index d00391a1..baffef34 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -26,6 +26,7 @@ import ru.bclib.config.Configs; import ru.bclib.gui.screens.AtomicProgressListener; import ru.bclib.gui.screens.ConfirmFixScreen; import ru.bclib.gui.screens.LevelFixErrorScreen; +import ru.bclib.gui.screens.LevelFixErrorScreen.Listener; import ru.bclib.gui.screens.ProgressScreen; import ru.bclib.util.Logger; @@ -241,13 +242,12 @@ public class DataFixerAPI { if (profile != null && showUI) { //something went wrong, show the user our error if (state.didFail || state.hasError()){ - Minecraft.getInstance() - .setScreen(new LevelFixErrorScreen(Minecraft.getInstance().screen, state.getErrorMessages(), (markFixed)->{ - if (markFixed) { - profile.markApplied(); - } - onResume.accept(applyFixes); - })); + showLevelFixErrorScreen(state, (markFixed)->{ + if (markFixed) { + profile.markApplied(); + } + onResume.accept(applyFixes); + }); } else { onResume.accept(applyFixes); } @@ -278,6 +278,11 @@ public class DataFixerAPI { } return false; } + @Environment(EnvType.CLIENT) + private static void showLevelFixErrorScreen(State state, Listener onContinue){ + Minecraft.getInstance() + .setScreen(new LevelFixErrorScreen(Minecraft.getInstance().screen, state.getErrorMessages(), onContinue)); + } private static MigrationProfile loadProfileIfNeeded(File levelBaseDir){ if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { From a879a826456568e340f1b70f37c15341e1943825 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 19:41:40 +0100 Subject: [PATCH 44/53] Turn off ModInfo on the server by default --- src/main/java/ru/bclib/config/ServerConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/config/ServerConfig.java b/src/main/java/ru/bclib/config/ServerConfig.java index 6ede7b8c..252c48e0 100644 --- a/src/main/java/ru/bclib/config/ServerConfig.java +++ b/src/main/java/ru/bclib/config/ServerConfig.java @@ -12,7 +12,7 @@ public class ServerConfig extends NamedPathConfig { public static final DependendConfigToken OFFER_FILES = DependendConfigToken.Boolean(true, "offerFiles", AutoSync.SYNC_CATEGORY, (config) -> config.get(ENABLED)); public static final DependendConfigToken OFFER_MODS = DependendConfigToken.Boolean(true, "offerMods", AutoSync.SYNC_CATEGORY, (config) -> config.get(ENABLED)); public static final DependendConfigToken OFFER_ALL_MODS = DependendConfigToken.Boolean(false, "offerAllMods", AutoSync.SYNC_CATEGORY, (config) -> config.get(OFFER_MODS)); - public static final DependendConfigToken SEND_ALL_MOD_INFO = DependendConfigToken.Boolean(true, "sendAllModInfo", AutoSync.SYNC_CATEGORY, (config) -> config.get(ENABLED)); + public static final DependendConfigToken SEND_ALL_MOD_INFO = DependendConfigToken.Boolean(false, "sendAllModInfo", AutoSync.SYNC_CATEGORY, (config) -> config.get(ENABLED)); public static final ConfigToken> ADDITIONAL_MODS = ConfigToken.StringArray(new ArrayList<>(0), "additionalMods", AutoSync.SYNC_CATEGORY); From 82331744872cae7924561e28efc31dd7eae9daf7 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 20:04:52 +0100 Subject: [PATCH 45/53] Show Mod info sorted by severity and show client-only mods as OK --- .../ru/bclib/gui/gridlayout/GridLayout.java | 1 + .../ru/bclib/gui/screens/ModListScreen.java | 25 +++++++++++-------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java index 4a2b50d1..cacee79d 100644 --- a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java +++ b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java @@ -88,6 +88,7 @@ public class GridLayout extends GridColumn { public static final int COLOR_RED = 0xFFDB1F48; public static final int COLOR_CYAN = 0xFF01949A; public static final int COLOR_GREEN = 0xFF00FF00; + public static final int COLOR_DARK_GREEN = 0xFF007F00; public static final int COLOR_YELLOW = 0xFFFAD02C; public static final int COLOR_BLUE = 0xFF0000FF; public static final int COLOR_GRAY = 0xFF7F7F7F; diff --git a/src/main/java/ru/bclib/gui/screens/ModListScreen.java b/src/main/java/ru/bclib/gui/screens/ModListScreen.java index 2a54264b..f2af5008 100644 --- a/src/main/java/ru/bclib/gui/screens/ModListScreen.java +++ b/src/main/java/ru/bclib/gui/screens/ModListScreen.java @@ -73,13 +73,14 @@ public class ModListScreen extends BCLibScreen { public static void addModDesc(GridColumn grid, java.util.List mods, HelloClient.IServerModMap serverInfo, GridScreen parent) { - final int STATE_OK = 0; - final int STATE_MISSING = 1; - final int STATE_SERVER_MISSING = 2; - final int STATE_VERSION = 3; - final int STATE_SERVER_MISSING_CLIENT_MOD = 4; - final int STATE_VERSION_NOT_OFFERED = 5; - final int STATE_MISSING_NOT_OFFERED = 6; + final int STATE_OK = 6; + final int STATE_SERVER_MISSING_CLIENT_MOD = 5; + final int STATE_MISSING_NOT_OFFERED = 4; + final int STATE_VERSION_NOT_OFFERED = 3; + final int STATE_VERSION = 2; + final int STATE_SERVER_MISSING = 1; + final int STATE_MISSING = 0; + List> items = new LinkedList<>(); if (serverInfo!=null) { @@ -141,7 +142,7 @@ public class ModListScreen extends BCLibScreen { }); items.stream() - .sorted(Comparator.comparing(a -> a.first.toLowerCase(Locale.ROOT))) + .sorted(Comparator.comparing(a -> a.second + a.first.toLowerCase(Locale.ROOT))) .forEach(t -> { final String name = t.first; final int state = t.second; @@ -160,12 +161,14 @@ public class ModListScreen extends BCLibScreen { color = GridLayout.COLOR_YELLOW; } } else if (state==STATE_SERVER_MISSING || state == STATE_SERVER_MISSING_CLIENT_MOD) { - typeText = "[NOT ON SERVER]"; if (state == STATE_SERVER_MISSING_CLIENT_MOD) { - color = GridLayout.COLOR_YELLOW; + color = GridLayout.COLOR_CYAN; + typeText = "[OK]"; + } else { + typeText = "[NOT ON SERVER]"; } } else { - color = GridLayout.COLOR_CYAN; + color = GridLayout.COLOR_DARK_GREEN; typeText = "[OK]"; } TextComponent dash = new TextComponent("-"); From 2cbfbe8047fb4a99f8e5884cb55dd09d4bff0811 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 20:58:41 +0100 Subject: [PATCH 46/53] Add config to exclude mods from syncing/info --- .../bclib/api/dataexchange/handler/autosync/AutoSync.java | 2 +- .../api/dataexchange/handler/autosync/HelloClient.java | 6 ++++++ src/main/java/ru/bclib/config/ServerConfig.java | 6 ++---- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java index da78fca4..89a33463 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java @@ -135,7 +135,7 @@ public class AutoSync { } private static boolean didRegisterAdditionalMods = false; - //we call this from HelloClient on the Srérver to prepare transfer + //we call this from HelloClient on the Server to prepare transfer protected static void loadSyncFolder() { if (Configs.SERVER_CONFIG.isOfferingFiles()) { syncFolderDescriptions.forEach(desc -> desc.loadCache()); diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java index 0d24997c..83762718 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloClient.java @@ -16,6 +16,7 @@ import ru.bclib.api.dataexchange.DataHandlerDescriptor; import ru.bclib.api.dataexchange.handler.autosync.AutoSyncID.WithContentOverride; import ru.bclib.api.dataexchange.handler.autosync.SyncFolderDescriptor.SubFile; import ru.bclib.config.Configs; +import ru.bclib.config.ServerConfig; import ru.bclib.gui.screens.ModListScreen; import ru.bclib.gui.screens.ProgressScreen; import ru.bclib.gui.screens.SyncFilesScreen; @@ -91,6 +92,11 @@ public class HelloClient extends DataHandler.FromServer { .collect(Collectors.toList()) ); } + + mods = mods + .stream() + .filter(entry -> !Configs.SERVER_CONFIG.get(ServerConfig.EXCLUDED_MODS).contains(entry)) + .collect(Collectors.toList()); //write Plugin Versions buf.writeInt(mods.size()); diff --git a/src/main/java/ru/bclib/config/ServerConfig.java b/src/main/java/ru/bclib/config/ServerConfig.java index 252c48e0..bf8a66b7 100644 --- a/src/main/java/ru/bclib/config/ServerConfig.java +++ b/src/main/java/ru/bclib/config/ServerConfig.java @@ -16,6 +16,7 @@ public class ServerConfig extends NamedPathConfig { public static final ConfigToken> ADDITIONAL_MODS = ConfigToken.StringArray(new ArrayList<>(0), "additionalMods", AutoSync.SYNC_CATEGORY); + public static final ConfigToken> EXCLUDED_MODS = ConfigToken.StringArray(new ArrayList<>(0), "excludeMods", AutoSync.SYNC_CATEGORY); public ServerConfig() { @@ -45,8 +46,5 @@ public class ServerConfig extends NamedPathConfig { public boolean isOfferingInfosForMods() { return get(SEND_ALL_MOD_INFO) /*&& isAllowingAutoSync()*/; } - - public String[] additionalModsForSync() { - return new String[0]; - } + } From 07d8c56e18e20e343f6fc8dbec03d5c6d2110c15 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 20:59:06 +0100 Subject: [PATCH 47/53] Mark Mods that do not contain a client entrypoint as Server-Only for Sync --- src/main/java/ru/bclib/util/ModUtil.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/ru/bclib/util/ModUtil.java b/src/main/java/ru/bclib/util/ModUtil.java index 05c0b596..8f4b973a 100644 --- a/src/main/java/ru/bclib/util/ModUtil.java +++ b/src/main/java/ru/bclib/util/ModUtil.java @@ -143,6 +143,22 @@ public class ModUtil { final String environment = env.getAsString().toLowerCase(Locale.ROOT); if (environment.isEmpty() || environment.equals("*") || environment.equals("common")) { + JsonElement entrypoints = data.get("entrypoints"); + boolean hasClient = true; + + //check if there is an actual client entrypoint + if (entrypoints!=null && entrypoints.isJsonObject()){ + JsonElement client = entrypoints.getAsJsonObject().get("client"); + if (client!=null && client.isJsonArray()){ + hasClient = client.getAsJsonArray().size() > 0; + } else if (client==null || !client.isJsonPrimitive()){ + hasClient = false; + } else if (!client.getAsJsonPrimitive().isString()){ + hasClient = false; + } + } + + if (hasClient == false) return ModEnvironment.SERVER; return ModEnvironment.UNIVERSAL; } else if (environment.equals("client")) { return ModEnvironment.CLIENT; From 60574d5b75f16dcd28a0a477cf60834257198d19 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 6 Nov 2021 21:26:32 +0100 Subject: [PATCH 48/53] Fallback to uncompressed when reading player data (paulevsGitch/BetterNether#436) --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index baffef34..b63505c9 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -41,6 +41,7 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import java.util.zip.ZipException; /** * API to manage Patches that need to get applied to a world @@ -393,11 +394,12 @@ public class DataFixerAPI { e.printStackTrace(); } } - + private static void fixPlayer(MigrationProfile data, State state, File file) { try { LOGGER.info("Inspecting " + file); - CompoundTag player = NbtIo.readCompressed(file); + + CompoundTag player = readNbt(file); boolean[] changed = { false }; fixPlayerNbt(player, changed, data); @@ -413,7 +415,7 @@ public class DataFixerAPI { e.printStackTrace(); } } - + private static void fixPlayerNbt(CompoundTag player, boolean[] changed, MigrationProfile data) { //Checking Inventory ListTag inventory = player.getList("Inventory", Tag.TAG_COMPOUND); @@ -599,4 +601,12 @@ public class DataFixerAPI { Patch.getALL().add(patch.get()); } + private static CompoundTag readNbt(File file) throws IOException { + try { + return NbtIo.readCompressed(file); + } catch (ZipException e){ + return NbtIo.read(file); + } + } + } From cc33a9138bb10be961d9b79f717327b90a4e2995 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 12 Nov 2021 08:50:41 +0300 Subject: [PATCH 49/53] Biome modification API --- gradle.properties | 2 +- src/main/java/ru/bclib/api/BiomeAPI.java | 76 +++++++++++++++++++ .../ru/bclib/gui/gridlayout/GridLayout.java | 2 +- .../bclib/mixin/common/ServerLevelMixin.java | 1 + .../generator/BCLibNetherBiomeSource.java | 1 + 5 files changed, 80 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index a20ca271..e3998406 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ loader_version= 0.12.4 fabric_version = 0.41.3+1.17 # Mod Properties -mod_version = 0.5.0 +mod_version = 0.5.1 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/api/BiomeAPI.java b/src/main/java/ru/bclib/api/BiomeAPI.java index eb4ff13e..35de02fd 100644 --- a/src/main/java/ru/bclib/api/BiomeAPI.java +++ b/src/main/java/ru/bclib/api/BiomeAPI.java @@ -1,6 +1,8 @@ package ru.bclib.api; +import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Sets; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.biome.InternalBiomeData; @@ -10,8 +12,11 @@ import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome.ClimateParameters; +import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.Biomes; import org.jetbrains.annotations.Nullable; import ru.bclib.util.MHelper; @@ -19,8 +24,11 @@ import ru.bclib.world.biomes.BCLBiome; import ru.bclib.world.biomes.FabricBiomesData; import ru.bclib.world.generator.BiomePicker; +import java.util.List; import java.util.Map; import java.util.Random; +import java.util.Set; +import java.util.function.BiConsumer; public class BiomeAPI { /** @@ -37,6 +45,9 @@ public class BiomeAPI { private static final Map CLIENT = Maps.newHashMap(); private static Registry biomeRegistry; + private static final Map>> MODIFICATIONS = Maps.newHashMap(); + private static final Set MODIFIED_BIOMES = Sets.newHashSet(); + 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)); @@ -320,4 +331,69 @@ public class BiomeAPI { private static boolean pickerHasBiome(BiomePicker picker, ResourceLocation key) { return picker.getBiomes().stream().filter(biome -> biome.getID().equals(key)).findFirst().isPresent(); } + + /** + * Registers new biome modification for specified dimension. Will work both for mod and datapack biomes. + * @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.get(dimensionID); + if (modifications == null) { + modifications = Lists.newArrayList(); + MODIFICATIONS.put(dimensionID, modifications); + } + modifications.add(modification); + } + + /** + * 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) { + registerBiomeModification(Level.OVERWORLD, modification); + } + + /** + * Registers new biome modification for the Nether. Will work both for mod and datapack biomes. + * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. + */ + public static void registerNetherBiomeModification(BiConsumer modification) { + registerBiomeModification(Level.NETHER, modification); + } + + /** + * Registers new biome modification for the End. Will work both for mod and datapack biomes. + * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. + */ + public static void registerEndBiomeModification(BiConsumer modification) { + registerBiomeModification(Level.END, modification); + } + + /** + * Will apply biome modifications to world, internal usage only. + * @param level + */ + public static void applyModifications(ServerLevel level) { + List> modifications = MODIFICATIONS.get(level.dimension()); + if (modifications == null) { + return; + } + BiomeSource source = level.getChunkSource().getGenerator().getBiomeSource(); + List biomes = source.possibleBiomes(); + + biomes.forEach(biome -> { + ResourceLocation biomeID = getBiomeID(biome); + boolean modify = isDatapackBiome(biomeID); + if (!modify && !MODIFIED_BIOMES.contains(biomeID)) { + MODIFIED_BIOMES.add(biomeID); + modify = true; + } + if (modify) { + modifications.forEach(consumer -> { + consumer.accept(biomeID, biome); + }); + } + }); + } } diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java index cacee79d..5e9ef459 100644 --- a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java +++ b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java @@ -5,8 +5,8 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.gui.components.AbstractWidget; import ru.bclib.gui.gridlayout.GridLayout.GridValueType; -import ru.bclib.util.Pair; import ru.bclib.interfaces.TriConsumer; +import ru.bclib.util.Pair; import java.util.LinkedList; import java.util.List; diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index 1717d4f7..8de68864 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -33,6 +33,7 @@ public abstract class ServerLevelMixin extends Level { @Inject(method = "*", at = @At("TAIL")) private void bclib_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { BiomeAPI.initRegistry(server); + BiomeAPI.applyModifications(ServerLevel.class.cast(this)); if (bclib_lastWorld != null && bclib_lastWorld.equals(session.getLevelId())) { return; diff --git a/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java b/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java index 9fdbfbe5..27a8ba3c 100644 --- a/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java +++ b/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java @@ -28,6 +28,7 @@ public class BCLibNetherBiomeSource extends BiomeSource { private BiomeMap biomeMap; private final long seed; + @Deprecated(forRemoval = true) public static final List> onInit = new LinkedList<>(); public BCLibNetherBiomeSource(Registry biomeRegistry, long seed) { From e45f1ac064b11184f627dc1e158b0e0db782b5a9 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 12 Nov 2021 09:22:47 +0300 Subject: [PATCH 50/53] Biome source options --- .../mixin/common/DimensionTypeMixin.java | 25 +++++++++++-------- .../world/generator/GeneratorOptions.java | 12 +++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java b/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java index a925d152..2826a052 100644 --- a/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java +++ b/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java @@ -12,24 +12,29 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.world.generator.BCLibEndBiomeSource; import ru.bclib.world.generator.BCLibNetherBiomeSource; +import ru.bclib.world.generator.GeneratorOptions; @Mixin(value = DimensionType.class, priority = 100) public class DimensionTypeMixin { @Inject(method = "defaultNetherGenerator", at = @At("HEAD"), cancellable = true) private static void be_replaceNetherBiomeSource(Registry biomeRegistry, Registry chunkGeneratorSettingsRegistry, long seed, CallbackInfoReturnable info) { - info.setReturnValue(new NoiseBasedChunkGenerator( - new BCLibNetherBiomeSource(biomeRegistry, seed), - seed, - () -> chunkGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.NETHER) - )); + if (GeneratorOptions.customNetherBiomeSource()) { + info.setReturnValue(new NoiseBasedChunkGenerator( + new BCLibNetherBiomeSource(biomeRegistry, seed), + seed, + () -> chunkGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.NETHER) + )); + } } @Inject(method = "defaultEndGenerator", at = @At("HEAD"), cancellable = true) private static void be_replaceEndBiomeSource(Registry biomeRegistry, Registry chunkGeneratorSettingsRegistry, long seed, CallbackInfoReturnable info) { - info.setReturnValue(new NoiseBasedChunkGenerator( - new BCLibEndBiomeSource(biomeRegistry, seed), - seed, - () -> chunkGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.END) - )); + if (GeneratorOptions.customEndBiomeSource()) { + info.setReturnValue(new NoiseBasedChunkGenerator( + new BCLibEndBiomeSource(biomeRegistry, seed), + seed, + () -> chunkGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.END) + )); + } } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/world/generator/GeneratorOptions.java b/src/main/java/ru/bclib/world/generator/GeneratorOptions.java index 7137ad2b..a2b80ad4 100644 --- a/src/main/java/ru/bclib/world/generator/GeneratorOptions.java +++ b/src/main/java/ru/bclib/world/generator/GeneratorOptions.java @@ -12,11 +12,15 @@ public class GeneratorOptions { private static int biomeSizeEndVoid; private static Function endLandFunction; private static boolean farEndBiomes = true; + private static boolean customNetherBiomeSource = true; + private static boolean customEndBiomeSource = true; public static void init() { biomeSizeNether = Configs.GENERATOR_CONFIG.getInt("nether.biomeMap", "biomeSize", 256); biomeSizeEndLand = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeLand", 256); biomeSizeEndVoid = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeVoid", 256); + customNetherBiomeSource = Configs.GENERATOR_CONFIG.getBoolean("options", "customNetherBiomeSource", true); + customEndBiomeSource = Configs.GENERATOR_CONFIG.getBoolean("options", "customEndBiomeSource", true); } public static int getBiomeSizeNether() { @@ -46,4 +50,12 @@ public class GeneratorOptions { public static void setFarEndBiomes(boolean farEndBiomes) { GeneratorOptions.farEndBiomes = farEndBiomes; } + + public static boolean customNetherBiomeSource() { + return customNetherBiomeSource; + } + + public static boolean customEndBiomeSource() { + return customEndBiomeSource; + } } From cae1d932a174b1c833bdd761afb7fffd3ccae19a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 12 Nov 2021 17:04:18 +0300 Subject: [PATCH 51/53] Biome feature adding API --- src/main/java/ru/bclib/api/BiomeAPI.java | 82 ++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/main/java/ru/bclib/api/BiomeAPI.java b/src/main/java/ru/bclib/api/BiomeAPI.java index 35de02fd..5036f787 100644 --- a/src/main/java/ru/bclib/api/BiomeAPI.java +++ b/src/main/java/ru/bclib/api/BiomeAPI.java @@ -1,11 +1,13 @@ package ru.bclib.api; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.biome.InternalBiomeData; +import net.fabricmc.fabric.mixin.biome.modification.GenerationSettingsAccessor; import net.minecraft.client.Minecraft; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; @@ -18,17 +20,23 @@ import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome.ClimateParameters; import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.levelgen.GenerationStep.Decoration; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; +import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; import org.jetbrains.annotations.Nullable; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; import ru.bclib.world.biomes.FabricBiomesData; +import ru.bclib.world.features.BCLFeature; import ru.bclib.world.generator.BiomePicker; +import ru.bclib.world.structures.BCLStructureFeature; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.function.BiConsumer; +import java.util.function.Supplier; public class BiomeAPI { /** @@ -396,4 +404,78 @@ public class BiomeAPI { } }); } + + /** + * Adds new features to existing biome. + * @param biome {@link Biome} to add features in. + * @param feature {@link ConfiguredFeature} to add. + * @param step a {@link Decoration} step for the feature. + */ + public static void addBiomeFeature(Biome biome, ConfiguredFeature feature, Decoration step) { + GenerationSettingsAccessor accessor = (GenerationSettingsAccessor) biome.getGenerationSettings(); + List>>> biomeFeatures = getMutableList(accessor.fabric_getFeatures()); + int index = step.ordinal(); + if (biomeFeatures.size() < index) { + for (int i = biomeFeatures.size(); i <= index; i++) { + biomeFeatures.add(Lists.newArrayList()); + } + } + List>> list = getMutableList(biomeFeatures.get(index)); + list.add(() -> feature); + accessor.fabric_setFeatures(biomeFeatures); + } + + /** + * Adds new features to existing biome. + * @param biome {@link Biome} to add features in. + * @param features array of {@link BCLFeature} to add. + */ + public static void addBiomeFeatures(Biome biome, BCLFeature... features) { + GenerationSettingsAccessor accessor = (GenerationSettingsAccessor) biome.getGenerationSettings(); + List>>> biomeFeatures = getMutableList(accessor.fabric_getFeatures()); + for (BCLFeature feature: features) { + int index = feature.getFeatureStep().ordinal(); + if (biomeFeatures.size() < index) { + for (int i = biomeFeatures.size(); i <= index; i++) { + biomeFeatures.add(Lists.newArrayList()); + } + } + List>> list = getMutableList(biomeFeatures.get(index)); + list.add(feature::getFeatureConfigured); + } + accessor.fabric_setFeatures(biomeFeatures); + } + + /** + * Adds new structure feature to existing biome. + * @param biome {@link Biome} to add structure feature in. + * @param structure {@link ConfiguredStructureFeature} to add. + */ + public static void addBiomeStructure(Biome biome, ConfiguredStructureFeature structure) { + GenerationSettingsAccessor accessor = (GenerationSettingsAccessor) biome.getGenerationSettings(); + List>> biomeStructures = getMutableList(accessor.fabric_getStructureFeatures()); + biomeStructures.add(() -> structure); + accessor.fabric_setStructureFeatures(biomeStructures); + } + + /** + * Adds new structure features to existing biome. + * @param biome {@link Biome} to add structure features in. + * @param structures array of {@link BCLStructureFeature} to add. + */ + public static void addBiomeStructures(Biome biome, BCLStructureFeature... structures) { + GenerationSettingsAccessor accessor = (GenerationSettingsAccessor) biome.getGenerationSettings(); + List>> biomeStructures = getMutableList(accessor.fabric_getStructureFeatures()); + for (BCLStructureFeature structure: structures) { + biomeStructures.add(structure::getFeatureConfigured); + } + accessor.fabric_setStructureFeatures(biomeStructures); + } + + private static List getMutableList(List input) { + if (input instanceof ImmutableList) { + return Lists.newArrayList(input); + } + return input; + } } From 5ad8752e00c515fcb3f8a0462fe40ceba83113c6 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 13 Nov 2021 11:33:04 +0300 Subject: [PATCH 52/53] Crafting menu fix --- .../bclib/mixin/common/CraftingMenuMixin.java | 31 +++++++++++++++++++ src/main/resources/bclib.mixins.common.json | 1 + 2 files changed, 32 insertions(+) create mode 100644 src/main/java/ru/bclib/mixin/common/CraftingMenuMixin.java diff --git a/src/main/java/ru/bclib/mixin/common/CraftingMenuMixin.java b/src/main/java/ru/bclib/mixin/common/CraftingMenuMixin.java new file mode 100644 index 00000000..82273228 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/CraftingMenuMixin.java @@ -0,0 +1,31 @@ +package ru.bclib.mixin.common; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ContainerLevelAccess; +import net.minecraft.world.inventory.CraftingMenu; +import net.minecraft.world.level.block.CraftingTableBlock; +import net.minecraft.world.level.block.state.BlockState; +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.callback.CallbackInfoReturnable; +import ru.bclib.api.TagAPI; + +@Mixin(CraftingMenu.class) +public abstract class CraftingMenuMixin { + @Final + @Shadow + private ContainerLevelAccess access; + + @Inject(method = "stillValid", at = @At("HEAD"), cancellable = true) + private void bclib_stillValid(Player player, CallbackInfoReturnable info) { + if (access.evaluate((world, pos) -> { + BlockState state = world.getBlockState(pos); + return state.getBlock() instanceof CraftingTableBlock || state.is(TagAPI.BLOCK_WORKBENCHES); + }, true)) { + info.setReturnValue(true); + } + } +} diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 2ce54afa..1487977a 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -22,6 +22,7 @@ "WorldGenRegionMixin", "DimensionTypeMixin", "RecipeManagerMixin", + "CraftingMenuMixin", "BoneMealItemMixin", "shears.SheepMixin", "PortalShapeMixin", From ce4cb8974faf0a55e7a1a0402f459c7974c7b116 Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 13 Nov 2021 10:50:57 +0100 Subject: [PATCH 53/53] Fixed potential crash in AnvilMenu --- .../ru/bclib/mixin/common/AnvilMenuMixin.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java index 5d5d9218..66bbbcc9 100644 --- a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java @@ -81,22 +81,23 @@ public abstract class AnvilMenuMixin extends ItemCombinerMenu implements AnvilSc stack = be_currentRecipe.craft(inputSlots, player); slotsChanged(inputSlots); access.execute((world, blockPos) -> { - BlockState anvilState = world.getBlockState(blockPos); - BaseAnvilBlock anvil = (BaseAnvilBlock) anvilState.getBlock(); - if (!player.getAbilities().instabuild && anvilState.is(BlockTags.ANVIL) && player.getRandom().nextDouble() < 0.1) { - BlockState damagedState = anvil.damageAnvilUse(anvilState, player.getRandom()); - if (damagedState == null) { - world.removeBlock(blockPos, false); - world.levelEvent(1029, blockPos, 0); - } - else { - world.setBlock(blockPos, damagedState, 2); + final BlockState anvilState = world.getBlockState(blockPos); + final Block anvilBlock = anvilState.getBlock(); + if (anvilBlock instanceof BaseAnvilBlock) { + final BaseAnvilBlock anvil = (BaseAnvilBlock) anvilBlock; + if (!player.getAbilities().instabuild && anvilState.is(BlockTags.ANVIL) && player.getRandom().nextDouble() < 0.1) { + BlockState damagedState = anvil.damageAnvilUse(anvilState, player.getRandom()); + if (damagedState == null) { + world.removeBlock(blockPos, false); + world.levelEvent(1029, blockPos, 0); + } else { + world.setBlock(blockPos, damagedState, 2); + world.levelEvent(1030, blockPos, 0); + } + } else { world.levelEvent(1030, blockPos, 0); } } - else { - world.levelEvent(1030, blockPos, 0); - } }); info.cancel(); return;