Skip to content

Commit

Permalink
Merge pull request #61
Browse files Browse the repository at this point in the history
Updated and reworked for 1.21.1
  • Loading branch information
Greeenman999 authored Sep 26, 2024
2 parents 33bcb5d + 933f3b8 commit f66651f
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 35 deletions.
6 changes: 3 additions & 3 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ org.gradle.parallel=true

# Fabric Properties
# check these on https://fabricmc.net/develop
minecraft_version=1.20.6
yarn_mappings=1.20.6+build.3
minecraft_version=1.21.1
yarn_mappings=1.21.1+build.3
loader_version=0.15.11

# Mod Properties
Expand All @@ -14,4 +14,4 @@ maven_group=de.greenman999
archives_base_name=librarian-trade-finder

# Dependencies
fabric_version=0.100.4+1.20.6
fabric_version=0.102.1+1.21.1
12 changes: 11 additions & 1 deletion src/main/java/de/greenman999/LibrarianTradeFinder.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.command.argument.RegistryEntryReferenceArgumentType;
Expand Down Expand Up @@ -125,7 +128,14 @@ public void onInitializeClient() {

WorldRenderEvents.END.register(context -> RotationTools.render());

getConfig().load();
ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> getConfig().load());
ServerLifecycleEvents.END_DATA_PACK_RELOAD.register((server, manager, success) -> {
if (MinecraftClient.getInstance().world != null) {
getConfig().load();
} else {
LOGGER.warn("Data pack reload event received, but world is not loaded yet. Skipping config reload.");
}
});

LOGGER.info("Librarian Trade Finder initialized.");
}
Expand Down
7 changes: 6 additions & 1 deletion src/main/java/de/greenman999/TradeFinder.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import net.minecraft.network.packet.c2s.play.PlayerActionC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.network.packet.c2s.play.UpdateSelectedSlotC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerInteractEntityC2SPacket;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.screen.slot.SlotActionType;
import net.minecraft.text.Text;
import net.minecraft.text.TextColor;
Expand Down Expand Up @@ -105,7 +107,7 @@ public static int searchSingle(Enchantment enchantment, int minLevel, int maxBoo
stop();
return 0;
}
MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable("commands.tradefinder.start.success-single", enchantment.getName(minLevel), maxBookPrice).styled(style -> style.withColor(TextColor.fromFormatting(Formatting.GREEN))));
MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable("commands.tradefinder.start.success-single", Enchantment.getName(RegistryEntry.of(enchantment), minLevel), maxBookPrice).styled(style -> style.withColor(TextColor.fromFormatting(Formatting.GREEN))));
return 1;
}

Expand Down Expand Up @@ -135,6 +137,7 @@ public static boolean select() {
double closestDistance = Double.POSITIVE_INFINITY;
Entity closestEntity = null;

assert MinecraftClient.getInstance().world != null;
for(Entity entity : MinecraftClient.getInstance().world.getEntities()) {
Vec3d entityPos = entity.getPos();
if (blockPos != null && entity instanceof VillagerEntity && ((VillagerEntity) entity).getVillagerData().getProfession().equals(VillagerProfession.LIBRARIAN) && entityPos.distanceTo(blockPos.toCenterPos()) < closestDistance) {
Expand Down Expand Up @@ -208,6 +211,8 @@ public static void tick() {
mc.player.swingHand(Hand.MAIN_HAND, true);
mc.player.networkHandler
.sendPacket(new HandSwingC2SPacket(Hand.MAIN_HAND));
mc.player.networkHandler
.sendPacket(PlayerInteractEntityC2SPacket.interact(villager, false, Hand.MAIN_HAND));
}
if(result == ActionResult.SUCCESS) {
finishedBreakLook = false;
Expand Down
82 changes: 64 additions & 18 deletions src/main/java/de/greenman999/config/TradeFinderConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
import com.google.gson.JsonObject;
import de.greenman999.LibrarianTradeFinder;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.registry.tag.TagKey;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;

Expand All @@ -33,6 +37,26 @@ public class TradeFinderConfig {

public HashMap<Enchantment, EnchantmentOption> enchantments = new HashMap<>();

private final HashMap<String, EnchantmentOption> enchantmentConfigs = new HashMap<>();

private static Registry<Enchantment> currentEnchantmentRegistry;

private static Registry<Enchantment> getEnchantmentRegistry(boolean refresh) {
if (refresh || currentEnchantmentRegistry == null) {
if (currentEnchantmentRegistry == null && !refresh) {
LibrarianTradeFinder.LOGGER.warn("Enchantment registry is null!");
}
assert MinecraftClient.getInstance().world != null;
currentEnchantmentRegistry = MinecraftClient.getInstance().world
.getRegistryManager().get(RegistryKeys.ENCHANTMENT);
}
return currentEnchantmentRegistry;
}

private static Registry<Enchantment> getEnchantmentRegistry() {
return getEnchantmentRegistry(false);
}

public void save() {
try {
Files.deleteIfExists(configFile);
Expand All @@ -45,8 +69,18 @@ public void save() {
json.addProperty("slowMode", slowMode);

JsonObject enchantmentsJson = new JsonObject();
enchantments.forEach((enchantment, enchantmentOption) -> enchantmentsJson.add(Registries.ENCHANTMENT.getEntry(enchantment).getKey().orElseThrow().getValue().toString(), enchantmentOption.toJson()));
json.add("enchantments", enchantmentsJson);

enchantmentConfigs.forEach((resLocation, enchantmentOption) ->
enchantmentsJson.add(resLocation, enchantmentOption.toJson()));

if (MinecraftClient.getInstance().world != null) {
Registry<Enchantment> enchantmentRegistry = getEnchantmentRegistry();
enchantments.forEach((enchantment, enchantmentOption) -> enchantmentsJson.add(
enchantmentRegistry.getEntry(enchantment).getKey().orElseThrow()
.getValue().toString(),
enchantmentOption.toJson()));
json.add("enchantments", enchantmentsJson);
}

Files.writeString(configFile, gson.toJson(json));
} catch (IOException e) {
Expand All @@ -62,6 +96,11 @@ public void load() {
}
JsonObject json = gson.fromJson(Files.readString(configFile), JsonObject.class);

Registry<Enchantment> enchantmentRegistry = getEnchantmentRegistry(true);

enchantments.clear();
enchantmentConfigs.clear();

if(!(!json.has("configVersion") || json.get("configVersion").getAsInt() != 1)) {
if (json.has("preventAxeBreaking"))
preventAxeBreaking = json.getAsJsonPrimitive("preventAxeBreaking").getAsBoolean();
Expand All @@ -74,21 +113,28 @@ public void load() {
if (json.has("enchantments")) {
JsonObject enchantmentsJson = json.getAsJsonObject("enchantments");
enchantmentsJson.entrySet().forEach(entry -> {
RegistryKey<Enchantment> enchantmentKey = RegistryKey.of(Registries.ENCHANTMENT.getKey(), Identifier.tryParse(entry.getKey()));
Enchantment enchantment = Registries.ENCHANTMENT.get(enchantmentKey);
if (enchantment != null) {
enchantments.put(enchantment, EnchantmentOption.fromJson(entry.getValue().getAsJsonObject()));
EnchantmentOption enchantmentOption = EnchantmentOption.fromJson(entry.getValue().getAsJsonObject());
if (enchantmentOption != null) {
enchantmentConfigs.put(entry.getKey(), enchantmentOption);
}
});
}
}

for(Enchantment enchantment : Registries.ENCHANTMENT) {
if(!enchantments.containsKey(enchantment)) {
if(!enchantment.isAvailableForEnchantedBookOffer()) continue;
enchantments.put(enchantment, new EnchantmentOption(enchantment, false));
}

final TagKey<Enchantment> tradeableTag = TagKey.of(enchantmentRegistry.getKey(),
Identifier.of("minecraft","tradeable"));
for (Enchantment enchantment : enchantmentRegistry) {
RegistryKey<Enchantment> enchantmentKey = enchantmentRegistry.getKey(enchantment).orElseThrow();
boolean availableAsTrade = enchantmentRegistry.entryOf(enchantmentKey).isIn(tradeableTag);
if (!availableAsTrade) continue;
String resLocation = enchantmentKey.getValue().toString();
EnchantmentOption enchantmentOption =
enchantmentConfigs.containsKey(resLocation)
? enchantmentConfigs.get(resLocation)
: new EnchantmentOption(enchantment, false);
enchantments.put(enchantment, enchantmentOption);
}

sortEnchantmentsMap();

save();
Expand All @@ -99,7 +145,7 @@ public void load() {

private void sortEnchantmentsMap() {
enchantments = enchantments.entrySet().stream()
.sorted(Map.Entry.comparingByKey(Comparator.comparing(enchantment -> enchantment.getName(enchantment.getMaxLevel()).copy().formatted(Formatting.WHITE).getString())))
.sorted(Map.Entry.comparingByKey(Comparator.comparing(enchantment -> Enchantment.getName(RegistryEntry.of(enchantment), enchantment.getMaxLevel()).copy().formatted(Formatting.WHITE).getString())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

Expand All @@ -122,15 +168,15 @@ public EnchantmentOption(Enchantment enchantment, boolean enabled) {
}

public static EnchantmentOption fromJson(JsonObject json) {
RegistryKey<Enchantment> enchantmentKey = RegistryKey.of(Registries.ENCHANTMENT.getKey(), Identifier.tryParse(json.getAsJsonPrimitive("enchantment").getAsString()));
Enchantment enchantment = Registries.ENCHANTMENT.get(enchantmentKey);
RegistryKey<Enchantment> enchantmentKey = RegistryKey.of(RegistryKeys.ENCHANTMENT, Identifier.tryParse(json.getAsJsonPrimitive("enchantment").getAsString()));
Enchantment enchantment = getEnchantmentRegistry().get(enchantmentKey);
if (enchantment == null) return null;
return new EnchantmentOption(enchantment, json.getAsJsonPrimitive("enabled").getAsBoolean(), json.getAsJsonPrimitive("level").getAsInt(), json.getAsJsonPrimitive("maxPrice").getAsInt());
}

public JsonObject toJson() {
JsonObject json = new JsonObject();
json.addProperty("enchantment", Registries.ENCHANTMENT.getEntry(enchantment).getKey().orElseThrow().getValue().toString());
json.addProperty("enchantment", getEnchantmentRegistry().getEntry(enchantment).getKey().orElseThrow().getValue().toString());
json.addProperty("enabled", enabled);
json.addProperty("level", level);
json.addProperty("maxPrice", maxPrice);
Expand Down Expand Up @@ -162,7 +208,7 @@ public int getMaxPrice() {
}

public String getName() {
return enchantment.getName(level).copy().formatted(Formatting.WHITE).getString();
return Enchantment.getName(RegistryEntry.of(enchantment), level).copy().formatted(Formatting.WHITE).getString();
}
}

Expand Down
11 changes: 8 additions & 3 deletions src/main/java/de/greenman999/mixin/ClientConnectionMixin.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import net.minecraft.network.packet.c2s.play.CloseHandledScreenC2SPacket;
import net.minecraft.network.packet.s2c.play.OpenScreenS2CPacket;
import net.minecraft.network.packet.s2c.play.SetTradeOffersS2CPacket;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
Expand Down Expand Up @@ -46,7 +47,7 @@ private void onChannelRead0(ChannelHandlerContext channelHandlerContext, Packet<
AtomicBoolean found = new AtomicBoolean(false);
for(TradeOffer tradeOffer : setTradeOffersS2CPacket.getOffers()) {
if(!tradeOffer.getSellItem().getItem().equals(Items.ENCHANTED_BOOK)) continue;
EnchantmentHelper.getEnchantments(tradeOffer.getSellItem()).getEnchantmentsMap().forEach((enchantmentEntry) -> {
EnchantmentHelper.getEnchantments(tradeOffer.getSellItem()).getEnchantmentEntries().forEach((enchantmentEntry) -> {
Enchantment enchantment = enchantmentEntry.getKey().value();
int level = enchantmentEntry.getIntValue();
int maxBookPrice;
Expand All @@ -58,7 +59,8 @@ private void onChannelRead0(ChannelHandlerContext channelHandlerContext, Packet<
minLevel = enchantmentOption.getLevel();
}
else {
if (!enchantment.getName(enchantment.getMaxLevel()).equals(TradeFinder.enchantment.getName(enchantment.getMaxLevel()))) return;
if (!Enchantment.getName(RegistryEntry.of(enchantment), enchantment.getMaxLevel()).equals(
Enchantment.getName(RegistryEntry.of(TradeFinder.enchantment), enchantment.getMaxLevel()))) return;
maxBookPrice = TradeFinder.maxBookPrice;
minLevel = TradeFinder.minLevel;
}
Expand All @@ -78,7 +80,10 @@ private void onChannelRead0(ChannelHandlerContext channelHandlerContext, Packet<
private void foundEnchantment(AtomicBoolean found, TradeOffer tradeOffer, Enchantment enchantment, int level) {
TradeFinder.stop();
found.set(true);
MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable("librarian-trade-finder.found", enchantment.getName(level), tradeOffer.getOriginalFirstBuyItem().getCount()).formatted(Formatting.GREEN));
MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(Text.translatable(
"librarian-trade-finder.found",
Enchantment.getName(RegistryEntry.of(enchantment), level),
tradeOffer.getOriginalFirstBuyItem().getCount()).formatted(Formatting.GREEN));
}

}
6 changes: 1 addition & 5 deletions src/main/java/de/greenman999/screens/EnchantmentEntry.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public void render(DrawContext context, int index, int y, int x, int entryWidth,
}else {
context.fill(x, y, x + entryWidth, y + entryHeight, 0x1AC7C0C0);
}
context.drawTextWithShadow(MinecraftClient.getInstance().textRenderer, Text.translatable(enchantment.getTranslationKey()), 8, y + (entryHeight / 2 / 2), 0xFFFFFF);
context.drawTextWithShadow(MinecraftClient.getInstance().textRenderer, enchantment.description(), 8, y + (entryHeight / 2 / 2), 0xFFFFFF);

matrices.push();
RenderSystem.enableDepthTest();
Expand Down Expand Up @@ -159,10 +159,7 @@ public static void renderMultilineTooltip(DrawContext context, TextRenderer text

matrices.push();
RenderSystem.enableDepthTest();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferBuilder = tessellator.getBuffer();
RenderSystem.setShader(GameRenderer::getPositionColorProgram);
bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION_COLOR);
TooltipBackgroundRenderer.render(
context,
drawX,
Expand All @@ -174,7 +171,6 @@ public static void renderMultilineTooltip(DrawContext context, TextRenderer text
RenderSystem.enableDepthTest();
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
BufferRenderer.drawWithGlobalProgram(bufferBuilder.end());
RenderSystem.disableBlend();
matrices.translate(0.0, 0.0, z + 10.0);

Expand Down
6 changes: 3 additions & 3 deletions src/main/resources/fabric.mod.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
],
"accessWidener" : "librarian-trade-finder.accesswidener",
"depends": {
"fabricloader": ">=0.14.13",
"minecraft": ["1.20.5", "1.20.6"],
"java": ">=17",
"fabricloader": ">=0.15.11",
"minecraft": ["1.21.1"],
"java": ">=21",
"fabric-api": "*"
}
}
2 changes: 1 addition & 1 deletion src/main/resources/librarian-trade-finder.accesswidener
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ accessible class net/minecraft/enchantment/EnchantmentHelper$Consumer

extendable method net/minecraft/client/gui/widget/EntryListWidget getEntryAtPosition (DD)Lnet/minecraft/client/gui/widget/EntryListWidget$Entry;

accessible method net/minecraft/enchantment/EnchantmentHelper forEachEnchantment (Lnet/minecraft/enchantment/EnchantmentHelper$Consumer;Lnet/minecraft/item/ItemStack;)V
accessible method net/minecraft/enchantment/EnchantmentHelper forEachEnchantment (Lnet/minecraft/item/ItemStack;Lnet/minecraft/enchantment/EnchantmentHelper$Consumer;)V

accessible field net/minecraft/client/gui/screen/Screen drawables Ljava/util/List;

0 comments on commit f66651f

Please sign in to comment.