Skip to content

Commit

Permalink
Use reflection to unfreeze the built-in item registry to prevent star…
Browse files Browse the repository at this point in the history
…tup error.
  • Loading branch information
rolyPolyVole committed Aug 9, 2024
1 parent dbeda50 commit 9b9690e
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
package net.slqmy.firework_wars_plugin.items.manager;

import net.minecraft.core.DefaultedMappedRegistry;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.slqmy.firework_wars_plugin.FireworkWarsPlugin;
import net.slqmy.firework_wars_plugin.items.FireworkRifleItem;
import net.slqmy.firework_wars_plugin.items.RifleAmmo;
import net.slqmy.firework_wars_plugin.items.nms.CustomCrossbow;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class CustomItemManager {
private final FireworkWarsPlugin plugin;

private final Map<String, AbstractItem> itemRegistry = new HashMap<>();
private final Map<String, Item> nmsItemRegistry = new HashMap<>();

public CustomItemManager(FireworkWarsPlugin plugin) {
this.plugin = plugin;

registerItem(new FireworkRifleItem(plugin));
registerItem(new RifleAmmo(plugin));

reopenItemRegistry();

registerNMSItem(
"firework_rifle_crossbow",
new CustomCrossbow(CustomCrossbow.PROPERTIES, getItem("firework_rifle_ammo")));

BuiltInRegistries.ITEM.freeze();
}

public Map<String, AbstractItem> getItemRegistry() {
Expand All @@ -47,4 +62,19 @@ private void registerNMSItem(String id, Item item) {
Items.registerItem(id, item);
nmsItemRegistry.put(id, item);
}

private void reopenItemRegistry() {
try {
Field frozenField = MappedRegistry.class.getDeclaredField("frozen");
Field unregisteredHoldersField = MappedRegistry.class.getDeclaredField("unregisteredIntrusiveHolders");

frozenField.setAccessible(true);
unregisteredHoldersField.setAccessible(true);

frozenField.setBoolean(BuiltInRegistries.ITEM, false);
unregisteredHoldersField.set(BuiltInRegistries.ITEM, new IdentityHashMap<>());
} catch (IllegalAccessException | NoSuchFieldException e) {
plugin.getLogger().severe("Failed to reopen the item registry! " + e.getMessage());
}
}
}

0 comments on commit 9b9690e

Please sign in to comment.