|
5 | 5 | import net.minecraft.core.Registry; |
6 | 6 | import net.minecraft.core.RegistryAccess; |
7 | 7 | import net.minecraft.resources.ResourceKey; |
| 8 | +import org.jetbrains.annotations.Nullable; |
| 9 | + |
| 10 | +import java.util.HashMap; |
| 11 | +import java.util.Map; |
8 | 12 |
|
9 | 13 | public class RegistryUtil { |
| 14 | + private static final Map<ResourceKey<? extends Registry<?>>, Registry<?>> REGISTRY_CACHE = new HashMap<>(); |
| 15 | + private static @Nullable RegistryAccess REGISTRY_ACCESS; |
| 16 | + |
10 | 17 | public static <T> Registry<T> getRegistry(ResourceKey<? extends Registry<T>> key) { |
| 18 | + Registry<?> registry = REGISTRY_CACHE.get(key); |
| 19 | + if (registry == null) { |
| 20 | + registry = getRegistryUncached(key); |
| 21 | + REGISTRY_CACHE.put(key, registry); |
| 22 | + } |
| 23 | + @SuppressWarnings("unchecked") |
| 24 | + Registry<T> castRegistry = (Registry<T>) registry; |
| 25 | + return castRegistry; |
| 26 | + } |
| 27 | + |
| 28 | + private static Registry<?> getRegistryUncached(ResourceKey<? extends Registry<?>> key) { |
11 | 29 | RegistryAccess registryAccess = getRegistryAccess(); |
12 | 30 | return registryAccess.registryOrThrow(key); |
13 | 31 | } |
14 | 32 |
|
15 | 33 | public static RegistryAccess getRegistryAccess() { |
16 | | - Minecraft minecraft = Minecraft.getInstance(); |
17 | | - ClientLevel level = minecraft.level; |
18 | | - if (level == null) { |
19 | | - throw new IllegalStateException("Could not get registry, registry access is unavailable because the level is currently null"); |
| 34 | + if (REGISTRY_ACCESS == null) { |
| 35 | + Minecraft minecraft = Minecraft.getInstance(); |
| 36 | + ClientLevel level = minecraft.level; |
| 37 | + if (level == null) { |
| 38 | + throw new IllegalStateException("Could not get registry, registry access is unavailable because the level is currently null"); |
| 39 | + } |
| 40 | + REGISTRY_ACCESS = level.registryAccess(); |
20 | 41 | } |
21 | | - return level.registryAccess(); |
| 42 | + return REGISTRY_ACCESS; |
| 43 | + } |
| 44 | + |
| 45 | + public static void setRegistryAccess(@Nullable RegistryAccess registryAccess) { |
| 46 | + REGISTRY_ACCESS = registryAccess; |
| 47 | + REGISTRY_CACHE.clear(); |
22 | 48 | } |
23 | 49 | } |
0 commit comments