[1.21.1] ModLoading cleanup and optimisations (#10052)

This commit is contained in:
Paint_Ninja authored and GitHub committed 2024-08-16 22:49:11 +01:00
1 parent f106ff0c21
commit 9714512c31
101 files changed
+837 -841

No files matched your search

@@ -141,7 +141,6 @@ import net.minecraftforge.common.ForgeConfig;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.IExtensionPoint;
import net.minecraftforge.fml.ModList;
@@ -202,7 +201,7 @@ public class ForgeHooksClient {
}
public static void clearGuiLayers(Minecraft minecraft) {
while(guiLayers.size() > 0)
while (!guiLayers.isEmpty())
popGuiLayerInternal(minecraft);
}
@@ -221,7 +220,7 @@ public class ForgeHooksClient {
}
public static void popGuiLayer(Minecraft minecraft) {
if (guiLayers.size() == 0) {
if (guiLayers.isEmpty()) {
minecraft.setScreen(null);
return;
}
@@ -310,7 +309,7 @@ public class ForgeHooksClient {
if (idx == -1)
return base + complex;
String name = complex.substring(idx + 1, complex.length());
String name = complex.substring(idx + 1);
if (idx > 1) {
String domain = complex.substring(0, idx);
return domain + ':' + base + name;
@@ -320,9 +319,7 @@ public class ForgeHooksClient {
}
public static float getFieldOfViewModifier(Player entity, float fovModifier) {
ComputeFovModifierEvent fovModifierEvent = new ComputeFovModifierEvent(entity, fovModifier);
MinecraftForge.EVENT_BUS.post(fovModifierEvent);
return fovModifierEvent.getNewFovModifier();
return MinecraftForge.EVENT_BUS.fire(new ComputeFovModifierEvent(entity, fovModifier)).getNewFovModifier();
}
/**
@@ -333,41 +330,52 @@ public class ForgeHooksClient {
//RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance);
}
private static VersionChecker.Status getForgeVersionStatus() {
final class LazyInit {
private static final VersionChecker.Status INSTANCE = ForgeVersion.getStatus();
static {
forgeStatusLine = switch (INSTANCE) {
// case FAILED -> " Version check failed";
// case UP_TO_DATE -> "Forge up to date";
// case AHEAD -> "Using non-recommended Forge build, issues may arise.";
case OUTDATED, BETA_OUTDATED -> I18n.get("forge.update.newversion", ForgeVersion.getTarget());
default -> null;
};
}
private LazyInit() {}
}
return LazyInit.INSTANCE;
}
public static void renderMainMenu(TitleScreen gui, GuiGraphics graphics, Font font, int width, int height, int alpha) {
VersionChecker.Status status = ForgeVersion.getStatus();
VersionChecker.Status status = getForgeVersionStatus();
if (status == VersionChecker.Status.BETA || status == VersionChecker.Status.BETA_OUTDATED) {
// Render a warning at the top of the screen
Component line = Component.translatable("forge.update.beta.1", ChatFormatting.RED, ChatFormatting.RESET).withStyle(ChatFormatting.RED);
graphics.drawCenteredString(font, line, width / 2, 4 + (0 * (font.lineHeight + 1)), 0xFFFFFF | alpha);
graphics.drawCenteredString(font, line, width / 2, 4, 0xFFFFFF | alpha);
line = Component.translatable("forge.update.beta.2");
graphics.drawCenteredString(font, line, width / 2, 4 + (1 * (font.lineHeight + 1)), 0xFFFFFF | alpha);
graphics.drawCenteredString(font, line, width / 2, 4 + (font.lineHeight + 1), 0xFFFFFF | alpha);
}
forgeStatusLine = switch(status) {
// case FAILED -> " Version check failed";
// case UP_TO_DATE -> "Forge up to date";
// case AHEAD -> "Using non-recommended Forge build, issues may arise.";
case OUTDATED, BETA_OUTDATED -> I18n.get("forge.update.newversion", ForgeVersion.getTarget());
default -> null;
};
}
public static String forgeStatusLine;
@Nullable
public static SoundInstance playSound(SoundEngine manager, SoundInstance sound) {
PlaySoundEvent e = new PlaySoundEvent(manager, sound);
MinecraftForge.EVENT_BUS.post(e);
return e.getSound();
return MinecraftForge.EVENT_BUS.fire(new PlaySoundEvent(manager, sound)).getSound();
}
public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
guiGraphics.pose().pushPose();
guiLayers.forEach(layer -> {
for (Screen layer : guiLayers) {
// Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted.
drawScreenInternal(layer, guiGraphics, Integer.MAX_VALUE, Integer.MAX_VALUE, partialTick);
guiGraphics.pose().translate(0, 0, 10000);
});
}
drawScreenInternal(screen, guiGraphics, mouseX, mouseY, partialTick);
guiGraphics.pose().popPose();
}
@@ -535,8 +543,7 @@ public class ForgeHooksClient {
public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) {
if (currentGameMode != newGameMode) {
ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode);
MinecraftForge.EVENT_BUS.post(evt);
MinecraftForge.EVENT_BUS.post(new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode));
}
}
@@ -563,8 +570,7 @@ public class ForgeHooksClient {
}
public static void onRecipesUpdated(RecipeManager mgr) {
Event event = new RecipesUpdatedEvent(mgr);
MinecraftForge.EVENT_BUS.post(event);
MinecraftForge.EVENT_BUS.post(new RecipesUpdatedEvent(mgr));
}
public static void onKeyInput(int key, int scanCode, int action, int modifiers) {
@@ -589,7 +595,7 @@ public class ForgeHooksClient {
public static SpriteContents loadSpriteContents(ResourceLocation name, Resource resource, FrameSize frameSize, NativeImage image, ResourceMetadata animationMeta) {
try {
ForgeTextureMetadata forgeMeta = ForgeTextureMetadata.forResource(resource);
return forgeMeta.getLoader() == null ? null : forgeMeta.getLoader().loadContents(name, resource, frameSize, image, animationMeta, forgeMeta);
return forgeMeta.loader() == null ? null : forgeMeta.loader().loadContents(name, resource, frameSize, image, animationMeta, forgeMeta);
} catch (IOException e) {
LOGGER.error("Unable to get Forge metadata for {}, falling back to vanilla loading", name);
e.printStackTrace();
@@ -599,10 +605,10 @@ public class ForgeHooksClient {
@Nullable
public static TextureAtlasSprite loadTextureAtlasSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) {
if (contents.forgeMeta == null || contents.forgeMeta.getLoader() == null)
if (contents.forgeMeta == null || contents.forgeMeta.loader() == null)
return null;
return contents.forgeMeta.getLoader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
return contents.forgeMeta.loader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
}
private static final Map<ModelLayerLocation, Supplier<LayerDefinition>> layerDefinitions = new HashMap<>();
@@ -612,7 +618,9 @@ public class ForgeHooksClient {
}
public static void loadLayerDefinitions(ImmutableMap.Builder<ModelLayerLocation, LayerDefinition> builder) {
layerDefinitions.forEach((k, v) -> builder.put(k, v.get()));
for (var entry : layerDefinitions.entrySet()) {
builder.put(entry.getKey(), entry.getValue().get());
}
}
public static void processForgeListPingData(ServerStatus packet, ServerData target) {
@@ -716,7 +724,7 @@ public class ForgeHooksClient {
}
private static Connection getClientConnection() {
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null;
return Minecraft.getInstance().getConnection() != null ? Minecraft.getInstance().getConnection().getConnection() : null;
}
public static void handleClientLevelClosing(ClientLevel level) {
@@ -825,8 +833,7 @@ public class ForgeHooksClient {
Font font = getTooltipFont(stack, fallbackFont);
var event = new RenderTooltipEvent.GatherComponents(stack, screenWidth, screenHeight, elements, -1);
MinecraftForge.EVENT_BUS.post(event);
if (event.isCanceled()) return List.of();
if (MinecraftForge.EVENT_BUS.post(event)) return List.of();
// text wrapping
int tooltipTextWidth = event.getTooltipElements().stream()
@@ -891,9 +898,7 @@ public class ForgeHooksClient {
}
public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) {
final ScreenEvent.RenderInventoryMobEffects event = new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset);
MinecraftForge.EVENT_BUS.post(event);
return event;
return MinecraftForge.EVENT_BUS.fire(new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset));
}
public static boolean onToastAdd(Toast toast) {
@@ -45,7 +45,10 @@ public final class ItemDecoratorHandler
var event = new RegisterItemDecorationsEvent(decorators);
ModLoader.get().postEventWrapContainerInModOrder(event);
var builder = new ImmutableMap.Builder<Item, ItemDecoratorHandler>();
decorators.forEach((item, itemDecorators) -> builder.put(item, new ItemDecoratorHandler(itemDecorators)));
for (var entry : decorators.entrySet()) {
Item item = entry.getKey();
builder.put(item, new ItemDecoratorHandler(entry.getValue()));
}
DECORATOR_LOOKUP = builder.build();
}
@@ -7,6 +7,7 @@ package net.minecraftforge.client;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
@@ -31,7 +32,12 @@ public final class PresetEditorManager
Map<ResourceKey<WorldPreset>, PresetEditor> gatheredEditors = new HashMap<>();
// Vanilla's map uses Optional<ResourceKey>s as its keys.
// As far as we can tell there's no good reason for this, so we'll just use regular keys.
PresetEditor.EDITORS.forEach((k, v) -> k.ifPresent(key -> gatheredEditors.put(key, v)));
for (var entry : PresetEditor.EDITORS.entrySet()) {
var key = entry.getKey().orElse(null);
if (key != null) {
gatheredEditors.put(key, entry.getValue());
}
}
// Gather mods' entries
RegisterPresetEditorsEvent event = new RegisterPresetEditorsEvent(gatheredEditors);
@@ -5,8 +5,6 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.RecipeBookCategories;
import net.minecraft.world.inventory.RecipeBookType;
import net.minecraft.world.item.crafting.Recipe;
@@ -57,14 +55,14 @@ public final class RecipeBookManager {
@ApiStatus.Internal
public static void init() {
// The ImmutableMap is the patched out value of AGGREGATE_CATEGORIES
var aggregateCategories = new HashMap<>(ImmutableMap.of(
RecipeBookCategories.CRAFTING_SEARCH, ImmutableList.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE),
RecipeBookCategories.FURNACE_SEARCH, ImmutableList.of(RecipeBookCategories.FURNACE_FOOD, RecipeBookCategories.FURNACE_BLOCKS, RecipeBookCategories.FURNACE_MISC),
RecipeBookCategories.BLAST_FURNACE_SEARCH, ImmutableList.of(RecipeBookCategories.BLAST_FURNACE_BLOCKS, RecipeBookCategories.BLAST_FURNACE_MISC),
RecipeBookCategories.SMOKER_SEARCH, ImmutableList.of(RecipeBookCategories.SMOKER_FOOD)
var aggregateCategories = new HashMap<>(Map.of(
RecipeBookCategories.CRAFTING_SEARCH, List.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE),
RecipeBookCategories.FURNACE_SEARCH, List.of(RecipeBookCategories.FURNACE_FOOD, RecipeBookCategories.FURNACE_BLOCKS, RecipeBookCategories.FURNACE_MISC),
RecipeBookCategories.BLAST_FURNACE_SEARCH, List.of(RecipeBookCategories.BLAST_FURNACE_BLOCKS, RecipeBookCategories.BLAST_FURNACE_MISC),
RecipeBookCategories.SMOKER_SEARCH, List.of(RecipeBookCategories.SMOKER_FOOD)
));
var typeCategories = new HashMap<RecipeBookType, ImmutableList<RecipeBookCategories>>();
var typeCategories = new HashMap<RecipeBookType, List<RecipeBookCategories>>();
var recipeCategoryLookups = new HashMap<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>>();
var event = new RegisterRecipeBookCategoriesEvent(aggregateCategories, typeCategories, recipeCategoryLookups);
ModLoader.get().postEventWrapContainerInModOrder(event);
@@ -78,8 +78,7 @@ public final class ForgeEventFactoryClient {
* @return the event object passed in and possibly modified by listeners
*/
private static <E extends Event> E fire(E e) {
post(e);
return e;
return MinecraftForge.EVENT_BUS.fire(e);
}
/**
@@ -5,7 +5,6 @@
package net.minecraftforge.client.event;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.RecipeBookCategories;
import net.minecraft.world.inventory.RecipeBookType;
import net.minecraft.world.item.crafting.Recipe;
@@ -31,14 +30,14 @@ import java.util.function.Function;
*/
public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusEvent
{
private final Map<RecipeBookCategories, ImmutableList<RecipeBookCategories>> aggregateCategories;
private final Map<RecipeBookType, ImmutableList<RecipeBookCategories>> typeCategories;
private final Map<RecipeBookCategories, List<RecipeBookCategories>> aggregateCategories;
private final Map<RecipeBookType, List<RecipeBookCategories>> typeCategories;
private final Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> recipeCategoryLookups;
@ApiStatus.Internal
public RegisterRecipeBookCategoriesEvent(
Map<RecipeBookCategories, ImmutableList<RecipeBookCategories>> aggregateCategories,
Map<RecipeBookType, ImmutableList<RecipeBookCategories>> typeCategories,
Map<RecipeBookCategories, List<RecipeBookCategories>> aggregateCategories,
Map<RecipeBookType, List<RecipeBookCategories>> typeCategories,
Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> recipeCategoryLookups)
{
this.aggregateCategories = aggregateCategories;
@@ -51,7 +50,7 @@ public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusE
*/
public void registerAggregateCategory(RecipeBookCategories category, List<RecipeBookCategories> others)
{
aggregateCategories.put(category, ImmutableList.copyOf(others));
aggregateCategories.put(category, List.copyOf(others));
}
/**
@@ -59,7 +58,7 @@ public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusE
*/
public void registerBookCategories(RecipeBookType type, List<RecipeBookCategories> categories)
{
typeCategories.put(type, ImmutableList.copyOf(categories));
typeCategories.put(type, List.copyOf(categories));
}
/**
@@ -21,60 +21,44 @@ import java.util.Optional;
/**
* The "forge" section of texture metadata files (.mcmeta). Currently used only to specify custom
* TextureAtlasSprite loaders.
*
* @see ITextureAtlasSpriteLoader
*/
public final class ForgeTextureMetadata
{
public record ForgeTextureMetadata(@Nullable ITextureAtlasSpriteLoader loader) {
public static final ForgeTextureMetadata EMPTY = new ForgeTextureMetadata(null);
public static final MetadataSectionSerializer<ForgeTextureMetadata> SERIALIZER = new Serializer();
public static ForgeTextureMetadata forResource(Resource resource) throws IOException {
Optional<ForgeTextureMetadata> metadata = resource.metadata().getSection(SERIALIZER);
return metadata.isEmpty() ? EMPTY : metadata.get();
return metadata.orElse(EMPTY);
}
@Nullable
private final ITextureAtlasSpriteLoader loader;
public ForgeTextureMetadata(@Nullable ITextureAtlasSpriteLoader loader)
{
this.loader = loader;
}
@Nullable
public ITextureAtlasSpriteLoader getLoader()
{
public ITextureAtlasSpriteLoader getLoader() {
return loader;
}
private static final class Serializer implements MetadataSectionSerializer<ForgeTextureMetadata>
{
private static final class Serializer implements MetadataSectionSerializer<ForgeTextureMetadata> {
@Override
@NotNull
public String getMetadataSectionName()
{
public String getMetadataSectionName() {
return "forge";
}
@Override
@NotNull
public ForgeTextureMetadata fromJson(JsonObject json)
{
public ForgeTextureMetadata fromJson(JsonObject json) {
@Nullable
ITextureAtlasSpriteLoader loader;
if (json.has("loader"))
{
if (json.has("loader")) {
ResourceLocation loaderName = ResourceLocation.parse(GsonHelper.getAsString(json, "loader"));
loader = TextureAtlasSpriteLoaderManager.get(loaderName);
if (loader == null)
{
if (loader == null) {
throw new JsonSyntaxException("Unknown TextureAtlasSpriteLoader " + loaderName);
}
}
else
{
} else {
loader = null;
}
return new ForgeTextureMetadata(loader);
@@ -13,35 +13,31 @@ import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* Manager for {@link ITextureAtlasSpriteLoader} instances.
* <p>
* Provides a lookup.
*/
public final class TextureAtlasSpriteLoaderManager
{
private static ImmutableMap<ResourceLocation, ITextureAtlasSpriteLoader> LOADERS;
public final class TextureAtlasSpriteLoaderManager {
private static Map<ResourceLocation, ITextureAtlasSpriteLoader> LOADERS;
/**
* Finds the loader with the given name, or null if none is registered.
*/
@Nullable
public static ITextureAtlasSpriteLoader get(ResourceLocation name)
{
public static ITextureAtlasSpriteLoader get(ResourceLocation name) {
return LOADERS.get(name);
}
@ApiStatus.Internal
public static void init()
{
public static void init() {
var loaders = new HashMap<ResourceLocation, ITextureAtlasSpriteLoader>();
var event = new RegisterTextureAtlasSpriteLoadersEvent(loaders);
ModLoader.get().postEventWrapContainerInModOrder(event);
LOADERS = ImmutableMap.copyOf(loaders);
}
private TextureAtlasSpriteLoaderManager()
{
}
private TextureAtlasSpriteLoaderManager() {}
}
@@ -21,7 +21,7 @@ import net.minecraft.world.level.biome.Biome;
public class BiomeManager
{
private static TrackedList<BiomeEntry>[] biomes = setupBiomes();
private static final TrackedList<BiomeEntry>[] biomes = setupBiomes();
private static final List<ResourceKey<Biome>> additionalOverworldBiomes = new ArrayList<>();
private static final List<ResourceKey<Biome>> additionalOverworldBiomesView = Collections.unmodifiableList(additionalOverworldBiomes);
@@ -109,7 +109,7 @@ public final class CreativeModeTabRegistry {
@Override
protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) {
try {
if (data.size() > 0) {
if (!data.isEmpty()) {
JsonArray order = GsonHelper.getAsJsonArray(data, "order");
List<CreativeModeTab> customOrder = new ArrayList<>();
for (JsonElement entry : order) {
@@ -183,8 +183,9 @@ public final class CreativeModeTabRegistry {
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.OP_BLOCKS));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.INVENTORY));
final List<Holder<CreativeModeTab>> indexed = new ArrayList<>();
BuiltInRegistries.CREATIVE_MODE_TAB.holders().filter(c -> !DEFAULT_TABS.contains(c.get())).forEach(indexed::add);
final List<Holder<CreativeModeTab>> indexed = BuiltInRegistries.CREATIVE_MODE_TAB.holders()
.filter(c -> !DEFAULT_TABS.contains(c.get()))
.collect(Collectors.toList());
int vanillaTabs = 10;
for (int i = 0; i < vanillaTabs; i++) { // Vanilla ordering
@@ -632,7 +632,7 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
if (count > currentPath.size())
throw new IllegalArgumentException("Attempted to pop " + count + " elements when we only had: " + currentPath);
for (int x = 0; x < count; x++)
currentPath.remove(currentPath.size() - 1);
currentPath.removeLast();
return this;
}
@@ -644,10 +644,14 @@ public class ForgeConfigSpec extends UnmodifiableConfigWrapper<UnmodifiableConfi
public ForgeConfigSpec build() {
context.ensureEmpty();
Config valueCfg = Config.of(Config.getDefaultMapCreator(true, true), InMemoryFormat.withSupport(ConfigValue.class::isAssignableFrom));
values.forEach(v -> valueCfg.set(v.getPath(), v));
for (ConfigValue<?> value : values) {
valueCfg.set(value.getPath(), value);
}
ForgeConfigSpec ret = new ForgeConfigSpec(storage, valueCfg, levelComments, levelTranslationKeys);
values.forEach(v -> v.spec = ret);
for (ConfigValue<?> v : values) {
v.spec = ret;
}
return ret;
}
@@ -30,8 +30,8 @@ public class ForgeI18n {
// From FontRenderer.renderCharAtPos
private static final String ALLOWED_CHARS = "\u00c0\u00c1\u00c2\u00c8\u00ca\u00cb\u00cd\u00d3\u00d4\u00d5\u00da\u00df\u00e3\u00f5\u011f\u0130\u0131\u0152\u0153\u015e\u015f\u0174\u0175\u017e\u0207\u0000\u0000\u0000\u0000\u0000\u0000\u0000 !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u0000\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00f8\u00a3\u00d8\u00d7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u00ae\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580\u03b1\u03b2\u0393\u03c0\u03a3\u03c3\u03bc\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u2205\u2208\u2229\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u0000";
private static final CharMatcher DISALLOWED_CHAR_MATCHER = CharMatcher.anyOf(ALLOWED_CHARS).negate();
private static Map<String,String> i18n;
private static Map<String,FormatFactory> customFactories;
private static Map<String, String> i18n;
private static final Map<String, FormatFactory> customFactories;
// From StringUtils
private static final Pattern PATTERN_CONTROL_CODE = Pattern.compile("(?i)\\u00A7[0-9A-FK-OR]");
@@ -60,11 +60,11 @@ public class ForgeInternalHandler {
WorldWorkerManager.tick(false);
}
@SubscribeEvent
public void checkSettings(ClientTickEvent event) {
//if (event.phase == Phase.END)
// CloudRenderer.updateCloudSettings();
}
// @SubscribeEvent
// public void checkSettings(ClientTickEvent event) {
// if (event.phase == Phase.END)
// CloudRenderer.updateCloudSettings();
// }
@SubscribeEvent
public void onChunkUnload(ChunkEvent.Unload event) {
@@ -399,7 +399,9 @@ public class ForgeMod {
modEventBus.addListener(this::registerFluids);
modEventBus.addListener(this::registerVanillaDisplayContexts);
modEventBus.register(this);
registries.forEach(r -> r.register(modEventBus));
for (DeferredRegister<?> r : registries) {
r.register(modEventBus);
}
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
@@ -92,14 +92,14 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
private static class ColorRegisterHandler {
@SubscribeEvent(priority = EventPriority.HIGHEST)
public static void registerSpawnEggColors(RegisterColorHandlersEvent.Item event) {
MOD_EGGS.forEach(egg -> {
for (ForgeSpawnEggItem egg : MOD_EGGS) {
event.register((stack, layer) -> {
int color = egg.getColor(layer);
if (FastColor.ARGB32.alpha(color) == 0)
color = FastColor.ARGB32.opaque(color);
return color;
}, egg);
});
}
}
}
}
@@ -29,11 +29,12 @@ public class VillagerTradingManager
static
{
VillagerTrades.TRADES.entrySet().forEach(e ->
{
VillagerTrades.TRADES.forEach((key, value) -> {
Int2ObjectMap<ItemListing[]> copy = new Int2ObjectOpenHashMap<>();
e.getValue().int2ObjectEntrySet().forEach(ent -> copy.put(ent.getIntKey(), Arrays.copyOf(ent.getValue(), ent.getValue().length)));
VANILLA_TRADES.put(e.getKey(), copy);
for (var ent : value.int2ObjectEntrySet()) {
copy.put(ent.getIntKey(), Arrays.copyOf(ent.getValue(), ent.getValue().length));
}
VANILLA_TRADES.put(key, copy);
});
VillagerTrades.WANDERING_TRADER_TRADES.int2ObjectEntrySet().forEach(e -> WANDERER_TRADES.put(e.getIntKey(), Arrays.copyOf(e.getValue(), e.getValue().length)));
}
@@ -71,13 +72,14 @@ public class VillagerTradingManager
{
mutableTrades.put(i, NonNullList.create());
}
trades.int2ObjectEntrySet().forEach(e ->
{
Arrays.stream(e.getValue()).forEach(mutableTrades.get(e.getIntKey())::add);
});
for (var entry : trades.int2ObjectEntrySet()) {
Arrays.stream(entry.getValue()).forEach(mutableTrades.get(entry.getIntKey())::add);
}
MinecraftForge.EVENT_BUS.post(new VillagerTradesEvent(mutableTrades, prof));
Int2ObjectMap<ItemListing[]> newTrades = new Int2ObjectOpenHashMap<>();
mutableTrades.int2ObjectEntrySet().forEach(e -> newTrades.put(e.getIntKey(), e.getValue().toArray(new ItemListing[0])));
for (var entry : mutableTrades.int2ObjectEntrySet()) {
newTrades.put(entry.getIntKey(), entry.getValue().toArray(new ItemListing[0]));
}
VillagerTrades.TRADES.put(prof, newTrades);
}
}
@@ -10,7 +10,7 @@ import java.util.List;
public class WorldWorkerManager
{
private static List<IWorker> workers = new ArrayList<IWorker>();
private static final List<IWorker> workers = new ArrayList<>();
private static long startTime = -1;
private static int index = 0;
@@ -13,6 +13,8 @@ import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Allows modders to register custom entity selectors by assigning an {@link IEntitySelectorType} to a String token. <br>
@@ -21,6 +23,7 @@ import java.util.HashMap;
public class EntitySelectorManager
{
private static final HashMap<String, IEntitySelectorType> REGISTRY = new HashMap<>();
private static final List<String> RESERVED_TOKENS = List.of("p", "a", "r", "s", "e");
/**
* Registers a new {@link IEntitySelectorType} for the given {@code token}.<br>
@@ -34,7 +37,7 @@ public class EntitySelectorManager
throw new IllegalArgumentException("Token must not be empty");
}
if (Arrays.asList("p", "a", "r", "s", "e").contains(token))
if (RESERVED_TOKENS.contains(token))
{
throw new IllegalArgumentException("Token clashes with vanilla @" + token);
}
@@ -78,6 +81,10 @@ public class EntitySelectorManager
*/
public static void fillSelectorSuggestions(SuggestionsBuilder suggestionBuilder)
{
REGISTRY.forEach((token, type) -> suggestionBuilder.suggest("@" + token, type.getSuggestionTooltip()));
for (var entry : REGISTRY.entrySet()) {
String token = entry.getKey();
IEntitySelectorType type = entry.getValue();
suggestionBuilder.suggest("@" + token, type.getSuggestionTooltip());
}
}
}
@@ -7,6 +7,7 @@ package net.minecraftforge.common.crafting;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Stream;
@@ -61,10 +62,10 @@ public class ConditionalRecipe {
}
public static class Builder {
private List<InnerRecipe> recipes = new ArrayList<>();
private List<InnerAdvancement> advancements = new ArrayList<>();
private final List<InnerRecipe> recipes = new ArrayList<>();
private final List<InnerAdvancement> advancements = new ArrayList<>();
private RecipeOutput bouncer = new RecipeOutput() {
private final RecipeOutput bouncer = new RecipeOutput() {
@Override
public void accept(ResourceLocation id, Recipe<?> value, @Nullable AdvancementHolder advancement) {
recipe(id, value, advancement);
@@ -221,7 +222,7 @@ public class ConditionalRecipe {
var count = new Holder<Integer>();
count.value = -1;
var ret = stream.map(entry -> accept(context, ops, count, entry))
.filter(entry -> entry != null)
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
@@ -273,7 +274,7 @@ public class ConditionalRecipe {
}
};
private static class Holder<T> {
private static final class Holder<T> {
private T value;
}
}
@@ -59,7 +59,7 @@ public class SimpleCraftingContainer {
int height = this.rows.size();
if (height == 0)
throw new IllegalStateException("Invalid builder, empty inventory");
int width = this.rows.get(0).length();
int width = this.rows.getFirst().length();
var items = NonNullList.withSize(width * height, ItemStack.EMPTY);
int idx = 0;
@@ -35,7 +35,7 @@ public class CompoundIngredient extends AbstractIngredient {
return new CompoundIngredient(Arrays.asList(children));
}
private List<Ingredient> children;
private final List<Ingredient> children;
private ItemStack[] stacks;
private IntList itemIds;
private final boolean isSimple;
@@ -109,7 +109,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
};
public static class Builder {
private List<ItemLike> items = new ArrayList<>();
private final List<ItemLike> items = new ArrayList<>();
private CompoundTag nbt;
public Builder nbt(CompoundTag value) {
@@ -253,10 +253,10 @@ public abstract class SoundDefinitionsProvider implements DataProvider
private CompletableFuture<?> save(final CachedOutput cache, final Path targetFile)
{
return DataProvider.saveStable(cache, this.mapToJson(this.sounds), targetFile);
return DataProvider.saveStable(cache, mapToJson(this.sounds), targetFile);
}
private JsonObject mapToJson(final Map<String, SoundDefinition> map)
private static JsonObject mapToJson(final Map<String, SoundDefinition> map)
{
final JsonObject obj = new JsonObject();
// namespaces are ignored when serializing
@@ -49,7 +49,11 @@ public abstract class SpriteSourceProvider extends JsonCodecProvider<List<Sprite
protected final void gather(BiConsumer<ResourceLocation, List<SpriteSource>> consumer)
{
addSources();
atlases.forEach((atlas, srcList) -> consumer.accept(atlas, srcList.sources));
for (var entry : atlases.entrySet()) {
ResourceLocation atlas = entry.getKey();
SourceList srcList = entry.getValue();
consumer.accept(atlas, srcList.sources);
}
}
protected abstract void addSources();
@@ -11,8 +11,8 @@ import net.minecraft.world.level.ChunkPos;
// Sorter to load nearby chunks first
public class CenterChunkPosComparator implements java.util.Comparator<ChunkPos>
{
private int x;
private int z;
private final int x;
private final int z;
public CenterChunkPosComparator(ServerPlayer entityplayer)
{
@@ -30,7 +30,7 @@ public class ConcatenatedListView<T> implements List<T>
{
return switch (members.size()) {
case 0 -> List.of();
case 1 -> Collections.unmodifiableList(members.get(0));
case 1 -> Collections.unmodifiableList(members.getFirst());
default -> new ConcatenatedListView<>(members);
};
}
@@ -46,7 +46,7 @@ public class HexDumper {
private static final String HEX = "0123456789ABCDEF";
private final int marked;
private final StringBuilder buf;
private char[] ascii = new char[16];
private final char[] ascii = new char[16];
private int index = 0;
private Instance(int marked, int size) {
@@ -15,7 +15,7 @@ import org.jetbrains.annotations.Nullable;
public class LevelCapabilityData extends SavedData {
public static final String ID = "capabilities";
private INBTSerializable<CompoundTag> serializable;
private final INBTSerializable<CompoundTag> serializable;
private CompoundTag capNBT = null;
public LevelCapabilityData(@Nullable INBTSerializable<CompoundTag> serializable) {
@@ -325,7 +325,7 @@ public class MutableHashedLinkedMap<K, V> implements Iterable<Map.Entry<K, V>>
Value apply(Key key, Value left, Value right);
}
private class Entry implements Map.Entry<K, V>
private final class Entry implements Map.Entry<K, V>
{
private final K key;
private V value;
@@ -374,7 +374,7 @@ public class MutableHashedLinkedMap<K, V> implements Iterable<Map.Entry<K, V>>
}
}
private static class BasicStrategy implements Strategy<Object> {
private static final class BasicStrategy implements Strategy<Object> {
@Override
public int hashCode(Object o) {
return Objects.hashCode(o);
@@ -386,7 +386,7 @@ public class MutableHashedLinkedMap<K, V> implements Iterable<Map.Entry<K, V>>
}
}
private static class IdentityStrategy implements Strategy<Object> {
private static final class IdentityStrategy implements Strategy<Object> {
@Override
public int hashCode(Object o) {
return System.identityHashCode(o);
@@ -8,6 +8,7 @@ package net.minecraftforge.common.util;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
@@ -25,7 +26,7 @@ public class SortedProperties extends Properties {
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
Set<Map.Entry<Object, Object>> ret = new TreeSet<>((left, right) -> left.getKey().toString().compareTo(right.getKey().toString()));
Set<Map.Entry<Object, Object>> ret = new TreeSet<>(Comparator.comparing(entry -> entry.getKey().toString()));
ret.addAll(super.entrySet());
return ret;
}
@@ -125,9 +125,9 @@ public class TextTable
public static class Column
{
private String header;
private final String header;
private int width;
private Alignment alignment;
private final Alignment alignment;
public Column(String header)
{
@@ -302,19 +302,12 @@ public final class TransformationHelper
Quaternionf ret;
try
{
if (entry.getKey().equals("x"))
{
ret = Axis.XP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
}
else if (entry.getKey().equals("y"))
{
ret = Axis.YP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
}
else if (entry.getKey().equals("z"))
{
ret = Axis.ZP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
}
else throw new JsonParseException("Axis rotation: expected single axis key, got: " + entry.getKey());
ret = switch (entry.getKey()) {
case "x" -> Axis.XP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
case "y" -> Axis.YP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
case "z" -> Axis.ZP.rotationDegrees(entry.getValue().getAsNumber().floatValue());
default -> throw new JsonParseException("Axis rotation: expected single axis key, got: " + entry.getKey());
};
}
catch(ClassCastException ex)
{
@@ -17,10 +17,12 @@ public class BiomeGenerationSettingsBuilder extends BiomeGenerationSettings.Plai
{
public BiomeGenerationSettingsBuilder(BiomeGenerationSettings orig)
{
orig.getCarvingStages().forEach(k -> {
for (GenerationStep.Carving k : orig.getCarvingStages()) {
carvers.put(k, new ArrayList<>());
orig.getCarvers(k).forEach(v -> carvers.get(k).add(v));
});
for (Holder<ConfiguredWorldCarver<?>> v : orig.getCarvers(k)) {
carvers.get(k).add(v);
}
}
orig.features().forEach(l -> {
final ArrayList<Holder<PlacedFeature>> featureList = new ArrayList<>();
l.forEach(featureList::add);
@@ -5,11 +5,9 @@
package net.minecraftforge.internal;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.IntStream;
import java.util.function.ObjIntConsumer;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
@@ -19,20 +17,20 @@ import net.minecraftforge.fml.ModList;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.versions.mcp.MCPVersion;
public class BrandingControl {
public final class BrandingControl {
private BrandingControl() {}
private static List<String> brandings;
private static List<String> brandingsNoMC;
private static List<String> overCopyrightBrandings;
private static void computeBranding() {
if (brandings == null) {
ImmutableList.Builder<String> brd = ImmutableList.builder();
brd.add("Forge " + ForgeVersion.getVersion());
brd.add("Minecraft " + MCPVersion.getMCVersion());
brd.add("MCP " + MCPVersion.getMCPVersion());
int tModCount = ModList.get().size();
brd.add(ForgeI18n.parseMessage("fml.menu.loadingmods", tModCount));
brandings = brd.build();
brandings = List.of(
"Forge " + ForgeVersion.getVersion(),
"Minecraft " + MCPVersion.getMCVersion(),
"MCP " + MCPVersion.getMCPVersion(),
ForgeI18n.parseMessage("fml.menu.loadingmods", ModList.get().size())
);
brandingsNoMC = brandings.subList(1, brandings.size());
}
}
@@ -40,34 +38,36 @@ public class BrandingControl {
private static List<String> getBrandings(boolean includeMC, boolean reverse) {
computeBranding();
if (includeMC)
return reverse ? Lists.reverse(brandings) : brandings;
return reverse ? brandings.reversed() : brandings;
else
return reverse ? Lists.reverse(brandingsNoMC) : brandingsNoMC;
return reverse ? brandingsNoMC.reversed() : brandingsNoMC;
}
private static void computeOverCopyrightBrandings() {
if (overCopyrightBrandings == null) {
ImmutableList.Builder<String> brd = ImmutableList.builder();
if (ForgeHooksClient.forgeStatusLine != null) brd.add(ForgeHooksClient.forgeStatusLine);
overCopyrightBrandings = brd.build();
public static List<String> getOverCopyrightBrandings() {
final class LazyInit {
private static final List<String> INSTANCE = ForgeHooksClient.forgeStatusLine == null
? Collections.emptyList()
: List.of(ForgeHooksClient.forgeStatusLine);
private LazyInit() {}
}
return LazyInit.INSTANCE;
}
public static void forEachLine(boolean includeMC, boolean reverse, BiConsumer<Integer, String> lineConsumer) {
final List<String> brandings = getBrandings(includeMC, reverse);
IntStream.range(0, brandings.size()).boxed().forEachOrdered(idx -> lineConsumer.accept(idx, brandings.get(idx)));
public static void forEachLine(boolean includeMC, boolean reverse, ObjIntConsumer<String> lineConsumer) {
var brandings = getBrandings(includeMC, reverse);
for (int idx = 0; idx < brandings.size(); idx++)
lineConsumer.accept(brandings.get(idx), idx);
}
public static void forEachAboveCopyrightLine(BiConsumer<Integer, String> lineConsumer) {
computeOverCopyrightBrandings();
IntStream.range(0, overCopyrightBrandings.size()).boxed().forEachOrdered(idx->lineConsumer.accept(idx, overCopyrightBrandings.get(idx)));
public static void forEachAboveCopyrightLine(ObjIntConsumer<String> lineConsumer) {
var overCopyrightBrandings = getOverCopyrightBrandings();
for (int idx = 0; idx < overCopyrightBrandings.size(); idx++)
lineConsumer.accept(overCopyrightBrandings.get(idx), idx);
}
public static String getClientBranding() {
return "forge";
}
public static String getServerBranding() {
public static String getBranding() {
return "forge";
}
@@ -15,15 +15,9 @@ import net.minecraftforge.fml.event.config.ModConfigEvent;
import java.util.function.Supplier;
public class ForgeBindings implements IBindingsProvider {
@Override
public Supplier<IEventBus> getForgeBusSupplier() {
return ()-> MinecraftForge.EVENT_BUS;
}
@Override
public Supplier<I18NParser> getMessageParser() {
return ()->new I18NParser() {
public final class ForgeBindings implements IBindingsProvider {
private static final class LazyInit {
private static final Supplier<I18NParser> INSTANCE = () -> new I18NParser() {
@Override
public String parseMessage(final String i18nMessage, final Object... args) {
return ForgeI18n.parseMessage(i18nMessage, args);
@@ -34,10 +28,22 @@ public class ForgeBindings implements IBindingsProvider {
return ForgeI18n.stripControlCodes(toStrip);
}
};
private LazyInit() {}
}
@Override
public Supplier<IEventBus> getForgeBusSupplier() {
return () -> MinecraftForge.EVENT_BUS;
}
@Override
public Supplier<I18NParser> getMessageParser() {
return LazyInit.INSTANCE;
}
@Override
public Supplier<IConfigEvent.ConfigConfig> getConfigConfiguration() {
return ()->new IConfigEvent.ConfigConfig(ModConfigEvent.Loading::new, ModConfigEvent.Reloading::new, ModConfigEvent.Unloading::new);
return () -> new IConfigEvent.ConfigConfig(ModConfigEvent.Loading::new, ModConfigEvent.Reloading::new, ModConfigEvent.Unloading::new);
}
}
@@ -22,7 +22,7 @@ import java.text.SimpleDateFormat;
import java.util.*;
public class CrashReportExtender {
private static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
private static final String LINE_SEPARATOR = System.lineSeparator();
public static void extendSystemReport(final SystemReport systemReport) {
for (final ISystemReportExtender call : CrashReportCallables.allCrashCallables()) {
if (call.isActive())
@@ -44,8 +44,8 @@ public class ChannelListManager {
.build();
private record Register(List<String> channels) implements CustomPacketPayload {
private static Type<Register> TYPE = CustomPacketPayload.createType("register");
private static StreamCodec<FriendlyByteBuf, Register> CODEC = StreamCodec.of(
private static final Type<Register> TYPE = CustomPacketPayload.createType("register");
private static final StreamCodec<FriendlyByteBuf, Register> CODEC = StreamCodec.of(
(buf, v) -> encode(buf, v.channels),
buf -> new Register(decode(buf))
);
@@ -57,8 +57,8 @@ public class ChannelListManager {
}
private record Unregister(List<String> channels) implements CustomPacketPayload {
private static Type<Unregister> TYPE = CustomPacketPayload.createType("unregister");
private static StreamCodec<FriendlyByteBuf, Unregister> CODEC = StreamCodec.of(
private static final Type<Unregister> TYPE = CustomPacketPayload.createType("unregister");
private static final StreamCodec<FriendlyByteBuf, Unregister> CODEC = StreamCodec.of(
(buf, v) -> encode(buf, v.channels),
buf -> new Unregister(decode(buf))
);
@@ -31,6 +31,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntRBTreeMap;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.nbt.Tag;
import net.minecraft.tags.TagKey;
import net.minecraftforge.common.util.LogMessageAdapter;
import net.minecraftforge.fml.ModLoadingContext;
@@ -794,7 +795,11 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
//Public for tests
public Snapshot makeSnapshot() {
Snapshot ret = new Snapshot();
this.ids.forEach((id, value) -> ret.ids.put(getKey(value), id));
for (Entry<Integer, V> entry : this.ids.entrySet()) {
Integer id = entry.getKey();
V value = entry.getValue();
ret.ids.put(getKey(value), id.intValue());
}
ret.aliases.putAll(this.aliases);
ret.blocked.addAll(this.blocked);
ret.overrides.putAll(getOverrideOwners());
@@ -862,19 +867,19 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
data.put("ids", ids);
ListTag aliases = new ListTag();
this.aliases.entrySet().forEach(e -> {
this.aliases.forEach((k, v) -> {
CompoundTag tag = new CompoundTag();
tag.putString("K", e.getKey().toString());
tag.putString("V", e.getValue().toString());
tag.putString("K", k.toString());
tag.putString("V", v.toString());
aliases.add(tag);
});
data.put("aliases", aliases);
ListTag overrides = new ListTag();
this.overrides.entrySet().forEach(e -> {
this.overrides.forEach((k, v) -> {
CompoundTag tag = new CompoundTag();
tag.putString("K", e.getKey().toString());
tag.putString("V", e.getValue());
tag.putString("K", k.toString());
tag.putString("V", v);
overrides.add(tag);
});
data.put("overrides", overrides);
@@ -891,22 +896,22 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
return ret;
ListTag list = nbt.getList("ids", 10);
list.forEach(e -> {
CompoundTag comp = (CompoundTag)e;
for (Tag tag : list) {
CompoundTag comp = (CompoundTag) tag;
ret.ids.put(ResourceLocation.parse(comp.getString("K")), comp.getInt("V"));
});
}
list = nbt.getList("aliases", 10);
list.forEach(e -> {
CompoundTag comp = (CompoundTag)e;
for (Tag tag : list) {
CompoundTag comp = (CompoundTag) tag;
ret.aliases.put(ResourceLocation.parse(comp.getString("K")), ResourceLocation.parse(comp.getString("V")));
});
}
list = nbt.getList("overrides", 10);
list.forEach(e -> {
CompoundTag comp = (CompoundTag)e;
for (Tag tag : list) {
CompoundTag comp = (CompoundTag) tag;
ret.overrides.put(ResourceLocation.parse(comp.getString("K")), comp.getString("V"));
});
}
int[] blocked = nbt.getIntArray("blocked");
for (int i : blocked)
@@ -976,20 +981,24 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
}
} else {
// block item missing, warn as requested and block the id
if (action == MissingMappingsEvent.Action.DEFAULT) {
V m = this.missing == null ? null : this.missing.createMissing(remap.key, injectNetworkDummies);
if (m == null)
defaulted.add(remap.key);
else
this.add(remap.id, remap.key, m, remap.key.getNamespace());
} else if (action == MissingMappingsEvent.Action.IGNORE) {
LOGGER.debug(REGISTRIES,"Ignoring {}", remap.key);
ignored++;
} else if (action == MissingMappingsEvent.Action.FAIL) {
LOGGER.debug(REGISTRIES,"Failing {}!", remap.key);
failed.add(remap.key);
} else if (action == MissingMappingsEvent.Action.WARN) {
LOGGER.warn(REGISTRIES,"{} may cause world breakage!", remap.key);
switch (action) {
case DEFAULT -> {
V m = this.missing == null ? null : this.missing.createMissing(remap.key, injectNetworkDummies);
if (m == null)
defaulted.add(remap.key);
else
this.add(remap.id, remap.key, m, remap.key.getNamespace());
}
case IGNORE -> {
LOGGER.debug(REGISTRIES, "Ignoring {}", remap.key);
ignored++;
}
case FAIL -> {
LOGGER.debug(REGISTRIES, "Failing {}!", remap.key);
failed.add(remap.key);
}
case WARN -> LOGGER.warn(REGISTRIES, "{} may cause world breakage!", remap.key);
case null, default -> {}
}
this.block(remap.id);
}
@@ -514,12 +514,12 @@ public class GameData {
throw new IllegalStateException("Could not get holder for " + key + " " + obj);
}
obj.matchingStates().forEach((state) -> {
for (BlockState state : obj.matchingStates()) {
var oldType = map.put(state, holder);
if (oldType != null) {
throw new IllegalStateException(String.format(Locale.ENGLISH, "Point of interest types %s and %s both list %s in their blockstates, this is not allowed. Blockstates can only have one point of interest type each.", oldType, obj, state));
}
});
}
}
@Override
@@ -53,10 +53,10 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
Lifecycle registryLifecycle = Lifecycle.stable();
private boolean frozen = false; // Frozen is vanilla's variant of locked, but it can be unfrozen
private List<Holder.Reference<T>> holdersSorted;
private ObjectList<Holder.Reference<T>> holdersById = new ObjectArrayList<>(256);
private Map<ResourceLocation, Holder.Reference<T>> holdersByName = new HashMap<>();
private Map<T, Holder.Reference<T>> holders = new IdentityHashMap<>();
private RegistryManager stage;
private final ObjectList<Holder.Reference<T>> holdersById = new ObjectArrayList<>(256);
private final Map<ResourceLocation, Holder.Reference<T>> holdersByName = new HashMap<>();
private final Map<T, Holder.Reference<T>> holders = new IdentityHashMap<>();
private final RegistryManager stage;
private volatile Map<TagKey<T>, HolderSet.Named<T>> tags = new IdentityHashMap<>();
private final Map<ResourceKey<T>, RegistrationInfo> registrationInfos = new IdentityHashMap<>();
@@ -323,7 +323,9 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
@Override
public void bindTags(Map<TagKey<T>, List<Holder<T>>> newTags) {
Map<Holder.Reference<T>, List<TagKey<T>>> holderToTag = new IdentityHashMap<>();
this.holdersByName.values().forEach(v -> holderToTag.put(v, new ArrayList<>()));
for (Holder.Reference<T> tReference : this.holdersByName.values()) {
holderToTag.put(tReference, new ArrayList<>());
}
newTags.forEach((name, values) -> values.forEach(holder -> addTagToHolder(holderToTag, name, holder)));
Set<TagKey<T>> set = new HashSet<>(Sets.difference(this.tags.keySet(), newTags.keySet()));
@@ -336,15 +338,17 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
newTags.forEach((k, v) -> tmpTags.computeIfAbsent(k, this::createTag).bind(v));
Set<TagKey<T>> defaultedTags = Sets.difference(this.optionalTags.keySet(), newTags.keySet());
defaultedTags.forEach(name -> {
for (TagKey<T> name : defaultedTags) {
List<Holder<T>> defaults = this.optionalTags.get(name).stream()
.map(valueSupplier -> getHolder(valueSupplier.get()).orElse(null))
.filter(Objects::nonNull)
.distinct()
.toList();
defaults.forEach(holder -> addTagToHolder(holderToTag, name, holder));
for (Holder<T> holder : defaults) {
addTagToHolder(holderToTag, name, holder);
}
tmpTags.computeIfAbsent(name, this::createTag).bind(defaults);
});
}
holderToTag.forEach(Holder.Reference::bindTags);
this.tags = tmpTags;
@@ -221,16 +221,13 @@ public class ObjectHolderRegistry
public static void applyObjectHolders(Predicate<ResourceLocation> filter)
{
RuntimeException aggregate = new RuntimeException("Failed to apply some object holders, see suppressed exceptions for details");
objectHolders.forEach(objectHolder -> {
try
{
for (Consumer<Predicate<ResourceLocation>> objectHolder : objectHolders) {
try {
objectHolder.accept(filter);
}
catch (Exception e)
{
} catch (Exception e) {
aggregate.addSuppressed(e);
}
});
}
if (aggregate.getSuppressed().length > 0)
{
@@ -5,7 +5,6 @@
package net.minecraftforge.registries;
import com.google.common.collect.Lists;
import net.minecraft.core.Holder;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry.AddCallback;
@@ -15,6 +14,8 @@ import net.minecraftforge.registries.IForgeRegistry.CreateCallback;
import net.minecraftforge.registries.IForgeRegistry.MissingFactory;
import net.minecraftforge.registries.IForgeRegistry.ValidateCallback;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -39,18 +40,18 @@ public class RegistryBuilder<T> {
private ResourceLocation optionalDefaultKey;
private int minId = 0;
private int maxId = MAX_ID;
private List<AddCallback<T>> addCallback = Lists.newArrayList();
private List<ClearCallback<T>> clearCallback = Lists.newArrayList();
private List<CreateCallback<T>> createCallback = Lists.newArrayList();
private List<ValidateCallback<T>> validateCallback = Lists.newArrayList();
private List<BakeCallback<T>> bakeCallback = Lists.newArrayList();
private final List<AddCallback<T>> addCallback = new ArrayList<>();
private final List<ClearCallback<T>> clearCallback = new ArrayList<>();
private final List<CreateCallback<T>> createCallback = new ArrayList<>();
private final List<ValidateCallback<T>> validateCallback = new ArrayList<>();
private final List<BakeCallback<T>> bakeCallback = new ArrayList<>();
private boolean saveToDisc = true;
private boolean sync = true;
private boolean allowOverrides = true;
private boolean allowModifications = false;
private boolean hasWrapper = false;
private MissingFactory<T> missingFactory;
private Set<ResourceLocation> legacyNames = new HashSet<>();
private final Set<ResourceLocation> legacyNames = new HashSet<>();
@Nullable
private Function<T, Holder.Reference<T>> intrusiveHolderCallback = null;
@@ -206,8 +207,8 @@ public class RegistryBuilder<T> {
IForgeRegistry<T> create() {
if (hasWrapper) {
GameData.WrapperFactory<T> wrapper = GameData.createWrapperFactory(getDefault() != null);
this.addCallback.add(0, wrapper);
this.createCallback.add(0, wrapper);
this.addCallback.addFirst(wrapper);
this.createCallback.addFirst(wrapper);
}
return RegistryManager.ACTIVE.createRegistry(registryName, this);
}
@@ -217,7 +218,7 @@ public class RegistryBuilder<T> {
if (addCallback.isEmpty())
return null;
if (addCallback.size() == 1)
return addCallback.get(0);
return addCallback.getFirst();
var tmp = this.addCallback;
return (owner, stage, id, key, obj, old) -> {
@@ -231,7 +232,7 @@ public class RegistryBuilder<T> {
if (clearCallback.isEmpty())
return null;
if (clearCallback.size() == 1)
return clearCallback.get(0);
return clearCallback.getFirst();
var tmp = this.clearCallback;
return (owner, stage) -> {
@@ -245,7 +246,7 @@ public class RegistryBuilder<T> {
if (createCallback.isEmpty())
return null;
if (createCallback.size() == 1)
return createCallback.get(0);
return createCallback.getFirst();
var tmp = this.createCallback;
return (owner, stage) -> {
@@ -259,7 +260,7 @@ public class RegistryBuilder<T> {
if (validateCallback.isEmpty())
return null;
if (validateCallback.size() == 1)
return validateCallback.get(0);
return validateCallback.getFirst();
var tmp = this.validateCallback;
return (owner, stage, id, key, obj) -> {
@@ -273,7 +274,7 @@ public class RegistryBuilder<T> {
if (bakeCallback.isEmpty())
return null;
if (bakeCallback.size() == 1)
return bakeCallback.get(0);
return bakeCallback.getFirst();
var tmp = this.bakeCallback;
return (owner, stage) -> {
@@ -7,14 +7,13 @@ package net.minecraftforge.registries;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Sets;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.WritableRegistry;
import net.minecraft.core.registries.BuiltInRegistries;
@@ -35,10 +34,10 @@ public class RegistryManager {
private static Set<ResourceLocation> vanillaRegistryKeys = Set.of();
BiMap<ResourceLocation, ForgeRegistry<?>> registries = HashBiMap.create();
private Map<ResourceLocation, ? extends IForgeRegistry<?>> registryView = Collections.unmodifiableMap(registries);
private Set<ResourceLocation> persisted = Sets.newHashSet();
private Set<ResourceLocation> synced = Sets.newHashSet();
private Map<ResourceLocation, ResourceLocation> legacyNames = new HashMap<>();
private final Map<ResourceLocation, ? extends IForgeRegistry<?>> registryView = Collections.unmodifiableMap(registries);
private final Set<ResourceLocation> persisted = new HashSet<>();
private final Set<ResourceLocation> synced = new HashSet<>();
private final Map<ResourceLocation, ResourceLocation> legacyNames = new HashMap<>();
private final String name;
RegistryManager() {
@@ -152,7 +151,9 @@ public class RegistryManager {
public Map<ResourceLocation, Snapshot> takeSnapshot(boolean savingToDisc) {
Map<ResourceLocation, Snapshot> ret = new HashMap<>();
var keys = savingToDisc ? this.persisted : this.synced;
keys.forEach(name -> ret.put(name, getRegistry(name).makeSnapshot()));
for (ResourceLocation key : keys) {
ret.put(key, getRegistry(key).makeSnapshot());
}
return ret;
}
@@ -26,7 +26,7 @@ public final class RegistryObject<T> implements Supplier<T> {
@Nullable
private final ResourceLocation name;
@Nullable
private ResourceKey<T> key;
private final ResourceKey<T> key;
private final boolean optionalRegistry;
@Nullable
private T value;
@@ -189,7 +189,8 @@ public final class RegistryObject<T> implements Supplier<T> {
@Override
public T get() {
T ret = this.value;
Objects.requireNonNull(ret, () -> "Registry Object not present: " + this.name);
if (ret == null)
throw new NullPointerException("Registry Object not present: " + this.name);
return ret;
}