Initial port to 1.18

Co-authored-by: David Quintana <[email protected]>
Co-authored-by: SizableShrimp <[email protected]>
This commit is contained in:
committed 2021-11-30 17:42:18 +00:00
1 parent be0a6819ac
commit 40a174310d
538 files changed
+3322 -9030

No files matched your search

@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.registry;
package net.minecraftforge.client;
import net.minecraft.world.entity.Entity;
import net.minecraft.resources.ResourceLocation;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient;
package net.minecraftforge.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient;
package net.minecraftforge.client;
public class ExtendedServerListData {
public final String type;
@@ -19,7 +19,6 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
@@ -65,7 +64,6 @@ import net.minecraft.client.resources.model.Material;
import net.minecraft.client.renderer.texture.TextureAtlas;
import com.mojang.blaze3d.platform.NativeImage;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import com.mojang.blaze3d.vertex.VertexFormatElement.Usage;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.KeyMapping;
import net.minecraft.world.entity.Entity;
@@ -101,8 +99,7 @@ import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.*;
import net.minecraftforge.client.event.sound.PlaySoundEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.animation.Animation;
import net.minecraftforge.client.model.ForgeModelBakery;
import net.minecraftforge.client.textures.ForgeTextureMetadata;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.MinecraftForge;
@@ -111,28 +108,22 @@ import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.*;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fmlclient.ExtendedServerListData;
import net.minecraftforge.fmlclient.registry.ClientRegistry;
import net.minecraftforge.fmllegacy.ForgeI18n;
import net.minecraftforge.fmllegacy.network.FMLNetworkConstants;
import net.minecraftforge.fmllegacy.network.NetworkRegistry;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.network.NetworkConstants;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.resource.VanillaResourceType;
import net.minecraftforge.versions.forge.ForgeVersion;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.lwjgl.opengl.GL13;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -152,8 +143,6 @@ import java.util.stream.Stream;
import static net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType.BOSSINFO;
import static net.minecraftforge.fml.VersionChecker.Status.BETA;
import static net.minecraftforge.fml.VersionChecker.Status.BETA_OUTDATED;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import net.minecraft.client.Camera;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
@@ -225,8 +214,7 @@ public class ForgeHooksClient
return result != null ? result : _default;
}
//TODO: Rename to onDrawHighlight
public static boolean onDrawBlockHighlight(LevelRenderer context, Camera info, HitResult target, float partialTicks, PoseStack matrix, MultiBufferSource buffers)
public static boolean onDrawHighlight(LevelRenderer context, Camera info, HitResult target, float partialTicks, PoseStack matrix, MultiBufferSource buffers)
{
switch (target.getType()) {
case BLOCK:
@@ -242,7 +230,7 @@ public class ForgeHooksClient
public static void dispatchRenderLast(LevelRenderer context, PoseStack mat, float partialTicks, Matrix4f projectionMatrix, long finishTimeNano)
{
MinecraftForge.EVENT_BUS.post(new RenderWorldLastEvent(context, mat, partialTicks, projectionMatrix, finishTimeNano));
MinecraftForge.EVENT_BUS.post(new RenderLevelLastEvent(context, mat, partialTicks, projectionMatrix, finishTimeNano));
}
public static boolean renderSpecificFirstPersonHand(InteractionHand hand, PoseStack mat, MultiBufferSource buffers, int light, float partialTicks, float interpPitch, float swingProgress, float equipProgress, ItemStack stack)
@@ -275,11 +263,11 @@ public class ForgeHooksClient
ModLoader.get().postEvent(new ColorHandlerEvent.Item(itemColors, blockColors));
}
static final ThreadLocal<RenderType> renderLayer = new ThreadLocal<RenderType>();
static final ThreadLocal<RenderType> renderType = new ThreadLocal<RenderType>();
public static void setRenderLayer(RenderType layer)
public static void setRenderType(RenderType layer)
{
renderLayer.set(layer);
renderType.set(layer);
}
public static <A extends HumanoidModel<?>> A getArmorModel(LivingEntity entityLiving, ItemStack itemStack, EquipmentSlot slot, A _default)
@@ -308,21 +296,16 @@ public class ForgeHooksClient
return base + name;
}
}
/* TODO mouse input
public static boolean postMouseEvent()
public static float getFieldOfView(Player entity, float fov)
{
return MinecraftForge.EVENT_BUS.post(new MouseEvent());
}
*/
public static float getOffsetFOV(Player entity, float fov)
{
FOVUpdateEvent fovUpdateEvent = new FOVUpdateEvent(entity, fov);
MinecraftForge.EVENT_BUS.post(fovUpdateEvent);
return fovUpdateEvent.getNewfov();
FOVModifierEvent fovModifierEvent = new FOVModifierEvent(entity, fov);
MinecraftForge.EVENT_BUS.post(fovModifierEvent);
return fovModifierEvent.getNewfov();
}
public static double getFOVModifier(GameRenderer renderer, Camera info, double renderPartialTicks, double fov) {
EntityViewRenderEvent.FOVModifier event = new EntityViewRenderEvent.FOVModifier(renderer, info, renderPartialTicks, fov);
public static double getFieldOfView(GameRenderer renderer, Camera info, double renderPartialTicks, double fov) {
EntityViewRenderEvent.FieldOfView event = new EntityViewRenderEvent.FieldOfView(renderer, info, renderPartialTicks, fov);
MinecraftForge.EVENT_BUS.post(event);
return event.getFOV();
}
@@ -367,15 +350,7 @@ public class ForgeHooksClient
{
PlaySoundEvent e = new PlaySoundEvent(manager, sound);
MinecraftForge.EVENT_BUS.post(e);
return e.getResultSound();
}
//static RenderBlocks VertexBufferRB;
static int worldRenderPass;
public static int getWorldRenderPass()
{
return worldRenderPass;
return e.getSound();
}
public static void drawScreen(Screen screen, PoseStack mStack, int mouseX, int mouseY, float partialTicks)
@@ -392,9 +367,9 @@ public class ForgeHooksClient
private static void drawScreenInternal(Screen screen, PoseStack mStack, int mouseX, int mouseY, float partialTicks)
{
if (!MinecraftForge.EVENT_BUS.post(new GuiScreenEvent.DrawScreenEvent.Pre(screen, mStack, mouseX, mouseY, partialTicks)))
if (!MinecraftForge.EVENT_BUS.post(new ScreenEvent.DrawScreenEvent.Pre(screen, mStack, mouseX, mouseY, partialTicks)))
screen.render(mStack, mouseX, mouseY, partialTicks);
MinecraftForge.EVENT_BUS.post(new GuiScreenEvent.DrawScreenEvent.Post(screen, mStack, mouseX, mouseY, partialTicks));
MinecraftForge.EVENT_BUS.post(new ScreenEvent.DrawScreenEvent.Post(screen, mStack, mouseX, mouseY, partialTicks));
}
public static float getFogDensity(FogMode type, Camera info, float partial, float density)
@@ -416,7 +391,7 @@ public class ForgeHooksClient
return event;
}
public static void onModelBake(ModelManager modelManager, Map<ResourceLocation, BakedModel> modelRegistry, ModelLoader modelLoader)
public static void onModelBake(ModelManager modelManager, Map<ResourceLocation, BakedModel> modelRegistry, ForgeModelBakery modelLoader)
{
ModLoader.get().postEvent(new ModelBakeEvent(modelManager, modelRegistry, modelLoader));
modelLoader.onPostBakeEvent(modelRegistry);
@@ -453,112 +428,6 @@ public class ForgeHooksClient
return model;
}
// moved and expanded from WorldVertexBufferUploader.draw
public static void preDraw(Usage attrType, VertexFormat format, int element, int stride, ByteBuffer buffer)
{
VertexFormatElement attr = format.getElements().get(element);
int count = attr.getElementCount();
int constant = attr.getType().getGlType();
((Buffer)buffer).position(format.getOffset(element));
switch(attrType)
{
case POSITION:
glVertexPointer(count, constant, stride, buffer);
glEnableClientState(GL_VERTEX_ARRAY);
break;
case NORMAL:
if(count != 3)
{
throw new IllegalArgumentException("Normal attribute should have the size 3: " + attr);
}
glNormalPointer(constant, stride, buffer);
glEnableClientState(GL_NORMAL_ARRAY);
break;
case COLOR:
glColorPointer(count, constant, stride, buffer);
glEnableClientState(GL_COLOR_ARRAY);
break;
case UV:
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + attr.getIndex());
glTexCoordPointer(count, constant, stride, buffer);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
break;
case PADDING:
break;
case GENERIC:
glEnableVertexAttribArray(attr.getIndex());
glVertexAttribPointer(attr.getIndex(), count, constant, false, stride, buffer);
break;
default:
LOGGER.fatal("Unimplemented vanilla attribute upload: {}", attrType.getName());
}
}
public static void postDraw(Usage attrType, VertexFormat format, int element, int stride, ByteBuffer buffer)
{
VertexFormatElement attr = format.getElements().get(element);
switch(attrType)
{
case POSITION:
glDisableClientState(GL_VERTEX_ARRAY);
break;
case NORMAL:
glDisableClientState(GL_NORMAL_ARRAY);
break;
case COLOR:
glDisableClientState(GL_COLOR_ARRAY);
break;
case UV:
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + attr.getIndex());
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
break;
case PADDING:
break;
case GENERIC:
glDisableVertexAttribArray(attr.getIndex());
break;
default:
LOGGER.fatal("Unimplemented vanilla attribute upload: {}", attrType.getName());
}
}
public static int getColorIndex(VertexFormat fmt)
{
ImmutableList<VertexFormatElement> elements = fmt.getElements();
for(int i=0;i<elements.size();i++)
{
if (elements.get(i).getUsage() == Usage.COLOR)
return i;
}
throw new IndexOutOfBoundsException("There is no COLOR element in the provided VertexFormat.");
}
// TODO: IVertexBuilder doesn't have a means to modify existing data.
/*
public static void putQuadColor(IVertexBuilder renderer, BakedQuad quad, float cr, float cg, float cb, float ca)
{
VertexFormat format = quad.getFormat();
int size = format.getIntegerSize();
int offset = format.getOffset(getColorIndex(format)) / 4; // assumes that color is aligned
boolean hasColor = format.hasColor();
for(int i = 0; i < 4; i++)
{
int vc = hasColor ? quad.getVertexData()[offset + size * i] : 0xFFFFFFFF;
float vcr = vc & 0xFF;
float vcg = (vc >>> 8) & 0xFF;
float vcb = (vc >>> 16) & 0xFF;
float vca = (vc >>> 24) & 0xFF;
int ncr = Math.min(0xFF, (int)(cr * vcr / 0xFF));
int ncg = Math.min(0xFF, (int)(cg * vcg / 0xFF));
int ncb = Math.min(0xFF, (int)(cb * vcb / 0xFF));
int nca = Math.min(0xFF, (int)(ca * vca / 0xFF));
renderer.putColorRGBA(renderer.getColorIndex(4 - i), ncr, ncg, ncb, nca);
}
}*/
@SuppressWarnings("deprecation")
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter world, BlockPos pos, FluidState fluidStateIn)
{
@@ -659,17 +528,17 @@ public class ForgeHooksClient
return from.getItem().shouldCauseReequipAnimation(from, to, changed);
}
public static RenderGameOverlayEvent.BossInfo bossBarRenderPre(PoseStack mStack, Window res, LerpingBossEvent bossInfo, int x, int y, int increment)
public static RenderGameOverlayEvent.BossInfo renderBossEventPre(PoseStack mStack, Window res, LerpingBossEvent bossInfo, int x, int y, int increment)
{
RenderGameOverlayEvent.BossInfo evt = new RenderGameOverlayEvent.BossInfo(mStack, new RenderGameOverlayEvent(mStack, Animation.getPartialTickTime(), res),
RenderGameOverlayEvent.BossInfo evt = new RenderGameOverlayEvent.BossInfo(mStack, new RenderGameOverlayEvent(mStack, MinecraftForgeClient.getPartialTick(), res),
BOSSINFO, bossInfo, x, y, increment);
MinecraftForge.EVENT_BUS.post(evt);
return evt;
}
public static void bossBarRenderPost(PoseStack mStack, Window res)
public static void renderBossEventPost(PoseStack mStack, Window res)
{
MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(mStack, new RenderGameOverlayEvent(mStack, Animation.getPartialTickTime(), res), BOSSINFO));
MinecraftForge.EVENT_BUS.post(new RenderGameOverlayEvent.Post(mStack, new RenderGameOverlayEvent(mStack, MinecraftForgeClient.getPartialTick(), res), BOSSINFO));
}
public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile)
@@ -679,11 +548,11 @@ public class ForgeHooksClient
return event;
}
public static void onClientChangeGameMode(PlayerInfo info, GameType currentGameMode, GameType newGameMode)
public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode)
{
if (currentGameMode != newGameMode)
{
ClientPlayerChangeGameModeEvent evt = new ClientPlayerChangeGameModeEvent(info, currentGameMode, newGameMode);
ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode);
MinecraftForge.EVENT_BUS.post(evt);
}
}
@@ -698,110 +567,100 @@ public class ForgeHooksClient
return model;
}
public static void onInputUpdate(Player player, Input movementInput)
public static void onMovementInputUpdate(Player player, Input movementInput)
{
MinecraftForge.EVENT_BUS.post(new InputUpdateEvent(player, movementInput));
MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput));
}
/**
* @deprecated use {@link Minecraft#reloadResourcePacks()} instead
*/
@Deprecated(since="1.17.1", forRemoval = true)
public static void refreshResources(Minecraft mc, VanillaResourceType... types) {
mc.reloadResourcePacks();
}
public static boolean onGuiMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button)
public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button)
{
Event event = new GuiScreenEvent.MouseClickedEvent.Pre(guiScreen, mouseX, mouseY, button);
Event event = new ScreenEvent.MouseClickedEvent.Pre(guiScreen, mouseX, mouseY, button);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled)
public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled)
{
Event event = new GuiScreenEvent.MouseClickedEvent.Post(guiScreen, mouseX, mouseY, button, handled);
event.setCanceled(handled);
Event event = new ScreenEvent.MouseClickedEvent.Post(guiScreen, mouseX, mouseY, button, handled);
MinecraftForge.EVENT_BUS.post(event);
return event.getResult() == Event.Result.DEFAULT ? handled : event.getResult() == Event.Result.ALLOW;
}
public static boolean onGuiMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button)
public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button)
{
Event event = new GuiScreenEvent.MouseReleasedEvent.Pre(guiScreen, mouseX, mouseY, button);
Event event = new ScreenEvent.MouseReleasedEvent.Pre(guiScreen, mouseX, mouseY, button);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled)
public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled)
{
Event event = new GuiScreenEvent.MouseReleasedEvent.Post(guiScreen, mouseX, mouseY, button, handled);
event.setCanceled(handled);
Event event = new ScreenEvent.MouseReleasedEvent.Post(guiScreen, mouseX, mouseY, button, handled);
MinecraftForge.EVENT_BUS.post(event);
return event.getResult() == Event.Result.DEFAULT ? handled : event.getResult() == Event.Result.ALLOW;
}
public static boolean onGuiMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
public static boolean onScreenMouseDragPre(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
{
Event event = new GuiScreenEvent.MouseDragEvent.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY);
Event event = new ScreenEvent.MouseDragEvent.Pre(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
public static boolean onScreenMouseDragPost(Screen guiScreen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
{
Event event = new GuiScreenEvent.MouseDragEvent.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY);
Event event = new ScreenEvent.MouseDragEvent.Post(guiScreen, mouseX, mouseY, mouseButton, dragX, dragY);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiMouseScrollPre(MouseHandler mouseHelper, Screen guiScreen, double scrollDelta)
public static boolean onScreenMouseScrollPre(MouseHandler mouseHelper, Screen guiScreen, double scrollDelta)
{
Window mainWindow = guiScreen.getMinecraft().getWindow();
double mouseX = mouseHelper.xpos() * (double) mainWindow.getGuiScaledWidth() / (double) mainWindow.getScreenWidth();
double mouseY = mouseHelper.ypos() * (double) mainWindow.getGuiScaledHeight() / (double) mainWindow.getScreenHeight();
Event event = new GuiScreenEvent.MouseScrollEvent.Pre(guiScreen, mouseX, mouseY, scrollDelta);
Event event = new ScreenEvent.MouseScrollEvent.Pre(guiScreen, mouseX, mouseY, scrollDelta);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiMouseScrollPost(MouseHandler mouseHelper, Screen guiScreen, double scrollDelta)
public static boolean onScreenMouseScrollPost(MouseHandler mouseHelper, Screen guiScreen, double scrollDelta)
{
Window mainWindow = guiScreen.getMinecraft().getWindow();
double mouseX = mouseHelper.xpos() * (double) mainWindow.getGuiScaledWidth() / (double) mainWindow.getScreenWidth();
double mouseY = mouseHelper.ypos() * (double) mainWindow.getGuiScaledHeight() / (double) mainWindow.getScreenHeight();
Event event = new GuiScreenEvent.MouseScrollEvent.Post(guiScreen, mouseX, mouseY, scrollDelta);
Event event = new ScreenEvent.MouseScrollEvent.Post(guiScreen, mouseX, mouseY, scrollDelta);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
Event event = new GuiScreenEvent.KeyboardKeyPressedEvent.Pre(guiScreen, keyCode, scanCode, modifiers);
Event event = new ScreenEvent.KeyboardKeyPressedEvent.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
Event event = new GuiScreenEvent.KeyboardKeyPressedEvent.Post(guiScreen, keyCode, scanCode, modifiers);
Event event = new ScreenEvent.KeyboardKeyPressedEvent.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
Event event = new GuiScreenEvent.KeyboardKeyReleasedEvent.Pre(guiScreen, keyCode, scanCode, modifiers);
Event event = new ScreenEvent.KeyboardKeyReleasedEvent.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers)
{
Event event = new GuiScreenEvent.KeyboardKeyReleasedEvent.Post(guiScreen, keyCode, scanCode, modifiers);
Event event = new ScreenEvent.KeyboardKeyReleasedEvent.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiCharTypedPre(Screen guiScreen, char codePoint, int modifiers)
public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers)
{
Event event = new GuiScreenEvent.KeyboardCharTypedEvent.Pre(guiScreen, codePoint, modifiers);
Event event = new ScreenEvent.KeyboardCharTypedEvent.Pre(guiScreen, codePoint, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onGuiCharTypedPost(Screen guiScreen, char codePoint, int modifiers)
public static boolean onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers)
{
Event event = new GuiScreenEvent.KeyboardCharTypedEvent.Post(guiScreen, codePoint, modifiers);
Event event = new ScreenEvent.KeyboardCharTypedEvent.Post(guiScreen, codePoint, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
@@ -846,7 +705,7 @@ public class ForgeHooksClient
{
BakedModel layer = layerModel.getFirst();
RenderType rendertype = layerModel.getSecond();
net.minecraftforge.client.ForgeHooksClient.setRenderLayer(rendertype); // neded for compatibility with MultiLayerModels
net.minecraftforge.client.ForgeHooksClient.setRenderType(rendertype); // neded for compatibility with MultiLayerModels
VertexConsumer ivertexbuilder;
if (fabulous)
{
@@ -856,7 +715,7 @@ public class ForgeHooksClient
}
renderer.renderModelLists(layer, itemStackIn, combinedLightIn, combinedOverlayIn, matrixStackIn, ivertexbuilder);
}
net.minecraftforge.client.ForgeHooksClient.setRenderLayer(null);
net.minecraftforge.client.ForgeHooksClient.setRenderType(null);
}
public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance) {
@@ -874,39 +733,39 @@ public class ForgeHooksClient
.filter(t -> ItemBlockRenderTypes.canRenderInLayer(state, t))
.forEach(rendertype ->
{
setRenderLayer(rendertype);
setRenderType(rendertype);
VertexConsumer ivertexbuilder = buffer.getBuffer(rendertype == RenderType.translucent() ? RenderType.translucentMovingBlock() : rendertype);
blockRenderer.getModelRenderer().tesselateBlock(world, blockRenderer.getBlockModel(state), state, pos, stack, ivertexbuilder, checkSides, new Random(), state.getSeed(pos), combinedOverlay);
});
setRenderLayer(null);
setRenderType(null);
}
public static void registerForgeWorldTypeScreens()
public static void registerForgeWorldPresetScreens()
{
ForgeWorldTypeScreens.registerTypes();
ForgeWorldPresetScreens.registerPresets();
}
public static WorldPreset.PresetEditor getBiomeGeneratorTypeScreenFactory(Optional<WorldPreset> generator, @Nullable WorldPreset.PresetEditor biomegeneratortypescreens$ifactory)
public static WorldPreset.PresetEditor getPresetEditor(Optional<WorldPreset> generator, @Nullable WorldPreset.PresetEditor biomegeneratortypescreens$ifactory)
{
return ForgeWorldTypeScreens.getGeneratorScreenFactory(generator, biomegeneratortypescreens$ifactory);
return ForgeWorldPresetScreens.getPresetEditor(generator, biomegeneratortypescreens$ifactory);
}
public static boolean hasBiomeGeneratorSettingsOptionsScreen(Optional<WorldPreset> generator)
public static boolean hasPresetEditor(Optional<WorldPreset> generator)
{
return getBiomeGeneratorTypeScreenFactory(generator, null) != null;
return getPresetEditor(generator, null) != null;
}
public static Optional<WorldPreset> getWorldTypeFromGenerator(WorldGenSettings dimensionGeneratorSettings)
public static Optional<WorldPreset> getWorldPresetFromGenerator(WorldGenSettings dimensionGeneratorSettings)
{
return WorldPreset.of(dimensionGeneratorSettings);
}
public static Optional<WorldPreset> getDefaultWorldType()
public static Optional<WorldPreset> getDefaultWorldPreset()
{
return Optional.of(ForgeWorldTypeScreens.getDefaultGenerator());
return Optional.of(ForgeWorldPresetScreens.getDefaultPreset());
}
public static boolean shouldRender(MobEffectInstance effectInstance)
public static boolean shouldRenderEffect(MobEffectInstance effectInstance)
{
return RenderProperties.getEffectRenderer(effectInstance).shouldRender(effectInstance);
}
@@ -944,7 +803,7 @@ public class ForgeHooksClient
final Map<ResourceLocation, Pair<String, Boolean>> remoteChannels = packet.getForgeData().getRemoteChannels();
final int fmlver = packet.getForgeData().getFMLNetworkVersion();
boolean fmlNetMatches = fmlver == FMLNetworkConstants.FMLNETVERSION;
boolean fmlNetMatches = fmlver == NetworkConstants.FMLNETVERSION;
boolean channelsMatch = NetworkRegistry.checkListPingCompatibilityForClient(remoteChannels);
AtomicBoolean result = new AtomicBoolean(true);
final List<String> extraClientMods = new ArrayList<>();
@@ -960,7 +819,7 @@ public class ForgeHooksClient
boolean modsMatch = result.get();
final Map<String, String> extraServerMods = mods.entrySet().stream().
filter(e -> !Objects.equals(FMLNetworkConstants.IGNORESERVERONLY, e.getValue())).
filter(e -> !Objects.equals(NetworkConstants.IGNORESERVERONLY, e.getValue())).
filter(e -> !ModList.get().isLoaded(e.getKey())).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
@@ -982,10 +841,10 @@ public class ForgeHooksClient
extraReason = "fml.menu.multiplayer.networkincompatible";
}
if (fmlver < FMLNetworkConstants.FMLNETVERSION) {
if (fmlver < NetworkConstants.FMLNETVERSION) {
extraReason = "fml.menu.multiplayer.serveroutdated";
}
if (fmlver > FMLNetworkConstants.FMLNETVERSION) {
if (fmlver > NetworkConstants.FMLNETVERSION) {
extraReason = "fml.menu.multiplayer.clientoutdated";
}
target.forgeData = new ExtendedServerListData("FML", extraServerMods.isEmpty() && fmlNetMatches && channelsMatch && modsMatch, mods.size(), extraReason, packet.getForgeData().isTruncated());
@@ -1044,14 +903,14 @@ public class ForgeHooksClient
}
}
private static Connection getClientToServerNetworkManager()
private static Connection getClientConnection()
{
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null;
}
public static void handleClientWorldClosing(ClientLevel world)
public static void handleClientLevelClosing(ClientLevel world)
{
Connection client = getClientToServerNetworkManager();
Connection client = getClientConnection();
// ONLY revert a non-local connection
if (client != null && !client.isMemoryConnection())
{
@@ -1102,14 +961,14 @@ public class ForgeHooksClient
return stackFont == null ? fallbackFont : stackFont;
}
public static RenderTooltipEvent.Pre preTooltipEvent(@Nonnull ItemStack stack, PoseStack matrixStack, int x, int y, int screenWidth, int screenHeight, @Nonnull List<ClientTooltipComponent> components, @Nullable Font forcedFont, @Nonnull Font fallbackFont)
public static RenderTooltipEvent.Pre onRenderTooltipPre(@Nonnull ItemStack stack, PoseStack matrixStack, int x, int y, int screenWidth, int screenHeight, @Nonnull List<ClientTooltipComponent> components, @Nullable Font forcedFont, @Nonnull Font fallbackFont)
{
var preEvent = new RenderTooltipEvent.Pre(stack, matrixStack, x, y, screenWidth, screenHeight, getTooltipFont(forcedFont, stack, fallbackFont), components);
MinecraftForge.EVENT_BUS.post(preEvent);
return preEvent;
}
public static RenderTooltipEvent.Color colorTooltipEvent(@Nonnull ItemStack stack, PoseStack matrixStack, int x, int y, @Nonnull Font font, @Nonnull List<ClientTooltipComponent> components)
public static RenderTooltipEvent.Color onRenderTooltipColor(@Nonnull ItemStack stack, PoseStack matrixStack, int x, int y, @Nonnull Font font, @Nonnull List<ClientTooltipComponent> components)
{
var colorEvent = new RenderTooltipEvent.Color(stack, matrixStack, x, y, font, 0xf0100010, 0x505000FF, 0x5028007f, components);
MinecraftForge.EVENT_BUS.post(colorEvent);
@@ -27,7 +27,7 @@ import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraftforge.common.world.ForgeWorldType;
import net.minecraftforge.common.world.ForgeWorldPreset;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -37,14 +37,14 @@ import javax.annotation.Nullable;
import java.util.Map;
import java.util.Optional;
public class ForgeWorldTypeScreens
public class ForgeWorldPresetScreens
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Map<ForgeWorldType, WorldPreset> GENERATORS = Maps.newHashMap();
private static final Map<ForgeWorldType, WorldPreset.PresetEditor> GENERATOR_SCREEN_FACTORIES = Maps.newHashMap();
private static final Map<ForgeWorldPreset, WorldPreset> GENERATORS = Maps.newHashMap();
private static final Map<ForgeWorldPreset, WorldPreset.PresetEditor> GENERATOR_SCREEN_FACTORIES = Maps.newHashMap();
public static synchronized void registerFactory(ForgeWorldType type, WorldPreset.PresetEditor factory)
public static synchronized void registerPresetEditor(ForgeWorldPreset type, WorldPreset.PresetEditor factory)
{
if (GENERATOR_SCREEN_FACTORIES.containsKey(type))
throw new IllegalStateException("Factory has already been registered for: " + type);
@@ -52,9 +52,9 @@ public class ForgeWorldTypeScreens
GENERATOR_SCREEN_FACTORIES.put(type, factory);
}
static WorldPreset getDefaultGenerator()
static WorldPreset getDefaultPreset()
{
ForgeWorldType def = ForgeWorldType.getDefaultWorldType();
ForgeWorldPreset def = ForgeWorldPreset.getDefaultWorldPreset();
if (def == null)
{
return WorldPreset.NORMAL;
@@ -70,49 +70,47 @@ public class ForgeWorldTypeScreens
return gen;
}
static WorldPreset.PresetEditor getGeneratorScreenFactory(Optional<WorldPreset> generator, @Nullable WorldPreset.PresetEditor biomegeneratortypescreens$ifactory)
static WorldPreset.PresetEditor getPresetEditor(Optional<WorldPreset> generator, @Nullable WorldPreset.PresetEditor biomegeneratortypescreens$ifactory)
{
return generator.filter(gen -> gen instanceof GeneratorType)
.map(type -> GENERATOR_SCREEN_FACTORIES.get(((GeneratorType)type).getWorldType()))
return generator.filter(gen -> gen instanceof GeneratorPreset)
.map(type -> GENERATOR_SCREEN_FACTORIES.get(((GeneratorPreset)type).getWorldPreset()))
.orElse(biomegeneratortypescreens$ifactory);
}
static void registerTypes()
static void registerPresets()
{
ForgeRegistries.WORLD_TYPES.forEach(wt -> {
GeneratorType gen = new GeneratorType(wt);
GeneratorPreset gen = new GeneratorPreset(wt);
GENERATORS.put(wt, gen);
WorldPreset.registerGenerator(gen);
});
}
private static class GeneratorType extends WorldPreset
private static class GeneratorPreset extends WorldPreset
{
private final ForgeWorldType worldType;
private final ForgeWorldPreset worldPreset;
public GeneratorType(ForgeWorldType wt)
public GeneratorPreset(ForgeWorldPreset wt)
{
super(wt.getDisplayName());
worldType = wt;
worldPreset = wt;
}
public ForgeWorldType getWorldType()
public ForgeWorldPreset getWorldPreset()
{
return worldType;
return worldPreset;
}
@Nonnull
@Override
public WorldGenSettings create(@Nonnull RegistryAccess.RegistryHolder dynamicRegistries, long seed, boolean generateStructures, boolean bonusChest)
{
return worldType.createSettings(dynamicRegistries, seed, generateStructures, bonusChest, "");
return worldPreset.createSettings(dynamicRegistries, seed, generateStructures, bonusChest, "");
}
@Nonnull
@Override
protected ChunkGenerator generator(@Nonnull Registry<Biome> p_241869_1_, @Nonnull Registry<NoiseGeneratorSettings> p_241869_2_, long p_241869_3_)
{
return worldType.createChunkGenerator(p_241869_1_, p_241869_2_, p_241869_3_, "");
protected ChunkGenerator generator(RegistryAccess p_194083_, long p_194084_) {
return worldPreset.createChunkGenerator(p_194083_, p_194084_, "");
}
}
}
@@ -54,9 +54,19 @@ import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader;
public class MinecraftForgeClient
{
public static RenderType getRenderLayer()
public static RenderType getRenderType()
{
return ForgeHooksClient.renderLayer.get();
return ForgeHooksClient.renderType.get();
}
private static float partialTick;
public static float getPartialTick() {
return partialTick;
}
public static void setPartialTick(float partialTick) {
MinecraftForgeClient.partialTick = partialTick;
}
/**
@@ -105,47 +115,6 @@ public class MinecraftForgeClient
}
}
private static final LoadingCache<Pair<Level, BlockPos>, Optional<RenderChunkRegion>> regionCache = CacheBuilder.newBuilder()
.maximumSize(500)
.concurrencyLevel(5)
.expireAfterAccess(1, TimeUnit.SECONDS)
.build(new CacheLoader<Pair<Level, BlockPos>, Optional<RenderChunkRegion>>()
{
@Override
public Optional<RenderChunkRegion> load(Pair<Level, BlockPos> key)
{
return Optional.ofNullable(RenderChunkRegion.createIfNotEmpty(key.getLeft(), key.getRight().offset(-1, -1, -1), key.getRight().offset(16, 16, 16), 1));
}
});
public static void onRebuildChunk(Level world, BlockPos position, RenderChunkRegion cache)
{
if (cache == null)
regionCache.invalidate(Pair.of(world, position));
else
regionCache.put(Pair.of(world, position), Optional.of(cache));
}
@Nullable
public static RenderChunkRegion getRegionRenderCache(Level world, BlockPos pos)
{
return getRegionRenderCacheOptional(world, pos).orElse(null);
}
public static Optional<RenderChunkRegion> getRegionRenderCacheOptional(Level world, BlockPos pos)
{
int x = pos.getX() & ~0xF;
int y = pos.getY() & ~0xF;
int z = pos.getZ() & ~0xF;
return regionCache.getUnchecked(Pair.of(world, new BlockPos(x, y, z)));
}
public static void clearRenderCache()
{
regionCache.invalidateAll();
regionCache.cleanUp();
}
private static HashMap<ResourceLocation, Supplier<NativeImage>> bufferedImageSuppliers = new HashMap<ResourceLocation, Supplier<NativeImage>>();
public static void registerImageLayerSupplier(ResourceLocation resourceLocation, Supplier<NativeImage> supplier)
{
@@ -26,17 +26,17 @@ import net.minecraftforge.eventbus.api.Event;
/**
* Fired before the client player is notified of a change in game mode from the server.
*/
public class ClientPlayerChangeGameModeEvent extends Event
public class ClientPlayerChangeGameTypeEvent extends Event
{
private final PlayerInfo info;
private final GameType currentGameMode;
private final GameType newGameMode;
private final GameType currentGameType;
private final GameType newGameType;
public ClientPlayerChangeGameModeEvent(PlayerInfo info, GameType currentGameMode, GameType newGameMode)
public ClientPlayerChangeGameTypeEvent(PlayerInfo info, GameType currentGameType, GameType newGameType)
{
this.info = info;
this.currentGameMode = currentGameMode;
this.newGameMode = newGameMode;
this.currentGameType = currentGameType;
this.newGameType = newGameType;
}
public PlayerInfo getInfo()
@@ -44,13 +44,13 @@ public class ClientPlayerChangeGameModeEvent extends Event
return info;
}
public GameType getCurrentGameMode()
public GameType getCurrentGameType()
{
return currentGameMode;
return currentGameType;
}
public GameType getNewGameMode()
public GameType getNewGameType()
{
return newGameMode;
return newGameType;
}
}
@@ -30,16 +30,16 @@ import javax.annotation.Nullable;
* Client side player connectivity events.
*/
public class ClientPlayerNetworkEvent extends Event {
private final MultiPlayerGameMode controller;
private final MultiPlayerGameMode multiPlayerGameMode;
private final LocalPlayer player;
private final Connection networkManager;
private final Connection connection;
/**
* @return the player controller for the client side
*/
@Nullable
public MultiPlayerGameMode getController() {
return controller;
public MultiPlayerGameMode getMultiPlayerGameMode() {
return multiPlayerGameMode;
}
/**
@@ -51,17 +51,17 @@ public class ClientPlayerNetworkEvent extends Event {
}
/**
* @return the network connection (if present - may be null)
* @return the impl connection (if present - may be null)
*/
@Nullable
public Connection getNetworkManager() {
return networkManager;
public Connection getConnection() {
return connection;
}
ClientPlayerNetworkEvent(final MultiPlayerGameMode controller, final LocalPlayer player, final Connection networkManager) {
this.controller = controller;
ClientPlayerNetworkEvent(final MultiPlayerGameMode multiPlayerGameMode, final LocalPlayer player, final Connection connection) {
this.multiPlayerGameMode = multiPlayerGameMode;
this.player = player;
this.networkManager = networkManager;
this.connection = connection;
}
/**
@@ -26,19 +26,19 @@ import net.minecraftforge.eventbus.api.Event;
/**
* Event class for handling GuiContainer specific events.
*/
public class GuiContainerEvent extends Event
public class ContainerScreenEvent extends Event
{
private final AbstractContainerScreen guiContainer;
private final AbstractContainerScreen<?> containerScreen;
public GuiContainerEvent(AbstractContainerScreen guiContainer)
public ContainerScreenEvent(AbstractContainerScreen<?> containerScreen)
{
this.guiContainer = guiContainer;
this.containerScreen = containerScreen;
}
public AbstractContainerScreen getGuiContainer()
public AbstractContainerScreen<?> getContainerScreen()
{
return guiContainer;
return containerScreen;
}
/**
@@ -47,9 +47,9 @@ public class GuiContainerEvent extends Event
* This is useful for any slot / item specific overlays.
* Things that need to be on top of All GUI elements but bellow tooltips and dragged stacks.
*/
public static class DrawForeground extends GuiContainerEvent
public static class DrawForeground extends ContainerScreenEvent
{
private final PoseStack mStack;
private final PoseStack poseStack;
private final int mouseX;
private final int mouseY;
@@ -61,17 +61,17 @@ public class GuiContainerEvent extends Event
* @param mouseX The current X position of the players mouse.
* @param mouseY The current Y position of the players mouse.
*/
public DrawForeground(AbstractContainerScreen guiContainer, PoseStack mStack, int mouseX, int mouseY)
public DrawForeground(AbstractContainerScreen<?> guiContainer, PoseStack mStack, int mouseX, int mouseY)
{
super(guiContainer);
this.mStack = mStack;
this.poseStack = mStack;
this.mouseX = mouseX;
this.mouseY = mouseY;
}
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return mStack;
return poseStack;
}
public int getMouseX()
@@ -89,9 +89,9 @@ public class GuiContainerEvent extends Event
* This event is fired directly after the GuiContainer has draw any background elements,
* This is useful for drawing new background elements.
*/
public static class DrawBackground extends GuiContainerEvent
public static class DrawBackground extends ContainerScreenEvent
{
private final PoseStack mStack;
private final PoseStack poseStack;
private final int mouseX;
private final int mouseY;
@@ -103,17 +103,17 @@ public class GuiContainerEvent extends Event
* @param mouseX The current X position of the players mouse.
* @param mouseY The current Y position of the players mouse.
*/
public DrawBackground(AbstractContainerScreen guiContainer, PoseStack mStack, int mouseX, int mouseY)
public DrawBackground(AbstractContainerScreen<?> guiContainer, PoseStack mStack, int mouseX, int mouseY)
{
super(guiContainer);
this.mStack = mStack;
this.poseStack = mStack;
this.mouseX = mouseX;
this.mouseY = mouseY;
}
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return mStack;
return poseStack;
}
public int getMouseX()
@@ -36,29 +36,29 @@ import net.minecraft.client.renderer.LevelRenderer;
@Cancelable
public class DrawSelectionEvent extends Event
{
private final LevelRenderer context;
private final Camera info;
private final LevelRenderer levelRenderer;
private final Camera camera;
private final HitResult target;
private final float partialTicks;
private final PoseStack matrix;
private final MultiBufferSource buffers;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
public DrawSelectionEvent(LevelRenderer context, Camera info, HitResult target, float partialTicks, PoseStack matrix, MultiBufferSource buffers)
public DrawSelectionEvent(LevelRenderer levelRenderer, Camera camera, HitResult target, float partialTicks, PoseStack poseStack, MultiBufferSource multiBufferSource)
{
this.context = context;
this.info = info;
this.levelRenderer = levelRenderer;
this.camera = camera;
this.target = target;
this.partialTicks= partialTicks;
this.matrix = matrix;
this.buffers = buffers;
this.partialTicks = partialTicks;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
}
public LevelRenderer getContext() { return context; }
public Camera getInfo() { return info; }
public LevelRenderer getLevelRenderer() { return levelRenderer; }
public Camera getCamera() { return camera; }
public HitResult getTarget() { return target; }
public float getPartialTicks() { return partialTicks; }
public PoseStack getMatrix() { return matrix; }
public MultiBufferSource getBuffers() { return buffers; }
public PoseStack getPoseStack() { return poseStack; }
public MultiBufferSource getMultiBufferSource() { return multiBufferSource; }
/**
* A variant of the DrawSelectionEvent only called when a block is highlighted.
@@ -25,8 +25,6 @@ import net.minecraft.client.renderer.FogRenderer.FogMode;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event.HasResult;
/**
* Event that hooks into GameRenderer, allowing any feature to customize visual attributes
* the player sees.
@@ -34,14 +32,14 @@ import net.minecraftforge.eventbus.api.Event.HasResult;
public abstract class EntityViewRenderEvent extends net.minecraftforge.eventbus.api.Event
{
private final GameRenderer renderer;
private final Camera info;
private final double renderPartialTicks;
private final Camera camera;
private final double partialTicks;
public EntityViewRenderEvent(GameRenderer renderer, Camera info, double renderPartialTicks)
public EntityViewRenderEvent(GameRenderer renderer, Camera camera, double partialTicks)
{
this.renderer = renderer;
this.info = info;
this.renderPartialTicks = renderPartialTicks;
this.camera = camera;
this.partialTicks = partialTicks;
}
public GameRenderer getRenderer()
@@ -49,27 +47,27 @@ public abstract class EntityViewRenderEvent extends net.minecraftforge.eventbus.
return renderer;
}
public Camera getInfo()
public Camera getCamera()
{
return info;
return camera;
}
public double getRenderPartialTicks()
public double getPartialTicks()
{
return renderPartialTicks;
return partialTicks;
}
private static class FogEvent extends EntityViewRenderEvent
{
private final FogMode type;
private final FogMode mode;
@SuppressWarnings("resource")
protected FogEvent(FogMode type, Camera info, double renderPartialTicks)
protected FogEvent(FogMode mode, Camera info, double renderPartialTicks)
{
super(Minecraft.getInstance().gameRenderer, info, renderPartialTicks);
this.type = type;
this.mode = mode;
}
public FogMode getType() { return type; }
public FogMode getMode() { return mode; }
}
/**
@@ -174,11 +172,11 @@ public abstract class EntityViewRenderEvent extends net.minecraftforge.eventbus.
* Event that allows mods to alter the raw FOV itself.
* This directly affects to the FOV without being modified.
* */
public static class FOVModifier extends EntityViewRenderEvent
public static class FieldOfView extends EntityViewRenderEvent
{
private double fov;
public FOVModifier(GameRenderer renderer, Camera info, double renderPartialTicks, double fov) {
public FieldOfView(GameRenderer renderer, Camera info, double renderPartialTicks, double fov) {
super(renderer, info, renderPartialTicks);
this.setFOV(fov);
}
@@ -24,13 +24,13 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.util.Mth;
import net.minecraftforge.eventbus.api.Event;
public class FOVUpdateEvent extends Event
public class FOVModifierEvent extends Event
{
private final Player entity;
private final float fov;
private float newfov;
public FOVUpdateEvent(Player entity, float fov)
public FOVModifierEvent(Player entity, float fov)
{
this.entity = entity;
this.fov = fov;
@@ -36,13 +36,13 @@ public class InputEvent extends Event
{
private final int button;
private final int action;
private final int mods;
private final int modifiers;
public RawMouseEvent(int button, int action, int mods)
public RawMouseEvent(int button, int action, int modifiers)
{
this.button = button;
this.action = action;
this.mods = mods;
this.modifiers = modifiers;
}
/**
@@ -76,9 +76,9 @@ public class InputEvent extends Event
* @see GLFW#GLFW_MOD_ALT
* @see GLFW#GLFW_MOD_SUPER
*/
public int getMods()
public int getModifiers()
{
return this.mods;
return this.modifiers;
}
}
@@ -89,12 +89,12 @@ public class InputEvent extends Event
{
private final int button;
private final int action;
private final int mods;
public MouseInputEvent(int button, int action, int mods)
private final int modifiers;
public MouseInputEvent(int button, int action, int modifiers)
{
this.button = button;
this.action = action;
this.mods = mods;
this.modifiers = modifiers;
}
/**
@@ -128,9 +128,9 @@ public class InputEvent extends Event
* @see GLFW#GLFW_MOD_ALT
* @see GLFW#GLFW_MOD_SUPER
*/
public int getMods()
public int getModifiers()
{
return this.mods;
return this.modifiers;
}
}
@@ -266,13 +266,13 @@ public class InputEvent extends Event
public static class ClickInputEvent extends InputEvent
{
private final int button;
private final KeyMapping keyBinding;
private final KeyMapping keyMapping;
private final InteractionHand hand;
private boolean handSwing = true;
public ClickInputEvent(int button, KeyMapping keyBinding, InteractionHand hand)
public ClickInputEvent(int button, KeyMapping keyMapping, InteractionHand hand)
{
this.button = button;
this.keyBinding = keyBinding;
this.keyMapping = keyMapping;
this.hand = hand;
}
@@ -316,9 +316,9 @@ public class InputEvent extends Event
return button == 2;
}
public KeyMapping getKeyBinding()
public KeyMapping getKeyMapping()
{
return keyBinding;
return keyMapping;
}
}
}
@@ -24,7 +24,7 @@ import java.util.Map;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ForgeModelBakery;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
@@ -37,9 +37,9 @@ public class ModelBakeEvent extends Event implements IModBusEvent
{
private final ModelManager modelManager;
private final Map<ResourceLocation, BakedModel> modelRegistry;
private final ModelLoader modelLoader;
private final ForgeModelBakery modelLoader;
public ModelBakeEvent(ModelManager modelManager, Map<ResourceLocation, BakedModel> modelRegistry, ModelLoader modelLoader)
public ModelBakeEvent(ModelManager modelManager, Map<ResourceLocation, BakedModel> modelRegistry, ForgeModelBakery modelLoader)
{
this.modelManager = modelManager;
this.modelRegistry = modelRegistry;
@@ -56,7 +56,7 @@ public class ModelBakeEvent extends Event implements IModBusEvent
return modelRegistry;
}
public ModelLoader getModelLoader()
public ForgeModelBakery getModelLoader()
{
return modelLoader;
}
@@ -19,11 +19,12 @@
package net.minecraftforge.client.event;
import net.minecraftforge.client.model.ForgeModelBakery;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
/**
* Fired when the {@link net.minecraftforge.client.model.ModelLoader} is ready to register model loaders
* Fired when the {@link ForgeModelBakery} is ready to register model loaders
*/
public class ModelRegistryEvent extends Event implements IModBusEvent
{
@@ -27,19 +27,19 @@ import net.minecraftforge.event.entity.player.PlayerEvent;
* This event is fired after player movement inputs are updated.<br>
* Handlers can freely manipulate {@link Input} to cancel movement.<br>
*/
public class InputUpdateEvent extends PlayerEvent
public class MovementInputUpdateEvent extends PlayerEvent
{
private final Input movementInput;
private final Input input;
public InputUpdateEvent(Player player, Input movementInput)
public MovementInputUpdateEvent(Player player, Input input)
{
super(player);
this.movementInput = movementInput;
this.input = input;
}
public Input getMovementInput()
public Input getInput()
{
return movementInput;
return input;
}
}
@@ -39,17 +39,17 @@ public class RenderBlockOverlayEvent extends Event
}
private final Player player;
private final PoseStack mat;
private final PoseStack poseStack;
private final OverlayType overlayType;
private final BlockState blockForOverlay;
private final BlockState blockState;
private final BlockPos blockPos;
public RenderBlockOverlayEvent(Player player, PoseStack mat, OverlayType type, BlockState block, BlockPos blockPos)
public RenderBlockOverlayEvent(Player player, PoseStack poseStack, OverlayType type, BlockState block, BlockPos blockPos)
{
this.player = player;
this.mat = mat;
this.poseStack = poseStack;
this.overlayType = type;
this.blockForOverlay = block;
this.blockState = block;
this.blockPos = blockPos;
}
@@ -58,7 +58,7 @@ public class RenderBlockOverlayEvent extends Event
* The player which the overlay will apply to
*/
public Player getPlayer() { return player; }
public PoseStack getMatrixStack() { return mat; }
public PoseStack getPoseStack() { return poseStack; }
/**
* The type of overlay to occur
*/
@@ -66,6 +66,6 @@ public class RenderBlockOverlayEvent extends Event
/**
* If the overlay type is BLOCK, then this is the block which the overlay is getting it's icon from
*/
public BlockState getBlockForOverlay() { return blockForOverlay; }
public BlockState getBlockState() { return blockState; }
public BlockPos getBlockPos() { return blockPos; }
}
@@ -134,14 +134,14 @@ public class RenderGameOverlayEvent extends Event
public static class BossInfo extends Pre
{
private final LerpingBossEvent bossInfo;
private final LerpingBossEvent bossEvent;
private final int x;
private final int y;
private int increment;
public BossInfo(PoseStack mStack, RenderGameOverlayEvent parent, ElementType type, LerpingBossEvent bossInfo, int x, int y, int increment)
public BossInfo(PoseStack mStack, RenderGameOverlayEvent parent, ElementType type, LerpingBossEvent bossEvent, int x, int y, int increment)
{
super(mStack, parent, type);
this.bossInfo = bossInfo;
this.bossEvent = bossEvent;
this.x = x;
this.y = y;
this.increment = increment;
@@ -150,9 +150,9 @@ public class RenderGameOverlayEvent extends Event
/**
* @return The {@link LerpingBossEvent} currently being rendered
*/
public LerpingBossEvent getBossInfo()
public LerpingBossEvent getBossEvent()
{
return bossInfo;
return bossEvent;
}
/**
@@ -38,9 +38,9 @@ import net.minecraftforge.eventbus.api.Event;
public class RenderHandEvent extends Event
{
private final InteractionHand hand;
private final PoseStack mat;
private final MultiBufferSource buffers;
private final int light;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
private final float partialTicks;
private final float interpolatedPitch;
private final float swingProgress;
@@ -48,14 +48,14 @@ public class RenderHandEvent extends Event
@Nonnull
private final ItemStack stack;
public RenderHandEvent(InteractionHand hand, PoseStack mat, MultiBufferSource buffers, int light,
public RenderHandEvent(InteractionHand hand, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight,
float partialTicks, float interpolatedPitch,
float swingProgress, float equipProgress, @Nonnull ItemStack stack)
{
this.hand = hand;
this.mat = mat;
this.buffers = buffers;
this.light = light;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
this.partialTicks = partialTicks;
this.interpolatedPitch = interpolatedPitch;
this.swingProgress = swingProgress;
@@ -68,17 +68,17 @@ public class RenderHandEvent extends Event
return hand;
}
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return mat;
return poseStack;
}
public MultiBufferSource getBuffers() {
return buffers;
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
public int getLight() {
return light;
public int getPackedLight() {
return packedLight;
}
public float getPartialTicks()
@@ -37,33 +37,33 @@ import javax.annotation.Nonnull;
@Cancelable
public class RenderItemInFrameEvent extends Event
{
private final ItemStack item;
private final ItemFrame entityItemFrame;
private final ItemStack itemStack;
private final ItemFrame itemFrameEntity;
private final ItemFrameRenderer renderer;
private final PoseStack matrix;
private final MultiBufferSource buffers;
private final int light;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer renderItemFrame, PoseStack matrix,
MultiBufferSource buffers, int light)
public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer renderItemFrame, PoseStack poseStack,
MultiBufferSource multiBufferSource, int packedLight)
{
item = itemFrame.getItem();
entityItemFrame = itemFrame;
itemStack = itemFrame.getItem();
itemFrameEntity = itemFrame;
renderer = renderItemFrame;
this.matrix = matrix;
this.buffers = buffers;
this.light = light;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
}
@Nonnull
public ItemStack getItem()
public ItemStack getItemStack()
{
return item;
return itemStack;
}
public ItemFrame getEntityItemFrame()
public ItemFrame getItemFrameEntity()
{
return entityItemFrame;
return itemFrameEntity;
}
public ItemFrameRenderer getRenderer()
@@ -71,15 +71,15 @@ public class RenderItemInFrameEvent extends Event
return renderer;
}
public PoseStack getMatrix() {
return matrix;
public PoseStack getPoseStack() {
return poseStack;
}
public MultiBufferSource getBuffers() {
return buffers;
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
public int getLight() {
return light;
public int getPackedLight() {
return packedLight;
}
}
@@ -24,36 +24,36 @@ import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.LevelRenderer;
import com.mojang.math.Matrix4f;
public class RenderWorldLastEvent extends net.minecraftforge.eventbus.api.Event
public class RenderLevelLastEvent extends net.minecraftforge.eventbus.api.Event
{
private final LevelRenderer context;
private final PoseStack mat;
private final float partialTicks;
private final LevelRenderer levelRenderer;
private final PoseStack poseStack;
private final float partialTick;
private final Matrix4f projectionMatrix;
private final long finishTimeNano;
private final long startNanos;
public RenderWorldLastEvent(LevelRenderer context, PoseStack mat, float partialTicks, Matrix4f projectionMatrix, long finishTimeNano)
public RenderLevelLastEvent(LevelRenderer levelRenderer, PoseStack poseStack, float partialTick, Matrix4f projectionMatrix, long startNanos)
{
this.context = context;
this.mat = mat;
this.partialTicks = partialTicks;
this.levelRenderer = levelRenderer;
this.poseStack = poseStack;
this.partialTick = partialTick;
this.projectionMatrix = projectionMatrix;
this.finishTimeNano = finishTimeNano;
this.startNanos = startNanos;
}
public LevelRenderer getContext()
public LevelRenderer getLevelRenderer()
{
return context;
return levelRenderer;
}
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return mat;
return poseStack;
}
public float getPartialTicks()
public float getPartialTick()
{
return partialTicks;
return partialTick;
}
public Matrix4f getProjectionMatrix()
@@ -61,8 +61,8 @@ public class RenderWorldLastEvent extends net.minecraftforge.eventbus.api.Event
return projectionMatrix;
}
public long getFinishTimeNano()
public long getStartNanos()
{
return finishTimeNano;
return startNanos;
}
}
@@ -32,28 +32,28 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
private final LivingEntity entity;
private final LivingEntityRenderer<T, M> renderer;
private final float partialRenderTick;
private final PoseStack matrixStack;
private final MultiBufferSource buffers;
private final int light;
private final float partialTick;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
public RenderLivingEvent(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialRenderTick, PoseStack matrixStack,
MultiBufferSource buffers, int light)
public RenderLivingEvent(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack,
MultiBufferSource multiBufferSource, int packedLight)
{
this.entity = entity;
this.renderer = renderer;
this.partialRenderTick = partialRenderTick;
this.matrixStack = matrixStack;
this.buffers = buffers;
this.light = light;
this.partialTick = partialTick;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
}
public LivingEntity getEntity() { return entity; }
public LivingEntityRenderer<T, M> getRenderer() { return renderer; }
public float getPartialRenderTick() { return partialRenderTick; }
public PoseStack getMatrixStack() { return matrixStack; }
public MultiBufferSource getBuffers() { return buffers; }
public int getLight() { return light; }
public float getPartialTick() { return partialTick; }
public PoseStack getPoseStack() { return poseStack; }
public MultiBufferSource getMultiBufferSource() { return multiBufferSource; }
public int getPackedLight() { return packedLight; }
@Cancelable
public static class Pre<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M>
@@ -36,12 +36,12 @@ import net.minecraftforge.eventbus.api.Event;
* changed by mods.<br>
* {@link #entityRenderer} contains the entity renderer instance that renders the name plate/tag. This cannot be
* changed by mods.<br>
* {@link #matrixStack} contains the matrix stack instance involved in rendering the name plate/tag. This cannot
* {@link #poseStack} contains the matrix stack instance involved in rendering the name plate/tag. This cannot
* be changed by mods.<br>
* {@link #renderTypeBuffer} contains the render type buffer instance involved in rendering the name plate/tag.
* {@link #multiBufferSource} contains the render type buffer instance involved in rendering the name plate/tag.
* This cannot be changed by mods.<br>
* {@link #packedLight} contains the sky and block light values used in rendering the name plate/tag.<br>
* {@link #partialTicks} contains the partial ticks used in rendering the name plate/tag. This cannot be changed by mods.<br>
* {@link #partialTick} contains the partial ticks used in rendering the name plate/tag. This cannot be changed by mods.<br>
* <br>
* This event has a result. {@link HasResult}. <br>
* ALLOW will force-render name plate/tag, DEFAULT will ignore the hook and continue using the vanilla check
@@ -56,21 +56,21 @@ public class RenderNameplateEvent extends EntityEvent
private Component nameplateContent;
private final Component originalContent;
private final EntityRenderer<?> entityRenderer;
private final PoseStack matrixStack;
private final MultiBufferSource renderTypeBuffer;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
private final float partialTicks;
private final float partialTick;
public RenderNameplateEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack matrixStack, MultiBufferSource renderTypeBuffer, int packedLight, float partialTicks)
public RenderNameplateEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick)
{
super(entity);
this.originalContent = content;
this.setContent(this.originalContent);
this.entityRenderer = entityRenderer;
this.matrixStack = matrixStack;
this.renderTypeBuffer = renderTypeBuffer;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
this.partialTicks = partialTicks;
this.partialTick = partialTick;
}
/**
@@ -108,17 +108,17 @@ public class RenderNameplateEvent extends EntityEvent
/**
* The matrix stack used during the rendering of the name plate/tag
*/
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return this.matrixStack;
return this.poseStack;
}
/**
* The render type buffer used during the rendering of the name plate/tag
*/
public MultiBufferSource getRenderTypeBuffer()
public MultiBufferSource getMultiBufferSource()
{
return this.renderTypeBuffer;
return this.multiBufferSource;
}
/**
@@ -132,8 +132,8 @@ public class RenderNameplateEvent extends EntityEvent
/**
* The partial ticks used during the rendering of the name plate/tag
*/
public float getPartialTicks()
public float getPartialTick()
{
return this.partialTicks;
return this.partialTick;
}
}
@@ -29,26 +29,26 @@ import net.minecraftforge.event.entity.player.PlayerEvent;
public abstract class RenderPlayerEvent extends PlayerEvent
{
private final PlayerRenderer renderer;
private final float partialRenderTick;
private final PoseStack stack;
private final MultiBufferSource buffers;
private final int light;
private final float partialTick;
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
public RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialRenderTick, PoseStack stack, MultiBufferSource buffers, int light)
public RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight)
{
super(player);
this.renderer = renderer;
this.partialRenderTick = partialRenderTick;
this.stack = stack;
this.buffers = buffers;
this.light = light;
this.partialTick = partialTick;
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
}
public PlayerRenderer getRenderer() { return renderer; }
public float getPartialRenderTick() { return partialRenderTick; }
public PoseStack getMatrixStack() { return stack; }
public MultiBufferSource getBuffers() { return buffers; }
public int getLight() { return light; }
public float getPartialTick() { return partialTick; }
public PoseStack getPoseStack() { return poseStack; }
public MultiBufferSource getMultiBufferSource() { return multiBufferSource; }
public int getPackedLight() { return packedLight; }
@Cancelable
public static class Pre extends RenderPlayerEvent
@@ -42,65 +42,36 @@ import net.minecraftforge.eventbus.api.Event;
* Do not use this event directly, use one of the subclasses:
* <ul>
* <li>{@link RenderTooltipEvent.Pre}</li>
* <li>{@link RenderTooltipEvent.PostBackground}</li>
* <li>{@link RenderTooltipEvent.PostText}</li>
* <li>{@link RenderTooltipEvent.GatherComponents}</li>
* <li>{@link RenderTooltipEvent.Color}</li>
* </ul>
*/
public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api.Event
{
@Nonnull
protected final ItemStack stack;
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
protected final List<? extends FormattedText> lines;
protected final PoseStack matrixStack; // TODO: rename in 1.18
protected final ItemStack itemStack;
protected int x;
protected int y;
protected Font fr;
protected Font font;
protected final List<ClientTooltipComponent> components;
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public RenderTooltipEvent(@Nonnull ItemStack stack, @Nonnull List<? extends FormattedText> lines, PoseStack matrixStack, int x, int y, @Nonnull Font fr)
{
this.stack = stack;
this.lines = Collections.unmodifiableList(lines);
this.matrixStack = matrixStack;
this.x = x;
this.y = y;
this.fr = fr;
this.components = List.of();
}
public RenderTooltipEvent(@Nonnull ItemStack stack, PoseStack poseStack, int x, int y, @Nonnull Font font, @Nonnull List<ClientTooltipComponent> components)
public RenderTooltipEvent(@Nonnull ItemStack itemStack, PoseStack poseStack, int x, int y, @Nonnull Font font, @Nonnull List<ClientTooltipComponent> components)
{
this.stack = stack;
this.lines = List.of();
this.itemStack = itemStack;
this.components = Collections.unmodifiableList(components);
this.matrixStack = poseStack;
this.x = x;
this.y = y;
this.fr = font;
this.font = font;
}
/**
* @return The stack which the tooltip is being rendered for. As tooltips can be drawn without itemstacks, this stack may be empty.
*/
@Nonnull
public ItemStack getStack()
public ItemStack getItemStack()
{
return stack;
}
/**
* The lines to be drawn. May change between {@link RenderTooltipEvent.Pre} and {@link RenderTooltipEvent.Post}.
*
* @return An <i>unmodifiable</i> list of strings. Use {@link net.minecraftforge.event.entity.player.ItemTooltipEvent} to modify tooltip text.
* @deprecated use {@link #getComponents()}
*/
@Nonnull
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public List<? extends FormattedText> getLines()
{
return lines;
return itemStack;
}
/**
@@ -114,14 +85,6 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
return components;
}
/**
* @return The MatrixStack of the current rendering context
*/
public PoseStack getMatrixStack()
{
return matrixStack;
}
/**
* @return The X position of the tooltip box. By default, the mouse X position.
*/
@@ -142,9 +105,9 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
* @return The {@link Font} instance the current render is using.
*/
@Nonnull
public Font getFontRenderer()
public Font getFont()
{
return fr;
return font;
}
/**
@@ -156,15 +119,15 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
@Cancelable
public static class GatherComponents extends Event
{
private final ItemStack stack;
private final ItemStack itemStack;
private final int screenWidth;
private final int screenHeight;
private final List<Either<FormattedText, TooltipComponent>> tooltipElements;
private int maxWidth;
public GatherComponents(ItemStack stack, int screenWidth, int screenHeight, List<Either<FormattedText, TooltipComponent>> tooltipElements, int maxWidth)
public GatherComponents(ItemStack itemStack, int screenWidth, int screenHeight, List<Either<FormattedText, TooltipComponent>> tooltipElements, int maxWidth)
{
this.stack = stack;
this.itemStack = itemStack;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.tooltipElements = tooltipElements;
@@ -174,9 +137,9 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
/**
* @return the ItemStack whose tooltip is being rendered or an empty stack if this tooltip is not for a stack
*/
public ItemStack getStack()
public ItemStack getItemStack()
{
return stack;
return itemStack;
}
/**
@@ -231,23 +194,12 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
{
private int screenWidth;
private int screenHeight;
private int maxWidth;
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public Pre(@Nonnull ItemStack stack, @Nonnull List<? extends FormattedText> lines, PoseStack matrixStack, int x, int y, int screenWidth, int screenHeight, int maxWidth, @Nonnull Font fr)
{
super(stack, lines, matrixStack, x, y, fr);
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.maxWidth = maxWidth;
}
public Pre(@Nonnull ItemStack stack, PoseStack matrixStack, int x, int y, int screenWidth, int screenHeight, @Nonnull Font font, @Nonnull List<ClientTooltipComponent> components)
{
super(stack, matrixStack, x, y, font, components);
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.maxWidth = -1;
}
public int getScreenWidth()
@@ -255,49 +207,17 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
return screenWidth;
}
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public void setScreenWidth(int screenWidth)
{
this.screenWidth = screenWidth;
}
public int getScreenHeight()
{
return screenHeight;
}
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public void setScreenHeight(int screenHeight)
{
this.screenHeight = screenHeight;
}
/**
* @return The max width the tooltip can be. Defaults to -1 (unlimited).
* @deprecated use {@link GatherComponents}
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public int getMaxWidth()
{
return maxWidth;
}
/**
* Sets the max width of the tooltip. Use -1 for unlimited.
* @deprecated use {@link GatherComponents}
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public void setMaxWidth(int maxWidth)
{
this.maxWidth = maxWidth;
}
/**
* Sets the {@link Font} to be used to render text.
*/
public void setFontRenderer(@Nonnull Font fr)
public void setFont(@Nonnull Font fr)
{
this.fr = fr;
this.font = fr;
}
/**
@@ -317,65 +237,6 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
}
}
/**
* Events inheriting from this class are fired at different stages during the tooltip rendering.
* <p>
* Do not use this event directly, use one of its subclasses:
* <ul>
* <li>{@link RenderTooltipEvent.PostBackground}</li>
* <li>{@link RenderTooltipEvent.PostText}</li>
* </ul>
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
protected static abstract class Post extends RenderTooltipEvent
{
private final int width;
private final int height;
public Post(@Nonnull ItemStack stack, @Nonnull List<? extends FormattedText> textLines, PoseStack matrixStack,int x, int y, @Nonnull Font fr, int width, int height)
{
super(stack, textLines, matrixStack, x, y, fr);
this.width = width;
this.height = height;
}
/**
* @return The width of the tooltip box. This is the width of the <i>inner</i> box, not including the border.
*/
public int getWidth()
{
return width;
}
/**
* @return The height of the tooltip box. This is the height of the <i>inner</i> box, not including the border.
*/
public int getHeight()
{
return height;
}
}
/**
* This event is fired directly after the tooltip background is drawn, but before any text is drawn.
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static class PostBackground extends Post
{
public PostBackground(@Nonnull ItemStack stack, @Nonnull List<? extends FormattedText> textLines, PoseStack matrixStack, int x, int y, @Nonnull Font fr, int width, int height)
{ super(stack, textLines, matrixStack, x, y, fr, width, height); }
}
/**
* This event is fired directly after the tooltip text is drawn, but before the GL state is reset.
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static class PostText extends Post
{
public PostText(@Nonnull ItemStack stack, @Nonnull List<? extends FormattedText> textLines, PoseStack matrixStack, int x, int y, @Nonnull Font fr, int width, int height)
{ super(stack, textLines, matrixStack, x, y, fr, width, height); }
}
/**
* This event is fired when the colours for the tooltip background are determined.
*/
@@ -389,19 +250,6 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
private int borderStart;
private int borderEnd;
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public Color(@Nonnull ItemStack stack, @Nonnull List<? extends FormattedText> textLines, PoseStack matrixStack, int x, int y, @Nonnull Font fr, int background, int borderStart, int borderEnd)
{
super(stack, textLines, matrixStack, x, y, fr);
this.originalBackground = background;
this.originalBorderStart = borderStart;
this.originalBorderEnd = borderEnd;
this.backgroundStart = background;
this.backgroundEnd = background;
this.borderStart = borderStart;
this.borderEnd = borderEnd;
}
public Color(@Nonnull ItemStack stack, PoseStack matrixStack, int x, int y, @Nonnull Font fr, int background, int borderStart, int borderEnd, @Nonnull List<ClientTooltipComponent> components)
{
super(stack, matrixStack, x, y, fr, components);
@@ -414,15 +262,6 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
this.borderEnd = borderEnd;
}
/**
* @deprecated use {@link #getBackgroundStart()} and {@link #getBackgroundEnd}
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public int getBackground()
{
return backgroundStart;
}
public int getBackgroundStart()
{
return backgroundStart;
@@ -469,12 +308,6 @@ public abstract class RenderTooltipEvent extends net.minecraftforge.eventbus.api
this.borderEnd = borderEnd;
}
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public int getOriginalBackground()
{
return originalBackground;
}
public int getOriginalBackgroundStart()
{
return originalBackground;
@@ -41,52 +41,52 @@ import org.lwjgl.glfw.GLFW;
* @author bspkrs
*/
@OnlyIn(Dist.CLIENT)
public class GuiScreenEvent extends Event
public class ScreenEvent extends Event
{
private final Screen gui;
private final Screen screen;
public GuiScreenEvent(Screen gui)
public ScreenEvent(Screen screen)
{
this.gui = gui;
this.screen = screen;
}
/**
* The GuiScreen object generating this event.
*/
public Screen getGui()
public Screen getScreen()
{
return gui;
return screen;
}
public static class InitGuiEvent extends GuiScreenEvent
public static class InitScreenEvent extends ScreenEvent
{
private Consumer<GuiEventListener> add;
private Consumer<GuiEventListener> remove;
private List<GuiEventListener> list;
private List<GuiEventListener> listenerList;
public InitGuiEvent(Screen gui, List<GuiEventListener> list, Consumer<GuiEventListener> add, Consumer<GuiEventListener> remove)
public InitScreenEvent(Screen screen, List<GuiEventListener> listenerList, Consumer<GuiEventListener> add, Consumer<GuiEventListener> remove)
{
super(gui);
this.list = Collections.unmodifiableList(list);
super(screen);
this.listenerList = Collections.unmodifiableList(listenerList);
this.add = add;
this.remove = remove;
}
/**
* Unmodifiable reference to the list of buttons on the {@link #gui}.
* Unmodifiable reference to the list of buttons on the {@link #screen}.
*/
public List<GuiEventListener> getWidgetList()
public List<GuiEventListener> getListenersList()
{
return list;
return listenerList;
}
public void addWidget(GuiEventListener button)
public void addListener(GuiEventListener button)
{
add.accept(button);
}
public void removeWidget(GuiEventListener button)
public void removeListener(GuiEventListener button)
{
remove.accept(button);
}
@@ -101,11 +101,11 @@ public class GuiScreenEvent extends Event
* {@code this.initGui();}<br/>
*/
@Cancelable
public static class Pre extends InitGuiEvent
public static class Pre extends InitScreenEvent
{
public Pre(Screen gui, List<GuiEventListener> list, Consumer<GuiEventListener> add, Consumer<GuiEventListener> remove)
public Pre(Screen screen, List<GuiEventListener> list, Consumer<GuiEventListener> add, Consumer<GuiEventListener> remove)
{
super(gui, list, add, remove);
super(screen, list, add, remove);
}
}
@@ -113,37 +113,37 @@ public class GuiScreenEvent extends Event
* This event fires right after {@code Screen#init()}.
* This is a good place to alter a GuiScreen's component layout if desired.
*/
public static class Post extends InitGuiEvent
public static class Post extends InitScreenEvent
{
public Post(Screen gui, List<GuiEventListener> list, Consumer<GuiEventListener> add, Consumer<GuiEventListener> remove)
public Post(Screen screen, List<GuiEventListener> list, Consumer<GuiEventListener> add, Consumer<GuiEventListener> remove)
{
super(gui, list, add, remove);
super(screen, list, add, remove);
}
}
}
public static class DrawScreenEvent extends GuiScreenEvent
public static class DrawScreenEvent extends ScreenEvent
{
private final PoseStack mStack;
private final PoseStack poseStack;
private final int mouseX;
private final int mouseY;
private final float renderPartialTicks;
private final float partialTicks;
public DrawScreenEvent(Screen gui, PoseStack mStack, int mouseX, int mouseY, float renderPartialTicks)
public DrawScreenEvent(Screen screen, PoseStack poseStack, int mouseX, int mouseY, float partialTicks)
{
super(gui);
this.mStack = mStack;
super(screen);
this.poseStack = poseStack;
this.mouseX = mouseX;
this.mouseY = mouseY;
this.renderPartialTicks = renderPartialTicks;
this.partialTicks = partialTicks;
}
/**
* The MatrixStack to render with.
*/
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return mStack;
return poseStack;
}
/**
@@ -165,9 +165,9 @@ public class GuiScreenEvent extends Event
/**
* Partial render ticks elapsed.
*/
public float getRenderPartialTicks()
public float getPartialTicks()
{
return renderPartialTicks;
return partialTicks;
}
/**
@@ -177,9 +177,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends DrawScreenEvent
{
public Pre(Screen gui, PoseStack mStack, int mouseX, int mouseY, float renderPartialTicks)
public Pre(Screen screen, PoseStack mStack, int mouseX, int mouseY, float renderPartialTicks)
{
super(gui, mStack, mouseX, mouseY, renderPartialTicks);
super(screen, mStack, mouseX, mouseY, renderPartialTicks);
}
}
@@ -188,9 +188,9 @@ public class GuiScreenEvent extends Event
*/
public static class Post extends DrawScreenEvent
{
public Post(Screen gui, PoseStack mStack, int mouseX, int mouseY, float renderPartialTicks)
public Post(Screen screen, PoseStack mStack, int mouseX, int mouseY, float renderPartialTicks)
{
super(gui, mStack, mouseX, mouseY, renderPartialTicks);
super(screen, mStack, mouseX, mouseY, renderPartialTicks);
}
}
}
@@ -199,22 +199,22 @@ public class GuiScreenEvent extends Event
* This event fires at the end of {@link Screen#renderBackground(PoseStack, int)} and before the rest of the Gui draws.
* This allows drawing next to Guis, above the background but below any tooltips.
*/
public static class BackgroundDrawnEvent extends GuiScreenEvent
public static class BackgroundDrawnEvent extends ScreenEvent
{
private final PoseStack mStack;
private final PoseStack poseStack;
public BackgroundDrawnEvent(Screen gui, PoseStack mStack)
public BackgroundDrawnEvent(Screen screen, PoseStack poseStack)
{
super(gui);
this.mStack = mStack;
super(screen);
this.poseStack = poseStack;
}
/**
* The MatrixStack to render with.
*/
public PoseStack getMatrixStack()
public PoseStack getPoseStack()
{
return mStack;
return poseStack;
}
}
@@ -224,22 +224,22 @@ public class GuiScreenEvent extends Event
* Cancel this event to prevent the Gui from being moved.
*/
@Cancelable
public static class PotionShiftEvent extends GuiScreenEvent
public static class PotionShiftEvent extends ScreenEvent
{
public PotionShiftEvent(Screen gui)
public PotionShiftEvent(Screen screen)
{
super(gui);
super(screen);
}
}
public static abstract class MouseInputEvent extends GuiScreenEvent
public static abstract class MouseInputEvent extends ScreenEvent
{
private final double mouseX;
private final double mouseY;
public MouseInputEvent(Screen gui, double mouseX, double mouseY)
public MouseInputEvent(Screen screen, double mouseX, double mouseY)
{
super(gui);
super(screen);
this.mouseX = mouseX;
this.mouseY = mouseY;
}
@@ -259,9 +259,9 @@ public class GuiScreenEvent extends Event
{
private final int button;
public MouseClickedEvent(Screen gui, double mouseX, double mouseY, int button)
public MouseClickedEvent(Screen screen, double mouseX, double mouseY, int button)
{
super(gui, mouseX, mouseY);
super(screen, mouseX, mouseY);
this.button = button;
}
@@ -277,9 +277,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends MouseClickedEvent
{
public Pre(Screen gui, double mouseX, double mouseY, int button)
public Pre(Screen screen, double mouseX, double mouseY, int button)
{
super(gui, mouseX, mouseY, button);
super(screen, mouseX, mouseY, button);
}
}
@@ -297,28 +297,17 @@ public class GuiScreenEvent extends Event
* <p>Note that this event is currently pre-cancelled if {@link Screen#mouseClicked} returns {@code true}
* to retain old behavior. This will be changed in 1.18 when the event is made non-cancellable.</p>
*/
@Cancelable // TODO: Make non-cancellable in 1.18.
@HasResult
public static class Post extends MouseClickedEvent
{
private final boolean handled;
public Post(Screen gui, double mouseX, double mouseY, int button, boolean handled)
public Post(Screen screen, double mouseX, double mouseY, int button, boolean handled)
{
super(gui, mouseX, mouseY, button);
super(screen, mouseX, mouseY, button);
this.handled = handled;
}
/**
* @deprecated event now has a result instead and will no longer be cancellable in 1.18; use {@link #setResult(Result)}
*/
@Override
@Deprecated
public void setCanceled(boolean cancel)
{
this.setResult(cancel ? Result.ALLOW : Result.DEFAULT);
}
/**
* @return {@code true} if the mouse click was already handled by its screen
*/
@@ -333,9 +322,9 @@ public class GuiScreenEvent extends Event
{
private final int button;
public MouseReleasedEvent(Screen gui, double mouseX, double mouseY, int button)
public MouseReleasedEvent(Screen screen, double mouseX, double mouseY, int button)
{
super(gui, mouseX, mouseY);
super(screen, mouseX, mouseY);
this.button = button;
}
@@ -351,9 +340,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends MouseReleasedEvent
{
public Pre(Screen gui, double mouseX, double mouseY, int button)
public Pre(Screen screen, double mouseX, double mouseY, int button)
{
super(gui, mouseX, mouseY, button);
super(screen, mouseX, mouseY, button);
}
}
@@ -368,31 +357,18 @@ public class GuiScreenEvent extends Event
* </ul>
* </p>
*
* <p>Note that this event is currently pre-cancelled if {@link Screen#mouseReleased} returns {@code true}
* to retain old behavior. This will be changed in 1.18 when the event is made non-cancellable.</p>
*/
@Cancelable // TODO: Make non-cancellable in 1.18.
@HasResult
public static class Post extends MouseReleasedEvent
{
private final boolean handled;
public Post(Screen gui, double mouseX, double mouseY, int button, boolean handled)
public Post(Screen screen, double mouseX, double mouseY, int button, boolean handled)
{
super(gui, mouseX, mouseY, button);
super(screen, mouseX, mouseY, button);
this.handled = handled;
}
/**
* @deprecated event now has a result instead and will no longer be cancellable in 1.18; use {@link #setResult(Result)}
*/
@Override
@Deprecated
public void setCanceled(boolean cancel)
{
this.setResult(cancel ? Result.ALLOW : Result.DEFAULT);
}
/**
* @return {@code true} if the mouse release was already handled by its screen
*/
@@ -409,9 +385,9 @@ public class GuiScreenEvent extends Event
private final double dragX;
private final double dragY;
public MouseDragEvent(Screen gui, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
public MouseDragEvent(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
{
super(gui, mouseX, mouseY);
super(screen, mouseX, mouseY);
this.mouseButton = mouseButton;
this.dragX = dragX;
this.dragY = dragY;
@@ -439,9 +415,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends MouseDragEvent
{
public Pre(Screen gui, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
public Pre(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
{
super(gui, mouseX, mouseY, mouseButton, dragX, dragY);
super(screen, mouseX, mouseY, mouseButton, dragX, dragY);
}
}
@@ -452,9 +428,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Post extends MouseDragEvent
{
public Post(Screen gui, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
public Post(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY)
{
super(gui, mouseX, mouseY, mouseButton, dragX, dragY);
super(screen, mouseX, mouseY, mouseButton, dragX, dragY);
}
}
}
@@ -463,9 +439,9 @@ public class GuiScreenEvent extends Event
{
private final double scrollDelta;
public MouseScrollEvent(Screen gui, double mouseX, double mouseY, double scrollDelta)
public MouseScrollEvent(Screen screen, double mouseX, double mouseY, double scrollDelta)
{
super(gui, mouseX, mouseY);
super(screen, mouseX, mouseY);
this.scrollDelta = scrollDelta;
}
@@ -481,9 +457,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends MouseScrollEvent
{
public Pre(Screen gui, double mouseX, double mouseY, double scrollDelta)
public Pre(Screen screen, double mouseX, double mouseY, double scrollDelta)
{
super(gui, mouseX, mouseY, scrollDelta);
super(screen, mouseX, mouseY, scrollDelta);
}
}
@@ -494,22 +470,22 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Post extends MouseScrollEvent
{
public Post(Screen gui, double mouseX, double mouseY, double scrollDelta)
public Post(Screen screen, double mouseX, double mouseY, double scrollDelta)
{
super(gui, mouseX, mouseY, scrollDelta);
super(screen, mouseX, mouseY, scrollDelta);
}
}
}
public static abstract class KeyboardKeyEvent extends GuiScreenEvent
public static abstract class KeyboardKeyEvent extends ScreenEvent
{
private final int keyCode;
private final int scanCode;
private final int modifiers;
public KeyboardKeyEvent(Screen gui, int keyCode, int scanCode, int modifiers)
public KeyboardKeyEvent(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui);
super(screen);
this.keyCode = keyCode;
this.scanCode = scanCode;
this.modifiers = modifiers;
@@ -556,9 +532,9 @@ public class GuiScreenEvent extends Event
public static abstract class KeyboardKeyPressedEvent extends KeyboardKeyEvent
{
public KeyboardKeyPressedEvent(Screen gui, int keyCode, int scanCode, int modifiers)
public KeyboardKeyPressedEvent(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui, keyCode, scanCode, modifiers);
super(screen, keyCode, scanCode, modifiers);
}
/**
@@ -568,9 +544,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends KeyboardKeyPressedEvent
{
public Pre(Screen gui, int keyCode, int scanCode, int modifiers)
public Pre(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui, keyCode, scanCode, modifiers);
super(screen, keyCode, scanCode, modifiers);
}
}
@@ -581,18 +557,18 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Post extends KeyboardKeyPressedEvent
{
public Post(Screen gui, int keyCode, int scanCode, int modifiers)
public Post(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui, keyCode, scanCode, modifiers);
super(screen, keyCode, scanCode, modifiers);
}
}
}
public static abstract class KeyboardKeyReleasedEvent extends KeyboardKeyEvent
{
public KeyboardKeyReleasedEvent(Screen gui, int keyCode, int scanCode, int modifiers)
public KeyboardKeyReleasedEvent(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui, keyCode, scanCode, modifiers);
super(screen, keyCode, scanCode, modifiers);
}
/**
@@ -602,9 +578,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends KeyboardKeyReleasedEvent
{
public Pre(Screen gui, int keyCode, int scanCode, int modifiers)
public Pre(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui, keyCode, scanCode, modifiers);
super(screen, keyCode, scanCode, modifiers);
}
}
@@ -615,21 +591,21 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Post extends KeyboardKeyReleasedEvent
{
public Post(Screen gui, int keyCode, int scanCode, int modifiers)
public Post(Screen screen, int keyCode, int scanCode, int modifiers)
{
super(gui, keyCode, scanCode, modifiers);
super(screen, keyCode, scanCode, modifiers);
}
}
}
public static class KeyboardCharTypedEvent extends GuiScreenEvent
public static class KeyboardCharTypedEvent extends ScreenEvent
{
private final char codePoint;
private final int modifiers;
public KeyboardCharTypedEvent(Screen gui, char codePoint, int modifiers)
public KeyboardCharTypedEvent(Screen screen, char codePoint, int modifiers)
{
super(gui);
super(screen);
this.codePoint = codePoint;
this.modifiers = modifiers;
}
@@ -662,9 +638,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Pre extends KeyboardCharTypedEvent
{
public Pre(Screen gui, char codePoint, int modifiers)
public Pre(Screen screen, char codePoint, int modifiers)
{
super(gui, codePoint, modifiers);
super(screen, codePoint, modifiers);
}
}
@@ -675,9 +651,9 @@ public class GuiScreenEvent extends Event
@Cancelable
public static class Post extends KeyboardCharTypedEvent
{
public Post(Screen gui, char codePoint, int modifiers)
public Post(Screen screen, char codePoint, int modifiers)
{
super(gui, codePoint, modifiers);
super(screen, codePoint, modifiers);
}
}
}
@@ -24,27 +24,27 @@ import net.minecraftforge.eventbus.api.Event;
import net.minecraft.client.gui.screens.Screen;
/**
* This event is called before any Gui will open.
* This event is called before any Screen will open.
* If you don't want this to happen, cancel the event.
* If you want to override this Gui, simply set the gui variable to your own Gui.
* If you want to override this Screen, simply set the screen variable to your own Screen.
*
*/
@Cancelable
public class GuiOpenEvent extends Event
public class ScreenOpenEvent extends Event
{
private Screen gui;
public GuiOpenEvent(Screen gui)
private Screen screen;
public ScreenOpenEvent(Screen screen)
{
this.setGui(gui);
this.setScreen(screen);
}
public Screen getGui()
public Screen getScreen()
{
return gui;
return screen;
}
public void setGui(Screen gui)
public void setScreen(Screen screen)
{
this.gui = gui;
this.screen = screen;
}
}
@@ -29,16 +29,16 @@ import java.util.Set;
public class TextureStitchEvent extends Event implements IModBusEvent
{
private final TextureAtlas map;
private final TextureAtlas atlas;
public TextureStitchEvent(TextureAtlas map)
public TextureStitchEvent(TextureAtlas atlas)
{
this.map = map;
this.atlas = atlas;
}
public TextureAtlas getMap()
public TextureAtlas getAtlas()
{
return map;
return atlas;
}
/**
@@ -31,15 +31,15 @@ import net.minecraft.client.sounds.SoundEngine;
public class PlaySoundEvent extends SoundEvent
{
private final String name;
private final SoundInstance sound;
private SoundInstance result;
private final SoundInstance originalSound;
private SoundInstance sound;
public PlaySoundEvent(SoundEngine manager, SoundInstance sound)
{
super(manager);
this.sound = sound;
this.originalSound = sound;
this.name = sound.getLocation().getPath();
this.setResultSound(sound);
this.setSound(sound);
}
public String getName()
@@ -47,18 +47,18 @@ public class PlaySoundEvent extends SoundEvent
return name;
}
public SoundInstance getOriginalSound()
{
return originalSound;
}
public SoundInstance getSound()
{
return sound;
}
public SoundInstance getResultSound()
public void setSound(SoundInstance result)
{
return result;
}
public void setResultSound(SoundInstance result)
{
this.result = result;
this.sound = result;
}
}
@@ -25,29 +25,29 @@ import com.mojang.blaze3d.audio.Channel;
public class SoundEvent extends net.minecraftforge.eventbus.api.Event
{
private final SoundEngine manager;
public SoundEvent(SoundEngine manager)
private final SoundEngine engine;
public SoundEvent(SoundEngine engine)
{
this.manager = manager;
this.engine = engine;
}
public SoundEngine getManager()
public SoundEngine getEngine()
{
return manager;
return engine;
}
public static class SoundSourceEvent extends SoundEvent
{
private final SoundInstance sound;
private final Channel source;
private final Channel channel;
private final String name;
public SoundSourceEvent(SoundEngine manager, SoundInstance sound, Channel source)
public SoundSourceEvent(SoundEngine manager, SoundInstance sound, Channel channel)
{
super(manager);
this.name = sound.getLocation().getPath();
this.sound = sound;
this.source = source;
this.channel = channel;
}
public SoundInstance getSound()
@@ -55,9 +55,9 @@ public class SoundEvent extends net.minecraftforge.eventbus.api.Event
return sound;
}
public Channel getSource()
public Channel getChannel()
{
return source;
return channel;
}
public String getName()
@@ -55,7 +55,7 @@ public interface IForgeBakedModel
return self().getQuads(state, side, rand);
}
default boolean isAmbientOcclusion(BlockState state) { return self().useAmbientOcclusion(); }
default boolean useAmbientOcclusion(BlockState state) { return self().useAmbientOcclusion(); }
/**
* Override to tell the new model loader that it shouldn't wrap this model
@@ -42,14 +42,14 @@ public interface IForgeKeyMapping
default void setToDefault()
{
setKeyModifierAndCode(getKeyModifierDefault(), self().getDefaultKey());
setKeyModifierAndCode(getDefaultKeyModifier(), self().getDefaultKey());
}
void setKeyConflictContext(IKeyConflictContext keyConflictContext);
IKeyConflictContext getKeyConflictContext();
KeyModifier getKeyModifierDefault();
KeyModifier getDefaultKeyModifier();
KeyModifier getKeyModifier();
@@ -63,7 +63,7 @@ public interface IForgeKeyMapping
/**
* Returns true when one of the bindings' key codes conflicts with the other's modifier.
*/
default boolean hasKeyCodeModifierConflict(KeyMapping other)
default boolean hasKeyModifierConflict(KeyMapping other)
{
if (getKeyConflictContext().conflicts(other.getKeyConflictContext()) || other.getKeyConflictContext().conflicts(getKeyConflictContext()))
{
@@ -1,45 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.extensions;
import net.minecraft.client.renderer.chunk.RenderChunkRegion;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
public interface IForgeRenderChunk
{
/**
* Creates a new RegionRenderCache instance.<br>
* Extending classes can change the behavior of the cache, allowing to visually change
* blocks (schematics etc).
*
* @see RenderChunkRegion
* @param world The world to cache.
* @param from The starting position of the chunk minus one on each axis.
* @param to The ending position of the chunk plus one on each axis.
* @param subtract Padding used internally by the RegionRenderCache constructor to make
* the cache a 20x20x20 cube, for a total of 8000 states in the cache.
* @return new RegionRenderCache instance
*/
default RenderChunkRegion createRegionRenderCache(Level world, BlockPos from, BlockPos to, int subtract)
{
return RenderChunkRegion.createIfNotEmpty(world, from, to, subtract);
}
}
@@ -1,57 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.extensions;
import java.util.Collection;
import java.util.function.Function;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.resources.ResourceLocation;
public interface IForgeTextureAtlasSprite
{
/**
* @deprecated See {@link net.minecraftforge.client.textures.ITextureAtlasSpriteLoader}
*/
@Deprecated
default boolean hasCustomLoader(ResourceManager manager, ResourceLocation location)
{
return false;
}
/**
* @deprecated See {@link net.minecraftforge.client.textures.ITextureAtlasSpriteLoader}
*/
@Deprecated
default boolean load(ResourceManager manager, ResourceLocation location, Function<ResourceLocation, TextureAtlasSprite> textureGetter)
{
return true;
}
@Deprecated
default Collection<ResourceLocation> getDependencies()
{
return ImmutableList.of();
}
}
@@ -1,36 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.extensions;
import net.minecraftforge.common.model.animation.IClip;
import java.util.Optional;
public interface IForgeUnbakedModel
{
/**
* Retrieves information about an animation clip in the model.
* @param name The clip name
* @return
*/
default Optional<? extends IClip> getClip(String name) {
return Optional.empty();
}
}
@@ -80,10 +80,10 @@ public class ForgeIngameGui extends Gui
public int left_height = 39;
public int right_height = 39;
private Font fontrenderer = null;
private Font font = null;
private RenderGameOverlayEvent eventParent;
private GuiOverlayDebugForge debugOverlay;
private ForgeDebugScreenOverlay debugOverlay;
public void setupOverlayRenderState(boolean blend, boolean depthText)
{
@@ -164,7 +164,7 @@ public class ForgeIngameGui extends Gui
gui.setupOverlayRenderState(true, false);
if (gui.minecraft.gameMode.getPlayerMode() == GameType.SPECTATOR)
{
gui.spectatorGui.renderHotbar(mStack, partialTicks);
gui.spectatorGui.renderHotbar(mStack);
}
else
{
@@ -335,7 +335,7 @@ public class ForgeIngameGui extends Gui
public ForgeIngameGui(Minecraft mc)
{
super(mc);
debugOverlay = new GuiOverlayDebugForge(mc);
debugOverlay = new ForgeDebugScreenOverlay(mc);
}
@Override
@@ -350,7 +350,7 @@ public class ForgeIngameGui extends Gui
if (pre(ALL, pStack)) return;
fontrenderer = minecraft.font;
font = minecraft.font;
this.random.setSeed(tickCount * 312871L);
@@ -689,20 +689,20 @@ public class ForgeIngameGui extends Gui
for (String msg : listL)
{
if (msg == null) continue;
fill(mStack, 1, top - 1, 2 + fontrenderer.width(msg) + 1, top + fontrenderer.lineHeight - 1, -1873784752);
fontrenderer.draw(mStack, msg, 2, top, 14737632);
top += fontrenderer.lineHeight;
fill(mStack, 1, top - 1, 2 + font.width(msg) + 1, top + font.lineHeight - 1, -1873784752);
font.draw(mStack, msg, 2, top, 14737632);
top += font.lineHeight;
}
top = 2;
for (String msg : listR)
{
if (msg == null) continue;
int w = fontrenderer.width(msg);
int w = font.width(msg);
int left = width - 2 - w;
fill(mStack, left - 1, top - 1, left + w + 1, top + fontrenderer.lineHeight - 1, -1873784752);
fontrenderer.draw(mStack, msg, left, top, 14737632);
top += fontrenderer.lineHeight;
fill(mStack, left - 1, top - 1, left + w + 1, top + font.lineHeight - 1, -1873784752);
font.draw(mStack, msg, left, top, 14737632);
top += font.lineHeight;
}
}
@@ -734,8 +734,8 @@ public class ForgeIngameGui extends Gui
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
int color = (animateOverlayMessageColor ? Mth.hsvToRgb(hue / 50.0F, 0.7F, 0.6F) & WHITE : WHITE);
drawBackdrop(pStack, fontrenderer, -4, fontrenderer.width(overlayMessageString), 16777215 | (opacity << 24));
fontrenderer.draw(pStack, overlayMessageString.getVisualOrderText(), -fontrenderer.width(overlayMessageString) / 2, -4, color | (opacity << 24));
drawBackdrop(pStack, font, -4, font.width(overlayMessageString), 16777215 | (opacity << 24));
font.draw(pStack, overlayMessageString.getVisualOrderText(), -font.width(overlayMessageString) / 2, -4, color | (opacity << 24));
RenderSystem.disableBlend();
pStack.popPose();
}
@@ -892,10 +892,10 @@ public class ForgeIngameGui extends Gui
RenderSystem.setShaderTexture(0, res);
}
private class GuiOverlayDebugForge extends DebugScreenOverlay
private class ForgeDebugScreenOverlay extends DebugScreenOverlay
{
private Minecraft mc;
private GuiOverlayDebugForge(Minecraft mc)
private ForgeDebugScreenOverlay(Minecraft mc)
{
super(mc);
this.mc = mc;
@@ -17,10 +17,9 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui;
package net.minecraftforge.client.gui;
import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.GameRenderer;
@@ -37,8 +36,6 @@ import net.minecraft.network.chat.Style;
import net.minecraftforge.client.event.RenderTooltipEvent;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.systems.RenderSystem;
@@ -229,215 +226,6 @@ public class GuiUtils
tessellator.end();
}
@Nonnull
private static ItemStack cachedTooltipStack = ItemStack.EMPTY;
/**
* Must be called from {@code GuiScreen.renderToolTip} before {@code GuiScreen.drawHoveringText} is called.
*
* @param stack The stack for which a tooltip is about to be drawn.
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static void preItemToolTip(@Nonnull ItemStack stack)
{
cachedTooltipStack = stack;
}
/**
* Must be called from {@code GuiScreen.renderToolTip} after {@code GuiScreen.drawHoveringText} is called.
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static void postItemToolTip()
{
cachedTooltipStack = ItemStack.EMPTY;
}
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static void drawHoveringText(PoseStack mStack, List<? extends FormattedText> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, Font font)
{
drawHoveringText(mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, DEFAULT_BACKGROUND_COLOR, DEFAULT_BORDER_COLOR_START, DEFAULT_BORDER_COLOR_END, font);
}
/**
* Draws a tooltip box on the screen with text in it.
* Automatically positions the box relative to the mouse to match Mojang's implementation.
* Automatically wraps text when there is not enough space on the screen to display the text without wrapping.
* Can have a maximum width set to avoid creating very wide tooltips.
*
* @param textLines the lines of text to be drawn in a hovering tooltip box.
* @param mouseX the mouse X position
* @param mouseY the mouse Y position
* @param screenWidth the available screen width for the tooltip to drawn in
* @param screenHeight the available screen height for the tooltip to drawn in
* @param maxTextWidth the maximum width of the text in the tooltip box.
* Set to a negative number to have no max width.
* @param backgroundColor The background color of the box
* @param borderColorStart The starting color of the box border
* @param borderColorEnd The ending color of the box border. The border color will be smoothly interpolated
* between the start and end values.
* @param font the font for drawing the text in the tooltip box
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static void drawHoveringText(PoseStack mStack, List<? extends FormattedText> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight,
int maxTextWidth, int backgroundColor, int borderColorStart, int borderColorEnd, Font font)
{
drawHoveringText(cachedTooltipStack, mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, backgroundColor, borderColorStart, borderColorEnd, font);
}
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static void drawHoveringText(@Nonnull final ItemStack stack, PoseStack mStack, List<? extends FormattedText> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, Font font)
{
drawHoveringText(stack, mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, DEFAULT_BACKGROUND_COLOR, DEFAULT_BORDER_COLOR_START, DEFAULT_BORDER_COLOR_END, font);
}
/**
* Use this version if calling from somewhere where ItemStack context is available.
*
* @see #drawHoveringText(PoseStack, List, int, int, int, int, int, int, int, int, Font)
*/
@Deprecated(since = "1.18", forRemoval = true) // TODO: remove in 1.18
public static void drawHoveringText(@Nonnull final ItemStack stack, PoseStack pStack, List<? extends FormattedText> textLines, int mouseX, int mouseY,
int screenWidth, int screenHeight, int maxTextWidth,
int backgroundColor, int borderColorStart, int borderColorEnd, Font font)
{
if (!textLines.isEmpty())
{
RenderTooltipEvent.Pre event = new RenderTooltipEvent.Pre(stack, textLines, pStack, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font);
if (MinecraftForge.EVENT_BUS.post(event))
return;
mouseX = event.getX();
mouseY = event.getY();
screenWidth = event.getScreenWidth();
screenHeight = event.getScreenHeight();
maxTextWidth = event.getMaxWidth();
font = event.getFontRenderer();
// RenderSystem.disableRescaleNormal();
RenderSystem.disableDepthTest();
int tooltipTextWidth = 0;
for (FormattedText textLine : textLines)
{
int textLineWidth = font.width(textLine);
if (textLineWidth > tooltipTextWidth)
tooltipTextWidth = textLineWidth;
}
boolean needsWrap = false;
int titleLinesCount = 1;
int tooltipX = mouseX + 12;
if (tooltipX + tooltipTextWidth + 4 > screenWidth)
{
tooltipX = mouseX - 16 - tooltipTextWidth;
if (tooltipX < 4) // if the tooltip doesn't fit on the screen
{
if (mouseX > screenWidth / 2)
tooltipTextWidth = mouseX - 12 - 8;
else
tooltipTextWidth = screenWidth - 16 - mouseX;
needsWrap = true;
}
}
if (maxTextWidth > 0 && tooltipTextWidth > maxTextWidth)
{
tooltipTextWidth = maxTextWidth;
needsWrap = true;
}
if (needsWrap)
{
int wrappedTooltipWidth = 0;
List<FormattedText> wrappedTextLines = new ArrayList<>();
for (int i = 0; i < textLines.size(); i++)
{
FormattedText textLine = textLines.get(i);
List<FormattedText> wrappedLine = font.getSplitter().splitLines(textLine, tooltipTextWidth, Style.EMPTY);
if (i == 0)
titleLinesCount = wrappedLine.size();
for (FormattedText line : wrappedLine)
{
int lineWidth = font.width(line);
if (lineWidth > wrappedTooltipWidth)
wrappedTooltipWidth = lineWidth;
wrappedTextLines.add(line);
}
}
tooltipTextWidth = wrappedTooltipWidth;
textLines = wrappedTextLines;
if (mouseX > screenWidth / 2)
tooltipX = mouseX - 16 - tooltipTextWidth;
else
tooltipX = mouseX + 12;
}
int tooltipY = mouseY - 12;
int tooltipHeight = 8;
if (textLines.size() > 1)
{
tooltipHeight += (textLines.size() - 1) * 10;
if (textLines.size() > titleLinesCount)
tooltipHeight += 2; // gap between title lines and next lines
}
if (tooltipY < 4)
tooltipY = 4;
else if (tooltipY + tooltipHeight + 4 > screenHeight)
tooltipY = screenHeight - tooltipHeight - 4;
final int zLevel = 400;
RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(stack, textLines, pStack, tooltipX, tooltipY, font, backgroundColor, borderColorStart, borderColorEnd);
MinecraftForge.EVENT_BUS.post(colorEvent);
backgroundColor = colorEvent.getBackground();
borderColorStart = colorEvent.getBorderStart();
borderColorEnd = colorEvent.getBorderEnd();
pStack.pushPose();
Matrix4f mat = pStack.last().pose();
//TODO, lots of unnessesary GL calls here, we can buffer all these together.
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 4, tooltipX + tooltipTextWidth + 3, tooltipY - 3, backgroundColor, backgroundColor);
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY + tooltipHeight + 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 4, backgroundColor, backgroundColor);
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
drawGradientRect(mat, zLevel, tooltipX - 4, tooltipY - 3, tooltipX - 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
drawGradientRect(mat, zLevel, tooltipX + tooltipTextWidth + 3, tooltipY - 3, tooltipX + tooltipTextWidth + 4, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3 + 1, tooltipX - 3 + 1, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
drawGradientRect(mat, zLevel, tooltipX + tooltipTextWidth + 2, tooltipY - 3 + 1, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY - 3 + 1, borderColorStart, borderColorStart);
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY + tooltipHeight + 2, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, borderColorEnd, borderColorEnd);
MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostBackground(stack, textLines, pStack, tooltipX, tooltipY, font, tooltipTextWidth, tooltipHeight));
MultiBufferSource.BufferSource renderType = MultiBufferSource.immediate(Tesselator.getInstance().getBuilder());
pStack.translate(0.0D, 0.0D, zLevel);
int tooltipTop = tooltipY;
for (int lineNumber = 0; lineNumber < textLines.size(); ++lineNumber)
{
FormattedText line = textLines.get(lineNumber);
if (line != null)
font.drawInBatch(Language.getInstance().getVisualOrder(line), (float)tooltipX, (float)tooltipY, -1, true, mat, renderType, false, 0, 15728880);
if (lineNumber + 1 == titleLinesCount)
tooltipY += 2;
tooltipY += 10;
}
renderType.endBatch();
pStack.popPose();
MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostText(stack, textLines, pStack, tooltipX, tooltipTop, font, tooltipTextWidth, tooltipHeight));
RenderSystem.enableDepthTest();
// RenderSystem.enableRescaleNormal();
}
}
public static void drawGradientRect(Matrix4f mat, int zLevel, int left, int top, int right, int bottom, int startColor, int endColor)
{
float startAlpha = (float)(startColor >> 24 & 255) / 255.0F;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui.screen;
package net.minecraftforge.client.gui;
import com.google.common.base.Strings;
import com.mojang.blaze3d.vertex.PoseStack;
@@ -31,12 +31,11 @@ import net.minecraft.Util;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.ChatFormatting;
import net.minecraftforge.fmllegacy.ForgeI18n;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.fml.LoadingFailedException;
import net.minecraftforge.fml.ModLoadingException;
import net.minecraftforge.fml.ModLoadingWarning;
import net.minecraftforge.fmlclient.ClientHooks;
import net.minecraftforge.fmlclient.gui.widget.ExtendedButton;
import net.minecraftforge.client.gui.widget.ExtendedButton;
import net.minecraftforge.fml.loading.FMLPaths;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui.screen;
package net.minecraftforge.client.gui;
import java.io.IOException;
import java.io.InputStream;
@@ -33,8 +33,7 @@ import java.util.stream.Collectors;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraftforge.fmlclient.gui.GuiUtils;
import net.minecraftforge.fmlclient.gui.widget.ModListWidget;
import net.minecraftforge.client.gui.widget.ModListWidget;
import net.minecraftforge.resource.PathResourcePack;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
@@ -56,18 +55,17 @@ import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.Util;
import net.minecraftforge.client.gui.ScrollPanel;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.util.Size2i;
import net.minecraftforge.fmllegacy.ForgeI18n;
import net.minecraftforge.fmllegacy.MavenVersionStringHelper;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.common.util.MavenVersionStringHelper;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fmlclient.ConfigGuiHandler;
import net.minecraftforge.client.ConfigGuiHandler;
import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.fmllegacy.packs.ResourcePackLoader;
import net.minecraftforge.resource.ResourcePackLoader;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraft.locale.Language;
@@ -256,10 +254,6 @@ public class ModListScreen extends Screen
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
protected void drawBackground() {
}
@Override
public NarrationPriority narrationPriority() {
return NarrationPriority.NONE;
@@ -31,7 +31,7 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fmlclient.ClientModLoader;
import net.minecraftforge.client.loading.ClientModLoader;
import net.minecraftforge.api.distmarker.Dist;
@OnlyIn(Dist.CLIENT)
@@ -37,7 +37,6 @@ import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.components.events.AbstractContainerEventHandler;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.components.Widget;
import net.minecraftforge.fmlclient.gui.GuiUtils;
/**
* Abstract scroll panel class.
@@ -171,9 +170,6 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
protected abstract int getContentHeight();
// TODO: 1.18 rename and add PoseStack parameter
protected void drawBackground() {}
/**
* Draws the background of the scroll panel. This runs AFTER Scissors are enabled.
*/
@@ -314,8 +310,6 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
@Override
public void render(PoseStack matrix, int mouseX, int mouseY, float partialTicks)
{
this.drawBackground();
Tesselator tess = Tesselator.getInstance();
BufferBuilder worldr = tess.getBuilder();
@@ -17,16 +17,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui.widget;
package net.minecraftforge.client.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraftforge.fmlclient.gui.GuiUtils;
import net.minecraft.client.gui.components.Button.OnPress;
import net.minecraftforge.client.gui.GuiUtils;
/**
* This class provides a button that fixes several bugs present in the vanilla GuiButton drawing code.
@@ -52,7 +50,7 @@ public class ExtendedButton extends Button
public void renderButton(PoseStack mStack, int mouseX, int mouseY, float partial)
{
Minecraft mc = Minecraft.getInstance();
int k = this.getYImage(this.isHovered());
int k = this.getYImage(this.isHovered);
GuiUtils.drawContinuousTexturedBox(mStack, WIDGETS_LOCATION, this.x, this.y, 0, 46 + k * 20, this.width, this.height, 200, 20, 2, 3, 2, 2, this.getBlitOffset());
this.renderBg(mStack, mc, mouseX, mouseY);
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui.widget;
package net.minecraftforge.client.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.gui.Font;
@@ -29,9 +29,9 @@ import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.locale.Language;
import net.minecraft.network.chat.TextComponent;
import net.minecraftforge.fmlclient.gui.screen.ModListScreen;
import net.minecraftforge.client.gui.ModListScreen;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.fmllegacy.MavenVersionStringHelper;
import net.minecraftforge.common.util.MavenVersionStringHelper;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.forgespi.language.IModInfo;
@@ -17,18 +17,16 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui.widget;
package net.minecraftforge.client.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraftforge.fmlclient.gui.GuiUtils;
import net.minecraftforge.client.gui.GuiUtils;
import javax.annotation.Nullable;
import net.minecraft.client.gui.components.Button.OnPress;
/**
* This class is blatantly stolen from iChunUtils with permission.
*
@@ -17,17 +17,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient.gui.widget;
package net.minecraftforge.client.gui.widget;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraftforge.fmlclient.gui.GuiUtils;
import net.minecraft.client.gui.components.Button.OnPress;
import net.minecraftforge.client.gui.GuiUtils;
/**
* This class provides a button that shows a string glyph at the beginning. The glyph can be scaled using the glyphScale parameter.
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient;
package net.minecraftforge.client.loading;
import static net.minecraftforge.fml.Logging.CORE;
import static net.minecraftforge.fml.Logging.LOADING;
@@ -26,7 +26,6 @@ import java.io.File;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import net.minecraft.server.packs.repository.RepositorySource;
@@ -38,11 +37,10 @@ import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.DataPackConfig;
import net.minecraftforge.event.AddPackFindersEvent;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.fml.*;
import net.minecraftforge.fmllegacy.BrandingControl;
import net.minecraftforge.fmllegacy.CrashReportExtender;
import net.minecraftforge.fmllegacy.LogicalSidedProvider;
import net.minecraftforge.internal.BrandingControl;
import net.minecraftforge.logging.CrashReportExtender;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.resource.PathResourcePack;
import org.apache.logging.log4j.LogManager;
@@ -62,10 +60,10 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.ForgeConfig;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fmlclient.gui.screen.LoadingErrorScreen;
import net.minecraftforge.fmllegacy.packs.DelegatingResourcePack;
import net.minecraftforge.fmllegacy.packs.ResourcePackLoader;
import net.minecraftforge.fmllegacy.server.LanguageHook;
import net.minecraftforge.client.gui.LoadingErrorScreen;
import net.minecraftforge.resource.DelegatingResourcePack;
import net.minecraftforge.resource.ResourcePackLoader;
import net.minecraftforge.server.LanguageHook;
import net.minecraftforge.forgespi.language.IModInfo;
@OnlyIn(Dist.CLIENT)
@@ -101,16 +99,16 @@ public class ClientModLoader
// force log4j to shutdown logging in a shutdown hook. This is because we disable default shutdown hook so the server properly logs it's shutdown
Runtime.getRuntime().addShutdownHook(new Thread(LogManager::shutdown));
loading = true;
net.minecraftforge.fmlclient.ClientModLoader.mc = minecraft;
ClientModLoader.mc = minecraft;
LogicalSidedProvider.setClient(()->minecraft);
LanguageHook.loadForgeAndMCLangs();
earlyLoaderGUI = new EarlyLoaderGUI(minecraft);
createRunnableWithCatch(()->ModLoader.get().gatherAndInitializeMods(ModWorkManager.syncExecutor(), ModWorkManager.parallelExecutor(), new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
if (error == null) {
ResourcePackLoader.loadResourcePacks(defaultResourcePacks, net.minecraftforge.fmlclient.ClientModLoader::buildPackFinder);
ResourcePackLoader.loadResourcePacks(defaultResourcePacks, ClientModLoader::buildPackFinder);
ModLoader.get().postEvent(new AddPackFindersEvent(PackType.CLIENT_RESOURCES, defaultResourcePacks::addPackFinder));
DataPackConfig.DEFAULT.addModPacks(ResourcePackLoader.getPackNames());
mcResourceManager.registerReloadListener(net.minecraftforge.fmlclient.ClientModLoader::onResourceReload);
mcResourceManager.registerReloadListener(ClientModLoader::onResourceReload);
mcResourceManager.registerReloadListener(BrandingControl.resourceManagerReloadListener());
ModelLoaderRegistry.init();
}
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmlclient;
package net.minecraftforge.client.loading;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmllegacy;
package net.minecraftforge.client.loading;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
@@ -58,9 +58,9 @@ public abstract class BakedModelWrapper<T extends BakedModel> implements BakedMo
}
@Override
public boolean isAmbientOcclusion(BlockState state)
public boolean useAmbientOcclusion(BlockState state)
{
return originalModel.isAmbientOcclusion(state);
return originalModel.useAmbientOcclusion(state);
}
@Override
@@ -263,7 +263,7 @@ public final class DynamicBucketModel implements IModelGeometry<DynamicBucketMod
if (!cache.containsKey(name))
{
DynamicBucketModel unbaked = this.parent.withFluid(fluid);
BakedModel bakedModel = unbaked.bake(owner, bakery, ModelLoader.defaultTextureGetter(), BlockModelRotation.X0_Y0, this, new ResourceLocation("forge:bucket_override"));
BakedModel bakedModel = unbaked.bake(owner, bakery, ForgeModelBakery.defaultTextureGetter(), BlockModelRotation.X0_Y0, this, new ResourceLocation("forge:bucket_override"));
cache.put(name, bakedModel);
return bakedModel;
}
@@ -47,7 +47,7 @@ import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.client.resources.model.UnbakedModel;
public final class ModelLoader extends ModelBakery
public final class ForgeModelBakery extends ModelBakery
{
private static final Logger LOGGER = LogManager.getLogger();
private final Map<ResourceLocation, Exception> loadingExceptions = Maps.newHashMap();
@@ -55,10 +55,10 @@ public final class ModelLoader extends ModelBakery
private boolean isLoading = false;
private static ModelLoader instance;
private static ForgeModelBakery instance;
@Nullable
public static ModelLoader instance()
public static ForgeModelBakery instance()
{
return instance;
}
@@ -68,7 +68,7 @@ public final class ModelLoader extends ModelBakery
return isLoading;
}
public ModelLoader(ResourceManager manager, BlockColors colours, ProfilerFiller profiler, int maxMipmapLevel)
public ForgeModelBakery(ResourceManager manager, BlockColors colours, ProfilerFiller profiler, int maxMipmapLevel)
{
super(manager, colours, false);
instance = this;
@@ -261,7 +261,7 @@ public final class ModelLoader extends ModelBakery
}
*/
private static final Function<ResourceLocation, UnbakedModel> DEFAULT_MODEL_GETTER = (rl) -> ModelLoader.instance().getModelOrMissing(rl);
private static final Function<ResourceLocation, UnbakedModel> DEFAULT_MODEL_GETTER = (rl) -> ForgeModelBakery.instance().getModelOrMissing(rl);
/**
* Get the default texture getter the models will be baked with.
@@ -45,7 +45,7 @@ import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
@EventBusSubscriber(modid = "forge", bus = Bus.FORGE, value = Dist.CLIENT)
public class ModelDataManager
{
private static WeakReference<Level> currentWorld = new WeakReference<>(null);
private static WeakReference<Level> currentLevel = new WeakReference<>(null);
private static final Map<ChunkPos, Set<BlockPos>> needModelDataRefresh = new ConcurrentHashMap<>();
@@ -55,9 +55,9 @@ public class ModelDataManager
{
Preconditions.checkNotNull(world, "World must not be null");
Preconditions.checkArgument(world == Minecraft.getInstance().level, "Cannot use model data for a world other than the current client world");
if (world != currentWorld.get())
if (world != currentLevel.get())
{
currentWorld = new WeakReference<>(world);
currentLevel = new WeakReference<>(world);
needModelDataRefresh.clear();
modelDataCache.clear();
}
@@ -149,7 +149,7 @@ public final class MultiLayerModel implements IModelGeometry<MultiLayerModel>
@Override
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @Nonnull Random rand, @Nonnull IModelData extraData)
{
RenderType layer = MinecraftForgeClient.getRenderLayer();
RenderType layer = MinecraftForgeClient.getRenderType();
if (layer == null)
{
ImmutableList.Builder<BakedQuad> builder = ImmutableList.builder();
@@ -175,7 +175,7 @@ public final class MultiLayerModel implements IModelGeometry<MultiLayerModel>
}
@Override
public boolean isAmbientOcclusion(BlockState state)
public boolean useAmbientOcclusion(BlockState state)
{
return ambientOcclusion;
}
@@ -131,7 +131,7 @@ public class PerspectiveMapWrapper implements IDynamicBakedModel
}
@Override public boolean useAmbientOcclusion() { return parent.useAmbientOcclusion(); }
@Override public boolean isAmbientOcclusion(BlockState state) { return parent.isAmbientOcclusion(state); }
@Override public boolean useAmbientOcclusion(BlockState state) { return parent.useAmbientOcclusion(state); }
@Override public boolean isGui3d() { return parent.isGui3d(); }
@Override public boolean usesBlockLight() { return parent.usesBlockLight(); }
@Override public boolean isCustomRenderer() { return parent.isCustomRenderer(); }
@@ -1,70 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.model.animation;
import net.minecraft.world.level.Level;
import java.lang.ref.WeakReference;
public enum Animation
{
INSTANCE;
private float clientPartialTickTime;
private static long epochTime;
private static WeakReference<Level> worldRef;
/**
* Get the global world time for the current tick, in seconds.
*/
public static float getWorldTime(Level world)
{
return getWorldTime(world, 0);
}
/**
* Get the global world time for the current tick + partial tick progress, in seconds.
*/
public static float getWorldTime(Level world, float tickProgress)
{
if (worldRef == null || worldRef.get() != world)
{
epochTime = world.getGameTime();
worldRef = new WeakReference<>(world);
}
return (world.getGameTime() - epochTime + tickProgress) / 20;
}
/**
* Get current partialTickTime.
*/
public static float getPartialTickTime()
{
return INSTANCE.clientPartialTickTime;
}
/**
* Internal hook, do not use.
*/
public static void setClientPartialTickTime(float clientPartialTickTime) {
Animation.INSTANCE.clientPartialTickTime = clientPartialTickTime;
}
}
@@ -1,87 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.model.animation;
import java.util.Random;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Sheets;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.client.model.ModelDataManager;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.common.animation.Event;
import net.minecraftforge.common.animation.IEventHandler;
import net.minecraftforge.common.model.animation.CapabilityAnimation;
import net.minecraftforge.common.model.animation.IAnimationStateMachine;
import net.minecraftforge.common.property.Properties;
import net.minecraftforge.common.util.LazyOptional;
/**
* Generic {@link BlockEntityRenderer} that works with the Forge model system and animations.
*/
public class AnimationBlockEntityRenderer<T extends BlockEntity> implements BlockEntityRenderer<T>, IEventHandler<T>
{
protected static BlockRenderDispatcher blockRenderer;
@Override
public void render(T te, float partialTick, PoseStack mat, MultiBufferSource renderer, int light, int otherlight)
{
LazyOptional<IAnimationStateMachine> cap = te.getCapability(CapabilityAnimation.ANIMATION_CAPABILITY);
if(!cap.isPresent())
{
return;
}
if(blockRenderer == null) blockRenderer = Minecraft.getInstance().getBlockRenderer();
BlockPos pos = te.getBlockPos();
BlockAndTintGetter world = MinecraftForgeClient.getRegionRenderCacheOptional(te.getLevel(), pos)
.map(BlockAndTintGetter.class::cast).orElseGet(() -> te.getLevel());
BlockState state = world.getBlockState(pos);
BakedModel model = blockRenderer.getBlockModelShaper().getBlockModel(state);
IModelData data = model.getModelData(world, pos, state, ModelDataManager.getModelData(te.getLevel(), pos));
if (data.hasProperty(Properties.AnimationProperty))
{
@SuppressWarnings("resource")
float time = Animation.getWorldTime(Minecraft.getInstance().level, partialTick);
cap
.map(asm -> asm.apply(time))
.ifPresent(pair -> {
handleEvents(te, time, pair.getRight());
// TODO: caching?
data.setData(Properties.AnimationProperty, pair.getLeft());
blockRenderer.getModelRenderer().tesselateBlock(world, model, state, pos, mat, renderer.getBuffer(Sheets.solidBlockSheet()), false, new Random(), 42, light, data);
});
}
}
@Override
public void handleEvents(T te, float time, Iterable<Event> pastEvents) {}
}
@@ -1,97 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.model.animation;
import java.util.List;
import java.util.function.Function;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.CompositeModelState;
import net.minecraftforge.common.model.animation.CapabilityAnimation;
import net.minecraft.client.renderer.block.model.ItemOverride;
import net.minecraft.client.renderer.block.model.ItemOverrides;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.Material;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.UnbakedModel;
public final class AnimationItemOverrideList extends ItemOverrides
{
private final ModelBakery bakery;
private final UnbakedModel model;
private final ResourceLocation modelLoc;
private final ModelState state;
private final Function<Material, TextureAtlasSprite> bakedTextureGetter;
//TODO, Mojang now bakes overrides, figure out how to reverse them.
/*
public AnimationItemOverrideList(ModelBakery bakery, UnbakedModel model, ResourceLocation modelLoc, ModelState state, Function<Material, TextureAtlasSprite> bakedTextureGetter, ItemOverrides overrides)
{
this(bakery, model, modelLoc, state, bakedTextureGetter, overrides.getOverrides().reverse());
}
*/
public AnimationItemOverrideList(ModelBakery bakery, UnbakedModel model, ResourceLocation modelLoc, ModelState state, Function<Material, TextureAtlasSprite> bakedTextureGetter, List<ItemOverride> overrides)
{
super(bakery, model, ModelLoader.defaultModelGetter(), bakedTextureGetter, overrides);
this.bakery = bakery;
this.model = model;
this.modelLoc = modelLoc;
this.state = state;
this.bakedTextureGetter = bakedTextureGetter;
}
@SuppressWarnings("resource")
@Override
public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel world, @Nullable LivingEntity entity, int seed)
{
return stack.getCapability(CapabilityAnimation.ANIMATION_CAPABILITY, null)
.map(asm ->
{
Level w = world;
// TODO caching?
if(w == null && entity != null)
{
w = entity.level;
}
if(world == null)
{
w = Minecraft.getInstance().level;
}
return asm.apply(Animation.getWorldTime(world, Animation.getPartialTickTime())).getLeft();
})
// TODO where should uvlock data come from?
.map(state -> model.bake(bakery, bakedTextureGetter, new CompositeModelState(state, this.state), modelLoc))
.orElseGet(() -> super.resolve(originalModel, stack, world, entity, seed));
}
}
@@ -1,593 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.model.animation;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.TreeMap;
import javax.annotation.Nullable;
import net.minecraft.client.resources.model.ModelState;
import com.mojang.math.Matrix4f;
import com.mojang.math.Quaternion;
import com.mojang.math.Transformation;
import com.mojang.math.Vector3f;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraftforge.client.model.animation.ModelBlockAnimation.Parameter.Interpolation;
import net.minecraftforge.client.model.animation.ModelBlockAnimation.Parameter.Type;
import net.minecraftforge.client.model.animation.ModelBlockAnimation.Parameter.Variable;
import net.minecraftforge.common.animation.Event;
import net.minecraftforge.common.model.animation.IClip;
import net.minecraftforge.common.model.animation.IJoint;
import net.minecraftforge.common.model.animation.IJointClip;
import net.minecraftforge.common.model.animation.JointClips;
import net.minecraftforge.common.util.JsonUtils;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.UnmodifiableIterator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
public class ModelBlockAnimation
{
private static final Logger LOGGER = LogManager.getLogger();
private final ImmutableMap<String, ImmutableMap<String, float[]>> joints;
private final ImmutableMap<String, MBClip> clips;
private transient ImmutableMultimap<Integer, MBJointWeight> jointIndexMap;
public ModelBlockAnimation(ImmutableMap<String, ImmutableMap<String, float[]>> joints, ImmutableMap<String, MBClip> clips)
{
this.joints = joints;
this.clips = clips;
}
public ImmutableMap<String, ? extends IClip> getClips()
{
return clips;
}
public ImmutableCollection<MBJointWeight> getJoint(int i)
{
if(jointIndexMap == null)
{
ImmutableMultimap.Builder<Integer, MBJointWeight> builder = ImmutableMultimap.builder();
for(Map.Entry<String, ImmutableMap<String, float[]>> info : joints.entrySet())
{
ImmutableMap.Builder<Integer, float[]> weightBuilder = ImmutableMap.builder();
for(Map.Entry<String, float[]> e : info.getValue().entrySet())
{
weightBuilder.put(Integer.parseInt(e.getKey()), e.getValue());
}
ImmutableMap<Integer, float[]> weightMap = weightBuilder.build();
for(Map.Entry<Integer, float[]> e : weightMap.entrySet())
{
builder.put(e.getKey(), new MBJointWeight(info.getKey(), weightMap));
}
}
jointIndexMap = builder.build();
}
return jointIndexMap.get(i);
}
protected static class MBVariableClip
{
private final Variable variable;
@SuppressWarnings("unused")
private final Type type;
private final Interpolation interpolation;
private final float[] samples;
public MBVariableClip(Variable variable, Type type, Interpolation interpolation, float[] samples)
{
this.variable = variable;
this.type = type;
this.interpolation = interpolation;
this.samples = samples;
}
}
protected static class MBClip implements IClip
{
private final boolean loop;
@SerializedName("joint_clips")
private final ImmutableMap<String, ImmutableList<MBVariableClip>> jointClipsFlat;
private transient ImmutableMap<String, MBJointClip> jointClips;
@SerializedName("events")
private final ImmutableMap<String, String> eventsRaw;
private transient TreeMap<Float, Event> events;
public MBClip(boolean loop, ImmutableMap<String, ImmutableList<MBVariableClip>> clips, ImmutableMap<String, String> events)
{
this.loop = loop;
this.jointClipsFlat = clips;
this.eventsRaw = events;
}
private void initialize()
{
if(jointClips == null)
{
ImmutableMap.Builder<String, MBJointClip> builder = ImmutableMap.builder();
for (Map.Entry<String, ImmutableList<MBVariableClip>> e : jointClipsFlat.entrySet())
{
builder.put(e.getKey(), new MBJointClip(loop, e.getValue()));
}
jointClips = builder.build();
events = Maps.newTreeMap();
if (!eventsRaw.isEmpty())
{
TreeMap<Float, String> times = Maps.newTreeMap();
for (String time : eventsRaw.keySet())
{
times.put(Float.parseFloat(time), time);
}
float lastTime = Float.POSITIVE_INFINITY;
if (loop)
{
lastTime = times.firstKey();
}
for (Map.Entry<Float, String> entry : times.descendingMap().entrySet())
{
float time = entry.getKey();
float offset = lastTime - time;
if (loop)
{
offset = 1 - (1 - offset) % 1;
}
events.put(time, new Event(eventsRaw.get(entry.getValue()), offset));
}
}
}
}
@Override
public IJointClip apply(IJoint joint)
{
initialize();
if(joint instanceof MBJoint)
{
MBJoint mbJoint = (MBJoint)joint;
//MBJointInfo = jointInfos.
MBJointClip clip = jointClips.get(mbJoint.getName());
if(clip != null) return clip;
}
return JointClips.IdentityJointClip.INSTANCE;
}
@Override
public Iterable<Event> pastEvents(final float lastPollTime, final float time)
{
initialize();
return new Iterable<Event>()
{
@Override
public Iterator<Event> iterator()
{
return new UnmodifiableIterator<Event>()
{
private Float curKey;
private Event firstEvent;
private float stopTime;
{
if(lastPollTime >= time)
{
curKey = null;
}
else
{
float fractTime = time - (float)Math.floor(time);
float fractLastTime = lastPollTime - (float)Math.floor(lastPollTime);
// swap if not in order
if(fractLastTime > fractTime)
{
float tmp = fractTime;
fractTime = fractLastTime;
fractLastTime = tmp;
}
// need to wrap around, swap again
if(fractTime - fractLastTime > .5f)
{
float tmp = fractTime;
fractTime = fractLastTime;
fractLastTime = tmp;
}
stopTime = fractLastTime;
curKey = events.floorKey(fractTime);
if(curKey == null && loop && !events.isEmpty())
{
curKey = events.lastKey();
}
if(curKey != null)
{
float checkCurTime = curKey;
float checkStopTime = stopTime;
if(checkCurTime >= fractTime) checkCurTime--;
if(checkStopTime >= fractTime) checkStopTime--;
float offset = fractTime - checkCurTime;
Event event = events.get(curKey);
if(checkCurTime < checkStopTime)
{
curKey = null;
}
else if(offset != event.offset())
{
firstEvent = new Event(event.event(), offset);
}
}
}
}
@Override
public boolean hasNext()
{
return curKey != null;
}
@Override
public Event next()
{
if(curKey == null)
{
throw new NoSuchElementException();
}
Event event;
if(firstEvent == null)
{
event = events.get(curKey);
}
else
{
event = firstEvent;
firstEvent = null;
}
curKey = events.lowerKey(curKey);
if(curKey == null && loop)
{
curKey = events.lastKey();
}
if(curKey != null)
{
float checkStopTime = stopTime;
while(curKey + events.get(curKey).offset() < checkStopTime) checkStopTime--;
while(curKey + events.get(curKey).offset() >= checkStopTime + 1) checkStopTime++;
if(curKey <= checkStopTime)
{
curKey = null;
}
}
return event;
}
};
}
};
}
protected static class MBJointClip implements IJointClip
{
private final boolean loop;
private final ImmutableList<MBVariableClip> variables;
public MBJointClip(boolean loop, ImmutableList<MBVariableClip> variables)
{
this.loop = loop;
this.variables = variables;
EnumSet<Variable> hadVar = Sets.newEnumSet(Collections.<Variable>emptyList(), Variable.class);
for(MBVariableClip var : variables)
{
if(hadVar.contains(var.variable))
{
throw new IllegalArgumentException("duplicate variable: " + var);
}
hadVar.add(var.variable);
}
}
@Override
public Transformation apply(float time)
{
time -= Math.floor(time);
Vector3f translation = new Vector3f(0, 0, 0);
Vector3f scale = new Vector3f(1, 1, 1);
Vector3f origin = new Vector3f(0, 0, 0);
Vector3f rotation_axis = new Vector3f(0, 0, 0);
float rotation_angle = 0;
for(MBVariableClip var : variables)
{
int length = loop ? var.samples.length : (var.samples.length - 1);
float timeScaled = time * length;
int s1 = Mth.clamp((int)Math.round(Math.floor(timeScaled)), 0, length - 1);
float progress = timeScaled - s1;
int s2 = s1 + 1;
if(s2 == length && loop) s2 = 0;
float value = 0;
switch(var.interpolation)
{
case LINEAR:
if(var.variable == Variable.ANGLE)
{
float v1 = var.samples[s1];
float v2 = var.samples[s2];
float diff = ((v2 - v1) % 360 + 540) % 360 - 180;
value = v1 + diff * progress;
}
else
{
value = var.samples[s1] * (1 - progress) + var.samples[s2] * progress;
}
break;
case NEAREST:
value = var.samples[progress < .5f ? s1 : s2];
break;
}
switch(var.variable)
{
case X:
translation.setX(value);
break;
case Y:
translation.setY(value);
break;
case Z:
translation.setZ(value);
break;
case XROT:
rotation_axis.setX(value);
break;
case YROT:
rotation_axis.setY(value);
break;
case ZROT:
rotation_axis.setZ(value);
break;
case ANGLE:
rotation_angle = (float)Math.toRadians(value);
break;
case SCALE:
scale.set(value, value, value);
break;
case XS:
scale.setX(value);
break;
case YS:
scale.setY(value);
break;
case ZS:
scale.setX(value);
break;
case XORIGIN:
origin.setX(value - 0.5F);
break;
case YORIGIN:
origin.setY(value - 0.5F);
break;
case ZORIGIN:
origin.setX(value - 0.5F);
break;
}
}
Quaternion rot = new Quaternion(rotation_axis, rotation_angle, false);
Transformation base = new Transformation(translation, rot, scale, null);
Vector3f negOrigin = origin.copy();
negOrigin.mul(-1,-1,-1);
base = new Transformation(origin, null, null, null).compose(base).compose(new Transformation(negOrigin, null, null, null));
return base.blockCenterToCorner();
}
}
}
protected static class MBJoint implements IJoint
{
private final String name;
public MBJoint(String name)
{
this.name = name;
}
@Override
public Transformation getInvBindPose()
{
return Transformation.identity();
}
@Override
public Optional<? extends IJoint> getParent()
{
return Optional.empty();
}
public String getName()
{
return name;
}
}
protected static class MBJointWeight
{
private final String name;
private final ImmutableMap<Integer, float[]> weights;
public MBJointWeight(String name, ImmutableMap<Integer, float[]> weights)
{
this.name = name;
this.weights = weights;
}
public String getName()
{
return name;
}
public ImmutableMap<Integer, float[]> getWeights()
{
return weights;
}
}
protected static class Parameter
{
public static enum Variable
{
@SerializedName("offset_x")
X,
@SerializedName("offset_y")
Y,
@SerializedName("offset_z")
Z,
@SerializedName("axis_x")
XROT,
@SerializedName("axis_y")
YROT,
@SerializedName("axis_z")
ZROT,
@SerializedName("angle")
ANGLE,
@SerializedName("scale")
SCALE,
@SerializedName("scale_x")
XS,
@SerializedName("scale_y")
YS,
@SerializedName("scale_z")
ZS,
@SerializedName("origin_x")
XORIGIN,
@SerializedName("origin_y")
YORIGIN,
@SerializedName("origin_z")
ZORIGIN;
}
public static enum Type
{
@SerializedName("uniform")
UNIFORM;
}
public static enum Interpolation
{
@SerializedName("linear")
LINEAR,
@SerializedName("nearest")
NEAREST;
}
}
@Nullable
public Transformation getPartTransform(ModelState state, BlockElement part, int i)
{
return getPartTransform(state, i);
}
@Nullable
public Transformation getPartTransform(ModelState state, int i)
{
ImmutableCollection<MBJointWeight> infos = getJoint(i);
if(!infos.isEmpty())
{
Matrix4f m = new Matrix4f(), tmp;
float weight = 0;
for(MBJointWeight info : infos)
{
if(info.getWeights().containsKey(i))
{
ModelBlockAnimation.MBJoint joint = new ModelBlockAnimation.MBJoint(info.getName());
Transformation trOp = state.getPartTransformation(joint);
if(!trOp.isIdentity())
{
float w = info.getWeights().get(i)[0];
tmp = trOp.getMatrix();
tmp.multiply(w);
m.add(tmp);
weight += w;
}
}
}
if(weight > 1e-5)
{
m.multiply(1f / weight);
return new Transformation(m);
}
}
return null;
}
/**
* Load armature associated with a vanilla model.
*/
public static ModelBlockAnimation loadVanillaAnimation(ResourceManager manager, ResourceLocation armatureLocation)
{
try
{
try (Resource resource = manager.getResource(armatureLocation))
{
ModelBlockAnimation mba = mbaGson.fromJson(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8), ModelBlockAnimation.class);
//String json = mbaGson.toJson(mba);
return mba;
}
catch(FileNotFoundException e)
{
// this is normal. FIXME: error reporting?
return defaultModelBlockAnimation;
}
}
catch(IOException | JsonParseException e)
{
LOGGER.error("Exception loading vanilla model animation {}, skipping", armatureLocation, e);
return defaultModelBlockAnimation;
}
}
private static final Gson mbaGson = new GsonBuilder()
.registerTypeAdapter(ImmutableList.class, JsonUtils.ImmutableListTypeAdapter.INSTANCE)
.registerTypeAdapter(ImmutableMap.class, JsonUtils.ImmutableMapTypeAdapter.INSTANCE)
.setPrettyPrinting()
.enableComplexMapKeySerialization()
.disableHtmlEscaping()
.create();
private static final ModelBlockAnimation defaultModelBlockAnimation = new ModelBlockAnimation(ImmutableMap.<String, ImmutableMap<String, float[]>>of(), ImmutableMap.<String, ModelBlockAnimation.MBClip>of());
}
@@ -1,103 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.model.b3d;
import com.mojang.math.Transformation;
import net.minecraftforge.client.model.b3d.B3DLoader.NodeJoint;
import net.minecraftforge.client.model.b3d.B3DModel.Key;
import net.minecraftforge.client.model.b3d.B3DModel.Node;
import net.minecraftforge.common.animation.Event;
import net.minecraftforge.common.model.TransformationHelper;
import net.minecraftforge.common.model.animation.IClip;
import net.minecraftforge.common.model.animation.IJoint;
import net.minecraftforge.common.model.animation.IJointClip;
import net.minecraftforge.common.model.animation.JointClips;
import com.google.common.collect.ImmutableSet;
// FIXME: is this fast enough?
public enum B3DClip implements IClip
{
INSTANCE;
@Override
public IJointClip apply(final IJoint joint)
{
if(!(joint instanceof NodeJoint))
{
return JointClips.IdentityJointClip.INSTANCE;
}
return new NodeClip(((NodeJoint)joint).getNode());
}
@Override
public Iterable<Event> pastEvents(float lastPollTime, float time)
{
return ImmutableSet.of();
}
protected static class NodeClip implements IJointClip
{
private final Node<?> node;
public NodeClip(Node<?> node)
{
this.node = node;
}
@Override
public Transformation apply(float time)
{
Transformation ret = Transformation.identity();
if(node.getAnimation() == null)
{
return ret.compose(new Transformation(node.getPos(), node.getRot(), node.getScale(), null));
}
int start = Math.max(1, (int)Math.round(Math.floor(time)));
int end = Math.min(start + 1, (int)Math.round(Math.ceil(time)));
float progress = time - (float)Math.floor(time);
Key keyStart = node.getAnimation().getKeys().get(start, node);
Key keyEnd = node.getAnimation().getKeys().get(end, node);
Transformation startTr = keyStart == null ? null : new Transformation(keyStart.getPos(), keyStart.getRot(),keyStart.getScale(), null);
Transformation endTr = keyEnd == null ? null : new Transformation(keyEnd.getPos(), keyEnd.getRot(),keyEnd.getScale(), null);
if(keyStart == null)
{
if(keyEnd == null)
{
ret = ret.compose(new Transformation(node.getPos(), node.getRot(), node.getScale(), null));
}
// TODO animated TRSRTransformation for speed?
else
{
ret = ret.compose(endTr);
}
}
else if(progress < 1e-5 || keyEnd == null)
{
ret = ret.compose(startTr);
}
else
{
ret = ret.compose(TransformationHelper.slerp(startTr, endTr, progress));
}
return ret;
}
}
}
@@ -19,38 +19,6 @@
package net.minecraftforge.client.model.b3d;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Matrix4f;
import com.mojang.math.Transformation;
import com.mojang.math.Vector3f;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
import com.mojang.blaze3d.vertex.VertexFormatElement;
import net.minecraftforge.client.model.*;
import net.minecraftforge.common.model.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.base.Objects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
@@ -60,37 +28,47 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import net.minecraft.world.level.block.state.BlockState;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexFormatElement;
import com.mojang.math.Matrix4f;
import com.mojang.math.Transformation;
import com.mojang.math.Vector3f;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemOverrides;
import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType;
import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.client.resources.model.*;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.Mth;
import net.minecraftforge.client.model.b3d.B3DModel.Animation;
import net.minecraftforge.client.model.b3d.B3DModel.Face;
import net.minecraftforge.client.model.b3d.B3DModel.Key;
import net.minecraftforge.client.model.b3d.B3DModel.Mesh;
import net.minecraftforge.client.model.b3d.B3DModel.Node;
import net.minecraftforge.client.model.b3d.B3DModel.Texture;
import net.minecraftforge.client.model.b3d.B3DModel.Vertex;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.CompositeModelState;
import net.minecraftforge.client.model.ForgeModelBakery;
import net.minecraftforge.client.model.ModelLoadingException;
import net.minecraftforge.client.model.PerspectiveMapWrapper;
import net.minecraftforge.client.model.b3d.B3DModel.*;
import net.minecraftforge.client.model.data.IDynamicBakedModel;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.client.model.pipeline.BakedQuadBuilder;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.common.model.animation.IClip;
import net.minecraftforge.common.model.animation.IJoint;
import net.minecraftforge.common.model.TransformationHelper;
import net.minecraftforge.common.property.Properties;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemOverrides;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.Material;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.UnbakedModel;
import javax.annotation.Nullable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
/*
* Loader for Blitz3D models.
@@ -341,7 +319,7 @@ public enum B3DLoader
}
}
static final class NodeJoint implements IJoint
static final class NodeJoint
{
private final Node<?> node;
@@ -350,7 +328,6 @@ public enum B3DLoader
this.node = node;
}
@Override
public Transformation getInvBindPose()
{
Matrix4f m = new Transformation(node.getPos(), node.getRot(), node.getScale(), null).getMatrix();
@@ -365,7 +342,6 @@ public enum B3DLoader
return pose;
}
@Override
public Optional<NodeJoint> getParent()
{
// FIXME cache?
@@ -378,13 +354,11 @@ public enum B3DLoader
return node;
}
@Override
public int hashCode()
{
return node.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj) return true;
@@ -558,16 +532,6 @@ public enum B3DLoader
return hasChanged ? new ModelWrapper(modelLocation, model, newMeshes, smooth, gui3d, isSideLit, newDefaultKey, textures) : this;
}
@Override
public Optional<IClip> getClip(String name)
{
if(name.equals("main"))
{
return Optional.of(B3DClip.INSTANCE);
}
return Optional.empty();
}
public ModelState getDefaultState()
{
return new B3DState(model.getRoot().getAnimation(), defaultKey, defaultKey, 0);
@@ -605,6 +569,8 @@ public enum B3DLoader
private ImmutableList<BakedQuad> quads;
public record HiddenModelPart(ImmutableList<String> path) { }
public BakedWrapper(final Node<?> node, final ModelState state, final boolean smooth, final boolean gui3d, boolean isSideLit, final ImmutableSet<String> meshes, final ImmutableMap<String, TextureAtlasSprite> textures)
{
this(node, state, smooth, gui3d, isSideLit, meshes, textures, CacheBuilder.newBuilder()
@@ -689,7 +655,7 @@ public enum B3DLoader
{
generateQuads(builder, child, state, newPath);
}
if(node.getKind() instanceof Mesh && meshes.contains(node.getName()) && state.getPartTransformation(Models.getHiddenModelPart(newPath)).isIdentity())
if(node.getKind() instanceof Mesh && meshes.contains(node.getName()) && state.getPartTransformation(new HiddenModelPart(newPath)).isIdentity())
{
Mesh mesh = (Mesh)node.getKind();
Collection<Face> faces = mesh.bake(new Function<Node<?>, Matrix4f>()
@@ -718,7 +684,7 @@ public enum B3DLoader
if(f.getBrush() != null) textures = f.getBrush().getTextures();
TextureAtlasSprite sprite;
if(textures == null || textures.isEmpty()) sprite = this.textures.get("missingno");
else if(textures.get(0) == B3DModel.Texture.White) sprite = ModelLoader.White.instance();
else if(textures.get(0) == B3DModel.Texture.White) sprite = ForgeModelBakery.White.instance();
else sprite = this.textures.get(textures.get(0).getPath());
BakedQuadBuilder quadBuilder = new BakedQuadBuilder(sprite);
quadBuilder.setContractUVs(true);
@@ -62,7 +62,6 @@ import net.minecraftforge.common.data.ExistingFileHelper;
*
* @param <T> Self type, for simpler chaining of methods.
*/
@SuppressWarnings("deprecation")
public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
@Nullable
@@ -165,16 +164,6 @@ public class ModelBuilder<T extends ModelBuilder<T>> extends ModelFile {
return self();
}
/**
* @param gui3d
* @return this builder
* @deprecated Unused in 1.15, use {@link #guiLight(GuiLight)} instead.
*/
@Deprecated
public T gui3d(boolean gui3d) {
return self();
}
public T guiLight(GuiLight light) {
this.guiLight = light;
return self();
@@ -35,7 +35,7 @@ public class BlockInfo
private static final Direction[] SIDES = Direction.values();
private final BlockColors colors;
private BlockAndTintGetter world;
private BlockAndTintGetter level;
private BlockState state;
private BlockPos blockPos;
@@ -62,18 +62,13 @@ public class BlockInfo
{
if(cachedTint == tint) return cachedMultiplier;
cachedTint = tint;
cachedMultiplier = colors.getColor(state, world, blockPos, tint);
cachedMultiplier = colors.getColor(state, level, blockPos, tint);
return cachedMultiplier;
}
@Deprecated
public void updateShift()
public void setLevel(BlockAndTintGetter level)
{
}
public void setWorld(BlockAndTintGetter world)
{
this.world = world;
this.level = level;
cachedTint = -1;
cachedMultiplier = -1;
}
@@ -94,7 +89,7 @@ public class BlockInfo
public void reset()
{
this.world = null;
this.level = null;
this.state = null;
this.blockPos = null;
cachedTint = -1;
@@ -119,24 +114,24 @@ public class BlockInfo
for(int z = 0; z <= 2; z++)
{
BlockPos pos = blockPos.offset(x - 1, y - 1, z - 1);
BlockState state = world.getBlockState(pos);
t[x][y][z] = state.getLightBlock(world, pos) < 15;
int brightness = LevelRenderer.getLightColor(world, pos);
BlockState state = level.getBlockState(pos);
t[x][y][z] = state.getLightBlock(level, pos) < 15;
int brightness = LevelRenderer.getLightColor(level, pos);
s[x][y][z] = LightTexture.sky(brightness);
b[x][y][z] = LightTexture.block(brightness);
ao[x][y][z] = state.getShadeBrightness(world, pos);
ao[x][y][z] = state.getShadeBrightness(level, pos);
}
}
}
for(Direction side : SIDES)
{
BlockPos pos = blockPos.relative(side);
BlockState state = world.getBlockState(pos);
BlockState state = level.getBlockState(pos);
BlockState thisStateShape = this.state.canOcclude() && this.state.useShapeForLightOcclusion() ? this.state : Blocks.AIR.defaultBlockState();
BlockState otherStateShape = state.canOcclude() && state.useShapeForLightOcclusion() ? state : Blocks.AIR.defaultBlockState();
if(state.getLightBlock(world, pos) == 15 || Shapes.faceShapeOccludes(thisStateShape.getFaceOcclusionShape(world, blockPos, side), otherStateShape.getFaceOcclusionShape(world, pos, side.getOpposite())))
if(state.getLightBlock(level, pos) == 15 || Shapes.faceShapeOccludes(thisStateShape.getFaceOcclusionShape(level, blockPos, side), otherStateShape.getFaceOcclusionShape(level, pos, side.getOpposite())))
{
int x = side.getStepX() + 1;
int y = side.getStepY() + 1;
@@ -188,19 +183,19 @@ public class BlockInfo
public void updateFlatLighting()
{
full = Block.isShapeFullBlock(state.getCollisionShape(world, blockPos));
packed[0] = LevelRenderer.getLightColor(world, blockPos);
full = Block.isShapeFullBlock(state.getCollisionShape(level, blockPos));
packed[0] = LevelRenderer.getLightColor(level, blockPos);
for (Direction side : SIDES)
{
int i = side.ordinal() + 1;
packed[i] = LevelRenderer.getLightColor(world, blockPos.relative(side));
packed[i] = LevelRenderer.getLightColor(level, blockPos.relative(side));
}
}
public BlockAndTintGetter getWorld()
public BlockAndTintGetter getLevel()
{
return world;
return level;
}
public BlockState getState()
@@ -243,24 +238,6 @@ public class BlockInfo
return full;
}
@Deprecated
public float getShx()
{
return 0;
}
@Deprecated
public float getShy()
{
return 0;
}
@Deprecated
public float getShz()
{
return 0;
}
public int getCachedTint()
{
return cachedTint;
@@ -117,7 +117,6 @@ public class LightUtil
}
}
// TODO: probably useless now, remove?
private static final VertexFormat DEFAULT_FROM = VertexLighterFlat.withNormal(DefaultVertexFormat.BLOCK);
private static final VertexFormat DEFAULT_TO = DefaultVertexFormat.BLOCK;
private static final int[] DEFAULT_MAPPING = generateMapping(DEFAULT_FROM, DEFAULT_TO);
@@ -19,13 +19,10 @@
package net.minecraftforge.client.model.pipeline;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mojang.blaze3d.vertex.PoseStack;
@@ -314,7 +311,7 @@ public class VertexLighterFlat extends QuadGatheringTransformer
public void setWorld(BlockAndTintGetter world)
{
blockInfo.setWorld(world);
blockInfo.setLevel(world);
}
public void setState(BlockState state)
@@ -171,7 +171,6 @@ public class VertexLighterSmoothAo extends VertexLighterFlat
@Override
public void updateBlockInfo()
{
blockInfo.updateShift();
blockInfo.updateLightMatrix();
}
}
@@ -33,7 +33,7 @@ import net.minecraft.world.item.trading.MerchantOffer;
* A default, exposed implementation of ITrade. All of the other implementations of ITrade (in VillagerTrades) are not public.
* This class contains everything needed to make a MerchantOffer, the actual "trade" object shown in trading guis.
*/
public class BasicTrade implements ItemListing
public class BasicItemListing implements ItemListing
{
protected final ItemStack price;
@@ -43,7 +43,7 @@ public class BasicTrade implements ItemListing
protected final int xp;
protected final float priceMult;
public BasicTrade(ItemStack price, ItemStack price2, ItemStack forSale, int maxTrades, int xp, float priceMult)
public BasicItemListing(ItemStack price, ItemStack price2, ItemStack forSale, int maxTrades, int xp, float priceMult)
{
this.price = price;
this.price2 = price2;
@@ -53,17 +53,17 @@ public class BasicTrade implements ItemListing
this.priceMult = priceMult;
}
public BasicTrade(ItemStack price, ItemStack forSale, int maxTrades, int xp, float priceMult)
public BasicItemListing(ItemStack price, ItemStack forSale, int maxTrades, int xp, float priceMult)
{
this(price, ItemStack.EMPTY, forSale, maxTrades, xp, priceMult);
}
public BasicTrade(int emeralds, ItemStack forSale, int maxTrades, int xp, float mult)
public BasicItemListing(int emeralds, ItemStack forSale, int maxTrades, int xp, float mult)
{
this(new ItemStack(Items.EMERALD, emeralds), forSale, maxTrades, xp, mult);
}
public BasicTrade(int emeralds, ItemStack forSale, int maxTrades, int xp)
public BasicItemListing(int emeralds, ItemStack forSale, int maxTrades, int xp)
{
this(new ItemStack(Items.EMERALD, emeralds), forSale, maxTrades, xp, 1);
}
@@ -302,7 +302,6 @@ public class BiomeDictionary
addTypes(Biomes.OCEAN, OCEAN, OVERWORLD);
addTypes(Biomes.PLAINS, PLAINS, OVERWORLD);
addTypes(Biomes.DESERT, HOT, DRY, SANDY, OVERWORLD);
addTypes(Biomes.MOUNTAINS, MOUNTAIN, HILLS, OVERWORLD);
addTypes(Biomes.FOREST, FOREST, OVERWORLD);
addTypes(Biomes.TAIGA, COLD, CONIFEROUS, FOREST, OVERWORLD);
addTypes(Biomes.SWAMP, WET, SWAMP, OVERWORLD);
@@ -311,34 +310,17 @@ public class BiomeDictionary
addTypes(Biomes.THE_END, COLD, DRY, END);
addTypes(Biomes.FROZEN_OCEAN, COLD, OCEAN, SNOWY, OVERWORLD);
addTypes(Biomes.FROZEN_RIVER, COLD, RIVER, SNOWY, OVERWORLD);
addTypes(Biomes.SNOWY_TUNDRA, COLD, SNOWY, WASTELAND, OVERWORLD);
addTypes(Biomes.SNOWY_MOUNTAINS, COLD, SNOWY, MOUNTAIN, OVERWORLD);
addTypes(Biomes.MUSHROOM_FIELDS, MUSHROOM, RARE, OVERWORLD);
addTypes(Biomes.MUSHROOM_FIELD_SHORE, MUSHROOM, BEACH, RARE, OVERWORLD);
addTypes(Biomes.BEACH, BEACH, OVERWORLD);
addTypes(Biomes.DESERT_HILLS, HOT, DRY, SANDY, HILLS, OVERWORLD);
addTypes(Biomes.WOODED_HILLS, FOREST, HILLS, OVERWORLD);
addTypes(Biomes.TAIGA_HILLS, COLD, CONIFEROUS, FOREST, HILLS, OVERWORLD);
addTypes(Biomes.MOUNTAIN_EDGE, MOUNTAIN, OVERWORLD);
addTypes(Biomes.JUNGLE, HOT, WET, DENSE, JUNGLE, OVERWORLD);
addTypes(Biomes.JUNGLE_HILLS, HOT, WET, DENSE, JUNGLE, HILLS, OVERWORLD);
addTypes(Biomes.JUNGLE_EDGE, HOT, WET, JUNGLE, FOREST, RARE, OVERWORLD);
addTypes(Biomes.DEEP_OCEAN, OCEAN, OVERWORLD);
addTypes(Biomes.STONE_SHORE, BEACH, OVERWORLD);
addTypes(Biomes.SNOWY_BEACH, COLD, BEACH, SNOWY, OVERWORLD);
addTypes(Biomes.BIRCH_FOREST, FOREST, OVERWORLD);
addTypes(Biomes.BIRCH_FOREST_HILLS, FOREST, HILLS, OVERWORLD);
addTypes(Biomes.DARK_FOREST, SPOOKY, DENSE, FOREST, OVERWORLD);
addTypes(Biomes.SNOWY_TAIGA, COLD, CONIFEROUS, FOREST, SNOWY, OVERWORLD);
addTypes(Biomes.SNOWY_TAIGA_HILLS, COLD, CONIFEROUS, FOREST, SNOWY, HILLS, OVERWORLD);
addTypes(Biomes.GIANT_TREE_TAIGA, COLD, CONIFEROUS, FOREST, OVERWORLD);
addTypes(Biomes.GIANT_TREE_TAIGA_HILLS, COLD, CONIFEROUS, FOREST, HILLS, OVERWORLD);
addTypes(Biomes.WOODED_MOUNTAINS, MOUNTAIN, FOREST, SPARSE, OVERWORLD);
addTypes(Biomes.SAVANNA, HOT, SAVANNA, PLAINS, SPARSE, OVERWORLD);
addTypes(Biomes.SAVANNA_PLATEAU, HOT, SAVANNA, PLAINS, SPARSE, RARE, OVERWORLD, PLATEAU);
addTypes(Biomes.BADLANDS, MESA, SANDY, DRY, OVERWORLD);
addTypes(Biomes.WOODED_BADLANDS_PLATEAU, MESA, SANDY, DRY, SPARSE, OVERWORLD, PLATEAU);
addTypes(Biomes.BADLANDS_PLATEAU, MESA, SANDY, DRY, OVERWORLD, PLATEAU);
addTypes(Biomes.SMALL_END_ISLANDS, END);
addTypes(Biomes.END_MIDLANDS, END);
addTypes(Biomes.END_HIGHLANDS, END);
@@ -346,34 +328,15 @@ public class BiomeDictionary
addTypes(Biomes.WARM_OCEAN, OCEAN, HOT, OVERWORLD);
addTypes(Biomes.LUKEWARM_OCEAN, OCEAN, OVERWORLD);
addTypes(Biomes.COLD_OCEAN, OCEAN, COLD, OVERWORLD);
addTypes(Biomes.DEEP_WARM_OCEAN, OCEAN, HOT, OVERWORLD);
addTypes(Biomes.DEEP_LUKEWARM_OCEAN, OCEAN, OVERWORLD);
addTypes(Biomes.DEEP_COLD_OCEAN, OCEAN, COLD, OVERWORLD);
addTypes(Biomes.DEEP_FROZEN_OCEAN, OCEAN, COLD, OVERWORLD);
addTypes(Biomes.THE_VOID, VOID);
addTypes(Biomes.SUNFLOWER_PLAINS, PLAINS, RARE, OVERWORLD);
addTypes(Biomes.DESERT_LAKES, HOT, DRY, SANDY, RARE, OVERWORLD);
addTypes(Biomes.GRAVELLY_MOUNTAINS, MOUNTAIN, SPARSE, RARE, OVERWORLD);
addTypes(Biomes.FLOWER_FOREST, FOREST, HILLS, RARE, OVERWORLD);
addTypes(Biomes.TAIGA_MOUNTAINS, COLD, CONIFEROUS, FOREST, MOUNTAIN, RARE, OVERWORLD);
addTypes(Biomes.SWAMP_HILLS, WET, SWAMP, HILLS, RARE, OVERWORLD);
addTypes(Biomes.ICE_SPIKES, COLD, SNOWY, HILLS, RARE, OVERWORLD);
addTypes(Biomes.MODIFIED_JUNGLE, HOT, WET, DENSE, JUNGLE, MOUNTAIN, RARE, OVERWORLD, MODIFIED);
addTypes(Biomes.MODIFIED_JUNGLE_EDGE, HOT, SPARSE, JUNGLE, HILLS, RARE, OVERWORLD, MODIFIED);
addTypes(Biomes.TALL_BIRCH_FOREST, FOREST, DENSE, HILLS, RARE, OVERWORLD);
addTypes(Biomes.TALL_BIRCH_HILLS, FOREST, DENSE, MOUNTAIN, RARE, OVERWORLD);
addTypes(Biomes.DARK_FOREST_HILLS, SPOOKY, DENSE, FOREST, MOUNTAIN, RARE, OVERWORLD);
addTypes(Biomes.SNOWY_TAIGA_MOUNTAINS, COLD, CONIFEROUS, FOREST, SNOWY, MOUNTAIN, RARE, OVERWORLD);
addTypes(Biomes.GIANT_SPRUCE_TAIGA, DENSE, FOREST, RARE, OVERWORLD);
addTypes(Biomes.GIANT_SPRUCE_TAIGA_HILLS, DENSE, FOREST, HILLS, RARE, OVERWORLD);
addTypes(Biomes.MODIFIED_GRAVELLY_MOUNTAINS, MOUNTAIN, SPARSE, RARE, OVERWORLD, MODIFIED);
addTypes(Biomes.SHATTERED_SAVANNA, HOT, DRY, SPARSE, SAVANNA, MOUNTAIN, RARE, OVERWORLD);
addTypes(Biomes.SHATTERED_SAVANNA_PLATEAU, HOT, DRY, SPARSE, SAVANNA, HILLS, RARE, OVERWORLD, PLATEAU);
addTypes(Biomes.ERODED_BADLANDS, HOT, DRY, SPARSE, MOUNTAIN, RARE, OVERWORLD);
addTypes(Biomes.MODIFIED_WOODED_BADLANDS_PLATEAU, HOT, DRY, SPARSE, HILLS, RARE, OVERWORLD, PLATEAU, MODIFIED);
addTypes(Biomes.MODIFIED_BADLANDS_PLATEAU, HOT, DRY, SPARSE, MOUNTAIN, RARE, OVERWORLD, PLATEAU, MODIFIED);
addTypes(Biomes.BAMBOO_JUNGLE, HOT, WET, RARE, JUNGLE, OVERWORLD);
addTypes(Biomes.BAMBOO_JUNGLE_HILLS, HOT, WET, RARE, JUNGLE, HILLS, OVERWORLD);
addTypes(Biomes.SOUL_SAND_VALLEY, HOT, DRY, NETHER);
addTypes(Biomes.CRIMSON_FOREST, HOT, DRY, NETHER, FOREST);
addTypes(Biomes.WARPED_FOREST, HOT, DRY, NETHER, FOREST);
@@ -27,9 +27,10 @@ import java.util.List;
import com.google.common.collect.ImmutableList;
import net.minecraft.util.random.WeightedRandom;
import net.minecraft.world.entity.ai.behavior.ShufflingList;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.WeighedRandom;
import net.minecraft.world.level.biome.Biome;
public class BiomeManager
@@ -46,7 +47,6 @@ public class BiomeManager
currentBiomes[BiomeType.DESERT_LEGACY.ordinal()] = new TrackedList<>(
new BiomeEntry(Biomes.DESERT, 10),
new BiomeEntry(Biomes.FOREST, 10),
new BiomeEntry(Biomes.MOUNTAINS, 10),
new BiomeEntry(Biomes.SWAMP, 10),
new BiomeEntry(Biomes.PLAINS, 10),
new BiomeEntry(Biomes.TAIGA, 10)
@@ -61,7 +61,6 @@ public class BiomeManager
currentBiomes[BiomeType.WARM.ordinal()] = new TrackedList<>(
new BiomeEntry(Biomes.FOREST, 10),
new BiomeEntry(Biomes.DARK_FOREST, 10),
new BiomeEntry(Biomes.MOUNTAINS, 10),
new BiomeEntry(Biomes.PLAINS, 10),
new BiomeEntry(Biomes.BIRCH_FOREST, 10),
new BiomeEntry(Biomes.SWAMP, 10)
@@ -69,37 +68,17 @@ public class BiomeManager
currentBiomes[BiomeType.COOL.ordinal()] = new TrackedList<>(
new BiomeEntry(Biomes.FOREST, 10),
new BiomeEntry(Biomes.MOUNTAINS, 10),
new BiomeEntry(Biomes.TAIGA, 10),
new BiomeEntry(Biomes.PLAINS, 10)
);
currentBiomes[BiomeType.ICY.ordinal()] = new TrackedList<>(
new BiomeEntry(Biomes.SNOWY_TUNDRA, 30),
new BiomeEntry(Biomes.SNOWY_TAIGA, 10)
);
return currentBiomes;
}
/*
public static void addSpawnBiome(Biome biome)
{
if (!BiomeProvider.BIOMES_TO_SPAWN_IN.contains(biome))
{
BiomeProvider.BIOMES_TO_SPAWN_IN.add(biome);
}
}
public static void removeSpawnBiome(Biome biome)
{
if (BiomeProvider.BIOMES_TO_SPAWN_IN.contains(biome))
{
BiomeProvider.BIOMES_TO_SPAWN_IN.remove(biome);
}
}
*/
/**
* Add biomes that you add to the overworld without using {@link BiomeManager#addBiome(BiomeType, BiomeEntry)}
*/
@@ -157,13 +136,12 @@ public class BiomeManager
DESERT, DESERT_LEGACY, WARM, COOL, ICY;
}
public static class BiomeEntry extends WeighedRandom.WeighedRandomItem
public static class BiomeEntry
{
private final ResourceKey<Biome> key;
public BiomeEntry(ResourceKey<Biome> key, int weight)
{
super(weight);
this.key = key;
}
@@ -23,8 +23,9 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.util.random.WeightedEntry;
import net.minecraft.util.random.WeightedRandom;
import net.minecraft.world.entity.EntityType;
import net.minecraft.util.WeighedRandom;
public class DungeonHooks
{
@@ -58,7 +59,7 @@ public class DungeonHooks
if (type == mob.type)
{
itr.remove();
rarity = mob.weight + rarity;
rarity = /* mob.weight */ 0 + rarity;
break;
}
}
@@ -80,7 +81,7 @@ public class DungeonHooks
if (name == mob.type)
{
dungeonMobs.remove(mob);
return mob.weight;
return 0; // mob.weight;
}
}
return 0;
@@ -93,12 +94,12 @@ public class DungeonHooks
*/
public static EntityType<?> getRandomDungeonMob(Random rand)
{
DungeonMob mob = WeighedRandom.getRandomItem(rand, dungeonMobs).orElseThrow();
return mob.type;
DungeonMob mob = WeightedRandom.getRandomItem(rand, dungeonMobs).orElseThrow();
return null; // mob.type;
}
public static class DungeonMob extends WeighedRandom.WeighedRandomItem
public static class DungeonMob extends WeightedEntry.IntrusiveBase
{
public final EntityType<?> type;
public DungeonMob(int weight, EntityType<?> type)
@@ -113,10 +113,6 @@ public class ForgeConfig {
public final BooleanValue experimentalForgeLightPipelineEnabled;
/** @deprecated Selective reloading is no longer supported due to vanilla now reloading resources in parallel */
@Deprecated(since="1.17.1", forRemoval = true)
public final BooleanValue selectiveResourceReloadEnabled;
public final BooleanValue showLoadWarnings;
public final BooleanValue useCombinedDepthStencilAttachment;
@@ -139,11 +135,6 @@ public class ForgeConfig {
.translation("forge.configgui.forgeLightPipelineEnabled")
.define("experimentalForgeLightPipelineEnabled", false);
selectiveResourceReloadEnabled = builder
.comment("When enabled, makes specific reload tasks such as language changing quicker to run.")
.translation("forge.configgui.selectiveResourceReloadEnabled")
.define("selectiveResourceReloadEnabled", true);
showLoadWarnings = builder
.comment("When enabled, Forge will show any warnings that occurred during loading.")
.translation("forge.configgui.showLoadWarnings")
@@ -43,7 +43,6 @@ import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import net.minecraftforge.fml.config.IConfigSpec;
import net.minecraftforge.fml.loading.FMLEnvironment;
import org.apache.commons.lang3.tuple.Pair;
@@ -28,13 +28,11 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
@@ -45,9 +43,7 @@ import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.Lifecycle;
import com.mojang.serialization.codecs.RecordCodecBuilder;
@@ -83,7 +79,6 @@ import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.inventory.AnvilMenu;
import net.minecraft.world.Container;
import net.minecraft.world.item.context.UseOnContext;
@@ -97,16 +92,11 @@ import net.minecraft.world.item.alchemy.Potion;
import net.minecraft.world.item.alchemy.PotionUtils;
import net.minecraft.stats.Stats;
import net.minecraft.world.phys.Vec3;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.Registry;
import net.minecraft.core.MappedRegistry;
import net.minecraft.resources.RegistryReadOps;
import net.minecraft.resources.RegistryWriteOps;
import net.minecraft.world.*;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.feature.StructureFeature;
import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.BaseSpawner;
import net.minecraft.world.level.block.entity.FurnaceBlockEntity;
import net.minecraft.world.level.block.entity.BlockEntity;
@@ -126,8 +116,8 @@ import net.minecraftforge.common.loot.LootModifierManager;
import net.minecraftforge.common.loot.LootTableIdCondition;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.common.world.BiomeGenerationSettingsBuilder;
import net.minecraftforge.common.world.ForgeWorldType;
import net.minecraftforge.common.world.MobSpawnInfoBuilder;
import net.minecraftforge.common.world.ForgeWorldPreset;
import net.minecraftforge.common.world.MobSpawnSettingsBuilder;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.event.DifficultyChangeEvent;
import net.minecraftforge.event.ForgeEventFactory;
@@ -162,13 +152,12 @@ import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.fmllegacy.packs.ResourcePackLoader;
import net.minecraftforge.resource.ResourcePackLoader;
import net.minecraftforge.registries.DataSerializerEntry;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.IRegistryDelegate;
import net.minecraftforge.versions.mcp.MCPVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -184,17 +173,13 @@ import net.minecraft.network.chat.TextComponent;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.material.EmptyFluid;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.material.LavaFluid;
import net.minecraft.world.level.material.WaterFluid;
@@ -242,7 +227,7 @@ public class ForgeHooks
if (isCreative && Screen.hasControlDown() && state.hasBlockEntity())
te = world.getBlockEntity(pos);
result = state.getPickBlock(target, world, pos, player);
result = state.getCloneItemStack(target, world, pos, player);
if (result.isEmpty())
LOGGER.warn("Picking on: [{}] {} gave null item", target.getType(), state.getBlock().getRegistryName());
@@ -846,9 +831,9 @@ public class ForgeHooks
throw new RuntimeException("Mod fluids must override createAttributes.");
}
public static String getDefaultWorldType()
public static String getDefaultWorldPreset()
{
ForgeWorldType def = ForgeWorldType.getDefaultWorldType();
ForgeWorldPreset def = ForgeWorldPreset.getDefaultWorldPreset();
if (def != null)
return def.getRegistryName().toString();
return "default";
@@ -870,16 +855,16 @@ public class ForgeHooks
@FunctionalInterface
public interface BiomeCallbackFunction
{
Biome apply(final Biome.ClimateSettings climate, final Biome.BiomeCategory category, final Float depth, final Float scale, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns);
Biome apply(final Biome.ClimateSettings climate, final Biome.BiomeCategory category, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns);
}
public static Biome enhanceBiome(@Nullable final ResourceLocation name, final Biome.ClimateSettings climate, final Biome.BiomeCategory category, final Float depth, final Float scale, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns, final RecordCodecBuilder.Instance<Biome> codec, final BiomeCallbackFunction callback)
public static Biome enhanceBiome(@Nullable final ResourceLocation name, final Biome.ClimateSettings climate, final Biome.BiomeCategory category, final BiomeSpecialEffects effects, final BiomeGenerationSettings gen, final MobSpawnSettings spawns, final RecordCodecBuilder.Instance<Biome> codec, final BiomeCallbackFunction callback)
{
BiomeGenerationSettingsBuilder genBuilder = new BiomeGenerationSettingsBuilder(gen);
MobSpawnInfoBuilder spawnBuilder = new MobSpawnInfoBuilder(spawns);
BiomeLoadingEvent event = new BiomeLoadingEvent(name, climate, category, depth, scale, effects, genBuilder, spawnBuilder);
MobSpawnSettingsBuilder spawnBuilder = new MobSpawnSettingsBuilder(spawns);
BiomeLoadingEvent event = new BiomeLoadingEvent(name, climate, category, effects, genBuilder, spawnBuilder);
MinecraftForge.EVENT_BUS.post(event);
return callback.apply(event.getClimate(), event.getCategory(), event.getDepth(), event.getScale(), event.getEffects(), event.getGeneration().build(), event.getSpawns().build()).setRegistryName(name);
return callback.apply(event.getClimate(), event.getCategory(), event.getEffects(), event.getGeneration().build(), event.getSpawns().build()).setRegistryName(name);
}
private static class LootTableContext
@@ -1226,76 +1211,6 @@ public class ForgeHooks
//No to static init!
private static final Supplier<Codec<MappedRegistry<LevelStem>>> CODEC = Suppliers.memoize(() -> MappedRegistry.dataPackCodec(Registry.LEVEL_STEM_REGISTRY, Lifecycle.stable(), LevelStem.CODEC).xmap(LevelStem::sortMap, Function.identity()));
/**
* Restores previously "deleted" dimensions to the world.
* The {@link LenientUnboundedMapCodec} prevents this from happening, this is to fix any world from before the fix.
* TODO: Remove in 1.18
*/
public static <T> Dynamic<T> fixUpDimensionsData(Dynamic<T> data)
{
if (!"1.17.1".equals(MCPVersion.getMCVersion()))
throw new IllegalStateException("Calling deprecated code that was scheduled for removal after 1.17.1 in version: " + MCPVersion.getMCVersion());
if(!(data.getOps() instanceof RegistryReadOps))
return data;
RegistryReadOps<T> ops = (RegistryReadOps<T>) data.getOps();
Dynamic<T> dymData = data.get(DIMENSIONS_KEY).orElseEmptyMap();
Dynamic<T> withInjected = dymData.asMapOpt().map(current ->
{
List<Pair<String, T>> currentList = current.map(p -> p.mapFirst(dyn -> dyn.asString().result().orElse("")).mapSecond(Dynamic::getValue)).collect(Collectors.toList());
Set<String> currentDimNames = currentList.stream().map(Pair::getFirst).collect(Collectors.toSet());
// FixUp deleted vanilla dims.
if (!currentDimNames.containsAll(VANILLA_DIMS))
{
LOGGER.warn("Detected missing vanilla dimensions from the world!");
RegistryAccess regs = ops.registryAccess;
if (regs == null) // should not happen, but it could after a MC version update.
throw new RuntimeException("Could not access dynamic registries using reflection. " +
"The world was detected to have missing vanilla dimensions and the attempted fix did not work.");
long seed = data.get(SEED_KEY).get().result().map(d -> d.asLong(0L)).orElse(0L);
Registry<Biome> biomeReg = regs.registryOrThrow(Registry.BIOME_REGISTRY);
Registry<DimensionType> typeReg = regs.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY);
Registry<NoiseGeneratorSettings> noiseReg = regs.registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY);
//Loads the default nether and end
MappedRegistry<LevelStem> dimReg = DimensionType.defaultDimensions(typeReg, biomeReg, noiseReg, seed);
//Loads the default overworld
dimReg = WorldGenSettings.withOverworld(typeReg, dimReg, WorldGenSettings.makeDefaultOverworld(biomeReg, noiseReg, seed));
// Encode and decode the registry. This adds any dimensions from datapacks (see SimpleRegistryCodec#decode), but only the vanilla overrides are needed.
// This assumes that the datapacks for the vanilla dimensions have not changed since they were "deleted"
// If they did, this will be seen in newly generated chunks.
// Since this is to fix an older world, from before the fixes by forge, there is no way to know the state of the dimension when it was "deleted".
dimReg = CODEC.get().encodeStart(RegistryWriteOps.create(ops, regs), dimReg).flatMap(t -> CODEC.get().parse(ops, t)).result().orElse(dimReg);
for (String name : VANILLA_DIMS)
{
if (currentDimNames.contains(name))
continue;
LevelStem dim = dimReg.get(new ResourceLocation(name));
if (dim == null)
{
LOGGER.error("The world is missing dimension: " + name + ", but the attempt to re-inject it failed.");
continue;
}
LOGGER.info("Fixing world: re-injected dimension: " + name);
Optional<T> dimT = LevelStem.CODEC.encodeStart(RegistryWriteOps.create(ops, regs), dim).resultOrPartial(s->{});
if (dimT.isPresent())
currentList.add(Pair.of(name, dimT.get()));
else
LOGGER.error("Could not re-encode dimension " + name + ", can not be re-injected.");
}
}
else
return dymData;
return new Dynamic<>(ops, ops.createMap(currentList.stream().map(p -> p.mapFirst(ops::createString))));
}).result().orElse(dymData);
return data.set(DIMENSIONS_KEY, withInjected);
}
private static final Map<EntityType<? extends LivingEntity>, AttributeSupplier> FORGE_ATTRIBUTES = new HashMap<>();
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
@Deprecated
@@ -17,9 +17,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmllegacy;
package net.minecraftforge.common;
import com.google.common.base.CharMatcher;
import net.minecraftforge.common.util.MavenVersionStringHelper;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.forgespi.language.IModInfo;
import org.apache.commons.lang3.text.ExtendedMessageFormat;
@@ -62,7 +63,7 @@ public class ForgeI18n {
// {0,exc,cls} -> class of exception; {0,exc,msg} -> message from exception
customFactories.put("exc", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseException(formatString, stringBuffer, objectToParse)));
// {0,vr} -> transform VersionRange into cleartext string using fml.messages.version.restriction.* strings
customFactories.put("vr", (name, formatString, locale) -> new CustomReadOnlyFormat(((stringBuffer, o) -> MavenVersionStringHelper.parseVersionRange(formatString, stringBuffer, o))));
customFactories.put("vr", (name, formatString, locale) -> new CustomReadOnlyFormat(MavenVersionStringHelper::parseVersionRange));
// {0,i18n,fml.message} -> pass object to i18n string 'fml.message'
customFactories.put("i18n", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(ForgeI18n.parseMessage(formatString, o))));
// {0,ornull,fml.absent} -> append String value of o, or i18n string 'fml.absent' (message format transforms nulls into the string literal "null")
@@ -41,7 +41,7 @@ import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.TickEvent.ClientTickEvent;
import net.minecraftforge.event.TickEvent.ServerTickEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fmllegacy.LogicalSidedProvider;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.server.command.ForgeCommand;
import net.minecraftforge.server.command.ConfigCommand;
@@ -62,7 +62,7 @@ public class ForgeInternalHandler
{
entity.discard();
event.setCanceled(true);
BlockableEventLoop<Runnable> executor = LogicalSidedProvider.WORKQUEUE.get(event.getWorld().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
var executor = LogicalSidedProvider.WORKQUEUE.get(event.getWorld().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickTask(0, () -> event.getWorld().addFreshEntity(newEntity)));
}
}
@@ -74,7 +74,7 @@ public class ForgeInternalHandler
public void onDimensionUnload(WorldEvent.Unload event)
{
if (event.getWorld() instanceof ServerLevel)
FakePlayerFactory.unloadWorld((ServerLevel) event.getWorld());
FakePlayerFactory.unloadLevel((ServerLevel) event.getWorld());
}
@SubscribeEvent
@@ -19,9 +19,11 @@
package net.minecraftforge.common;
import com.google.common.collect.Multimap;
import net.minecraft.commands.synchronization.EmptyArgumentSerializer;
import net.minecraft.commands.synchronization.ArgumentTypes;
import net.minecraft.commands.synchronization.ArgumentSerializer;
import net.minecraft.nbt.ListTag;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
import net.minecraft.world.item.crafting.Ingredient;
@@ -39,6 +41,7 @@ import net.minecraftforge.common.data.ForgeFluidTagsProvider;
import net.minecraftforge.common.loot.CanToolPerformAction;
import net.minecraftforge.common.loot.GlobalLootModifierSerializer;
import net.minecraftforge.common.loot.LootTableIdCondition;
import net.minecraftforge.common.util.MavenVersionStringHelper;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fluids.FluidAttributes;
@@ -46,20 +49,16 @@ import net.minecraftforge.fluids.ForgeFlowingFluid;
import net.minecraftforge.fml.*;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fmllegacy.FMLWorldPersistenceHook;
import net.minecraftforge.fmllegacy.RegistryObject;
import net.minecraftforge.fmllegacy.WorldPersistenceHooks;
import net.minecraftforge.fmllegacy.event.lifecycle.FMLModIdMappingEvent;
import net.minecraftforge.fmllegacy.network.FMLNetworkConstants;
import net.minecraftforge.fmlserverevents.FMLServerStoppingEvent;
import net.minecraftforge.registries.*;
import net.minecraftforge.internal.WorldPersistenceHooks;
import net.minecraftforge.network.NetworkConstants;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.forge.event.lifecycle.GatherDataEvent;
import net.minecraftforge.network.VanillaPacketSplitter;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.network.filters.VanillaPacketSplitter;
import net.minecraftforge.server.command.EnumArgument;
import net.minecraftforge.server.command.ModIdArgument;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.versions.mcp.MCPVersion;
@@ -88,7 +87,6 @@ import net.minecraftforge.common.data.ForgeBlockTagsProvider;
import net.minecraftforge.common.data.ForgeItemTagsProvider;
import net.minecraftforge.common.data.ForgeLootTableProvider;
import net.minecraftforge.common.data.ForgeRecipeProvider;
import net.minecraftforge.common.model.animation.CapabilityAnimation;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
@@ -97,9 +95,7 @@ import net.minecraftforge.fml.common.Mod;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.*;
@Mod("forge")
public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
@@ -145,7 +141,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
return uuid.toString();
});
LOGGER.debug(FORGEMOD, "Loading Network data for FML net version: {}", FMLNetworkConstants.init());
LOGGER.debug(FORGEMOD, "Loading Network data for FML net version: {}", NetworkConstants.init());
CrashReportCallables.registerCrashCallable("FML", ForgeVersion::getSpec);
CrashReportCallables.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion());
@@ -178,7 +174,6 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
{
CapabilityItemHandler.register(event);
CapabilityFluidHandler.register(event);
CapabilityAnimation.register(event);
CapabilityEnergy.register(event);
}
@@ -200,10 +195,10 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
public void loadComplete(FMLLoadCompleteEvent event)
{
if (FMLEnvironment.dist == Dist.CLIENT)
ForgeHooksClient.registerForgeWorldTypeScreens();
ForgeHooksClient.registerForgeWorldPresetScreens();
}
public void serverStopping(FMLServerStoppingEvent evt)
public void serverStopping(ServerStoppingEvent evt)
{
WorldWorkerManager.clear();
}
@@ -229,7 +224,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
// DimensionManager.processScheduledDeletions(levelSave);
}
public void mappingChanged(FMLModIdMappingEvent evt)
public void mappingChanged(RegistryEvent.IdMappingEvent evt)
{
Ingredient.invalidateAll();
}
@@ -317,4 +312,98 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
Registry.register(Registry.LOOT_CONDITION_TYPE, new ResourceLocation("forge:loot_table_id"), LootTableIdCondition.LOOT_TABLE_ID);
Registry.register(Registry.LOOT_CONDITION_TYPE, new ResourceLocation("forge:can_tool_perform_action"), CanToolPerformAction.LOOT_CONDITION_TYPE);
}
private static final class FMLWorldPersistenceHook implements WorldPersistenceHooks.WorldPersistenceHook
{
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP");
@Override
public String getModId()
{
return "fml";
}
@Override
public CompoundTag getDataForWriting(LevelStorageSource.LevelStorageAccess levelSave, WorldData serverInfo)
{
CompoundTag fmlData = new CompoundTag();
ListTag modList = new ListTag();
ModList.get().getMods().forEach(mi->
{
final CompoundTag mod = new CompoundTag();
mod.putString("ModId", mi.getModId());
mod.putString("ModVersion", MavenVersionStringHelper.artifactVersionToString(mi.getVersion()));
modList.add(mod);
});
fmlData.put("LoadingModList", modList);
CompoundTag registries = new CompoundTag();
fmlData.put("Registries", registries);
LOGGER.debug(WORLDPERSISTENCE,"Gathering id map for writing to world save {}", serverInfo.getLevelName());
for (Map.Entry<ResourceLocation, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
{
registries.put(e.getKey().toString(), e.getValue().write());
}
LOGGER.debug(WORLDPERSISTENCE,"ID Map collection complete {}", serverInfo.getLevelName());
return fmlData;
}
@Override
public void readData(LevelStorageSource.LevelStorageAccess levelSave, WorldData serverInfo, CompoundTag tag)
{
if (tag.contains("LoadingModList"))
{
ListTag modList = tag.getList("LoadingModList", (byte)10);
for (int i = 0; i < modList.size(); i++)
{
CompoundTag mod = modList.getCompound(i);
String modId = mod.getString("ModId");
if (Objects.equals("minecraft", modId)) {
continue;
}
String modVersion = mod.getString("ModVersion");
Optional<? extends ModContainer> container = ModList.get().getModContainerById(modId);
if (!container.isPresent())
{
LOGGER.error(WORLDPERSISTENCE,"This world was saved with mod {} which appears to be missing, things may not work well", modId);
continue;
}
if (!Objects.equals(modVersion, MavenVersionStringHelper.artifactVersionToString(container.get().getModInfo().getVersion())))
{
LOGGER.warn(WORLDPERSISTENCE,"This world was saved with mod {} version {} and it is now at version {}, things may not work well", modId, modVersion, MavenVersionStringHelper.artifactVersionToString(container.get().getModInfo().getVersion()));
}
}
}
Multimap<ResourceLocation, ResourceLocation> failedElements = null;
if (tag.contains("Registries")) // 1.8, genericed out the 'registries' list
{
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
CompoundTag regs = tag.getCompound("Registries");
for (String key : regs.getAllKeys())
{
snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompound(key)));
}
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
if (failedElements != null && !failedElements.isEmpty())
{
StringBuilder buf = new StringBuilder();
buf.append("Forge Mod Loader could not load this save.\n\n")
.append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n")
.append("You will not be able to load until they are present again.\n\n");
failedElements.asMap().forEach((name, entries) ->
{
buf.append("Missing ").append(name).append(":\n");
entries.forEach(rl -> buf.append(" ").append(rl).append("\n"));
});
}
}
}
}
@@ -17,34 +17,26 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fmllegacy;
package net.minecraftforge.common;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.*;
import net.minecraftforge.fmllegacy.network.NetworkRegistry;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.ObjectHolderRegistry;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
/*
dispatchAndHandleError(ModLoadingStage.CONSTRUCT, syncExecutor, parallelExecutor, periodicTask);
statusConsumer.ifPresent(c->c.accept("Creating registries"));
dispatchAndHandleError(ModLoadingStage.CREATE_REGISTRIES, syncExecutor, parallelExecutor, periodicTask);
ObjectHolderRegistry.findObjectHolders();
CapabilityManager.INSTANCE.injectCapabilities(modList.getAllScanData());
statusConsumer.ifPresent(c->c.accept("Adding custom tag types"));
GameData.setCustomTagTypesFromRegistries();
statusConsumer.ifPresent(c->c.accept("Populating registries"));
dispatchAndHandleError(ModLoadingStage.LOAD_REGISTRIES, syncExecutor, parallelExecutor, periodicTask);
statusConsumer.ifPresent(c->c.accept("Early mod loading complete"));
statusConsumer.ifPresent(c->c.accept("Freezing data"));
GameData.freezeData();
NetworkRegistry.lock();
*/
public class ForgeStatesProvider implements IModStateProvider {
final ModLoadingState CREATE_REGISTRIES = ModLoadingState.withTransition("CREATE_REGISTRIES", "CONSTRUCT", ModLoadingPhase.GATHER, SerialTransition.of(()-> Stream.of(IModStateTransition.EventGenerator.fromFunction(RegistryEvent.NewRegistry::new))));
final ModLoadingState OBJECT_HOLDERS = ModLoadingState.withInline("OBJECT_HOLDERS", "CREATE_REGISTRIES", ModLoadingPhase.GATHER, ml-> ObjectHolderRegistry.findObjectHolders());
@@ -57,4 +49,25 @@ public class ForgeStatesProvider implements IModStateProvider {
public List<IModLoadingState> getAllStates() {
return List.of(CREATE_REGISTRIES, OBJECT_HOLDERS, INJECT_CAPABILITIES, CUSTOM_TAGS, LOAD_REGISTRIES, FREEZE, NETLOCK);
}
static record SerialTransition<T extends Event & IModBusEvent>(Supplier<Stream<EventGenerator<?>>> eventStream, BiFunction<Executor, ? extends EventGenerator<T>, CompletableFuture<List<Throwable>>> preDispatchHook, BiFunction<Executor, ? extends EventGenerator<T>, CompletableFuture<List<Throwable>>> postDispatchHook, BiFunction<Executor, CompletableFuture<List<Throwable>>, CompletableFuture<List<Throwable>>> finalActivityGenerator) implements IModStateTransition {
public static <T extends Event & IModBusEvent> SerialTransition<T> of(Supplier<Stream<EventGenerator<?>>> eventStream) {
return new SerialTransition<T>(eventStream, (t, f)->CompletableFuture.completedFuture(Collections.emptyList()), (t, f)->CompletableFuture.completedFuture(Collections.emptyList()), (e, prev) ->prev.thenApplyAsync(Function.identity(), e));
}
@Override
public Supplier<Stream<EventGenerator<?>>> eventFunctionStream() {
return eventStream;
}
@Override
public ThreadSelector threadSelector() {
return ThreadSelector.SYNC;
}
// These never progress the ModLoadingStage..
@Override
public BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextModLoadingStage() {
return ModLoadingStage::currentState;
}
}
}
@@ -19,7 +19,10 @@
package net.minecraftforge.common;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.util.StringRepresentable;
import java.util.function.Function;
@@ -58,6 +61,18 @@ public interface IExtensibleEnum
* Use this instead of {@link StringRepresentable#fromEnum(Supplier, Function)} for extensible enums because this not cache the enum values on construction
*/
static <E extends Enum<E> & StringRepresentable> Codec<E> createCodecForExtensibleEnum(Supplier<E[]> valuesSupplier, Function<? super String, ? extends E> enumValueFromNameFunction) {
return StringRepresentable.fromStringResolver(Enum::ordinal, (id) -> valuesSupplier.get()[id], enumValueFromNameFunction);
return Codec.either(Codec.STRING, Codec.INT).comapFlatMap(
either -> either.map(
str -> {
var val = enumValueFromNameFunction.apply(str);
return val != null ? DataResult.success(val) : DataResult.error("Unknown enum value name: " + str);
},
num -> {
var values = valuesSupplier.get();
return num >= 0 && num < values.length ? DataResult.success(values[num]) : DataResult.error("Unknown enum id: " + num);
}
),
value -> Either.left(value.getSerializedName())
);
}
}
@@ -25,7 +25,6 @@ import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import com.google.gson.*;
import it.unimi.dsi.fastutil.booleans.BooleanConsumer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
@@ -48,12 +47,12 @@ import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
import net.minecraftforge.fmllegacy.network.NetworkDirection;
import net.minecraftforge.fmllegacy.network.NetworkEvent;
import net.minecraftforge.fmllegacy.network.NetworkRegistry;
import net.minecraftforge.fmllegacy.network.PacketDistributor;
import net.minecraftforge.fmllegacy.network.simple.SimpleChannel;
import net.minecraftforge.fmllegacy.server.ServerLifecycleHooks;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;
import net.minecraftforge.server.ServerLifecycleHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -406,7 +405,7 @@ public class TierSortingRegistry
private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggedInEvent event)
{
if (event.getNetworkManager() == null || !event.getNetworkManager().isMemoryConnection())
if (event.getConnection() == null || !event.getConnection().isMemoryConnection())
recalculateItemTiers();
}
}
@@ -32,7 +32,7 @@ import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
import net.minecraft.core.NonNullList;
import net.minecraftforge.event.village.VillagerTradesEvent;
import net.minecraftforge.event.village.WandererTradesEvent;
import net.minecraftforge.fmlserverevents.FMLServerAboutToStartEvent;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.registries.ForgeRegistries;
public class VillagerTradingManager
@@ -52,7 +52,7 @@ public class VillagerTradingManager
VillagerTrades.WANDERING_TRADER_TRADES.int2ObjectEntrySet().forEach(e -> WANDERER_TRADES.put(e.getIntKey(), Arrays.copyOf(e.getValue(), e.getValue().length)));
}
static void loadTrades(FMLServerAboutToStartEvent e)
static void loadTrades(ServerAboutToStartEvent e)
{
postWandererEvent();
postVillagerEvents();
@@ -1,66 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.animation;
import com.google.common.base.MoreObjects;
/**
* Event stored in the clip
*/
public final class Event implements Comparable<Event>
{
private final String event;
private final float offset;
public Event(String event, float offset)
{
this.event = event;
this.offset = offset;
}
/**
* @return the name of the event.
*/
public String event()
{
return event;
}
/**
* @return how long ago the event happened, relative to the next event / first query time
*/
public float offset()
{
return offset;
}
@Override
public int compareTo(Event event)
{
return Float.compare(offset, event.offset);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(getClass()).add("event", event).add("offset", offset).toString();
}
}
@@ -1,30 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.animation;
/**
* Handler for animation events;
*/
public interface IEventHandler<T>
{
void handleEvents(T instance, float time, Iterable<Event> pastEvents);
}
@@ -1,31 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.animation;
/**
* Time-varying value associated with the animation.
* Return value should be constant with the respect to the input and reasonable context (current render frame).
* Simplest example is the input time itself.
* Unity calls them Parameters, Unreal calls them Variables.
*/
public interface ITimeValue
{
float apply(float input);
}
@@ -1,402 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.animation;
import java.io.IOException;
import java.util.regex.Pattern;
import net.minecraft.util.StringRepresentable;
import java.util.function.Function;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import javax.annotation.Nullable;
/**
* Various implementations of ITimeValue.
*/
public final class TimeValues
{
public static enum IdentityValue implements ITimeValue, StringRepresentable
{
INSTANCE;
@Override
public float apply(float input)
{
return input;
}
@Override
public String getSerializedName()
{
return "identity";
}
}
public static final class ConstValue implements ITimeValue
{
private final float output;
public ConstValue(float output)
{
this.output = output;
}
@Override
public float apply(float input)
{
return output;
}
@Override
public int hashCode()
{
return Objects.hashCode(output);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConstValue other = (ConstValue) obj;
return output == other.output;
}
}
/**
* Simple value holder.
*/
public static final class VariableValue implements ITimeValue
{
private float output;
public VariableValue(float initialValue)
{
this.output = initialValue;
}
public void setValue(float newValue)
{
this.output = newValue;
}
@Override
public float apply(float input)
{
return output;
}
@Override
public int hashCode()
{
return Objects.hashCode(output);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VariableValue other = (VariableValue) obj;
return output == other.output;
}
}
public static final class SimpleExprValue implements ITimeValue
{
private static final Pattern opsPattern = Pattern.compile("[+\\-*/mMrRfF]+");
private final String operators;
private final ImmutableList<ITimeValue> args;
public SimpleExprValue(String operators, ImmutableList<ITimeValue> args)
{
this.operators = operators;
this.args = args;
}
@Override
public float apply(float input)
{
float ret = input;
for(int i = 0; i < operators.length(); i++)
{
float arg = args.get(i).apply(input);
switch(operators.charAt(i))
{
case '+': ret += arg; break;
case '-': ret -= arg; break;
case '*': ret *= arg; break;
case '/': ret /= arg; break;
case 'm': ret = Math.min(ret, arg); break;
case 'M': ret = Math.max(ret, arg); break;
case 'r': ret = (float)Math.floor(ret / arg) * arg; break;
case 'R': ret = (float)Math.ceil(ret / arg) * arg; break;
case 'f': ret -= Math.floor(ret / arg) * arg; break;
case 'F': ret = (float)Math.ceil(ret / arg) * arg - ret; break;
}
}
return ret;
}
@Override
public int hashCode()
{
return Objects.hashCode(operators, args);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleExprValue other = (SimpleExprValue) obj;
return Objects.equal(operators, other.operators) && Objects.equal(args, other.args);
}
}
public static final class CompositionValue implements ITimeValue
{
private final ITimeValue g;
private final ITimeValue f;
public CompositionValue(ITimeValue g, ITimeValue f)
{
super();
this.g = g;
this.f = f;
}
@Override
public float apply(float input)
{
return g.apply(f.apply(input));
}
@Override
public int hashCode()
{
return Objects.hashCode(g, f);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CompositionValue other = (CompositionValue) obj;
return Objects.equal(g, other.g) && Objects.equal(f, other.f);
}
}
public static final class ParameterValue implements ITimeValue, StringRepresentable
{
private final String parameterName;
private final Function<String, ITimeValue> valueResolver;
private ITimeValue parameter;
public ParameterValue(String parameterName, Function<String, ITimeValue> valueResolver)
{
this.parameterName = parameterName;
this.valueResolver = valueResolver;
}
@Override
public String getSerializedName()
{
return parameterName;
}
private void resolve()
{
if(parameter == null)
{
if(valueResolver != null)
{
parameter = valueResolver.apply(parameterName);
}
if(parameter == null)
{
throw new IllegalArgumentException("Couldn't resolve parameter value " + parameterName);
}
}
}
@Override
public float apply(float input)
{
resolve();
return parameter.apply(input);
}
@Override
public int hashCode()
{
resolve();
return parameter.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ParameterValue other = (ParameterValue) obj;
resolve();
other.resolve();
return Objects.equal(parameter, other.parameter);
}
}
public static enum CommonTimeValueTypeAdapterFactory implements TypeAdapterFactory
{
INSTANCE;
private final ThreadLocal<Function<String, ITimeValue>> valueResolver = new ThreadLocal<Function<String, ITimeValue>>();
public void setValueResolver(@Nullable Function<String, ITimeValue> valueResolver)
{
this.valueResolver.set(valueResolver);
}
@Override
@SuppressWarnings("unchecked")
@Nullable
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
{
if(type.getRawType() != ITimeValue.class)
{
return null;
}
return (TypeAdapter<T>)new TypeAdapter<ITimeValue>()
{
@Override
public void write(JsonWriter out, ITimeValue parameter) throws IOException
{
if(parameter instanceof ConstValue)
{
out.value(((ConstValue)parameter).output);
}
else if(parameter instanceof SimpleExprValue)
{
SimpleExprValue p = (SimpleExprValue)parameter;
out.beginArray();
out.value(p.operators);
for(ITimeValue v : p.args)
{
write(out, v);
}
out.endArray();
}
else if(parameter instanceof CompositionValue)
{
CompositionValue p = (CompositionValue)parameter;
out.beginArray();
out.value("compose");
write(out, p.g);
write(out, p.f);
out.endArray();
}
else if(parameter instanceof StringRepresentable)
{
out.value("#" + ((StringRepresentable)parameter).getSerializedName());
}
}
@Override
public ITimeValue read(JsonReader in) throws IOException
{
switch(in.peek())
{
case NUMBER:
return new ConstValue((float)in.nextDouble());
case BEGIN_ARRAY:
in.beginArray();
String type = in.nextString();
ITimeValue p;
if(SimpleExprValue.opsPattern.matcher(type).matches())
{
ImmutableList.Builder<ITimeValue> builder = ImmutableList.builder();
while(in.hasNext())
{
builder.add(read(in));
}
p = new SimpleExprValue(type, builder.build());
}
else if("compose".equals(type))
{
p = new CompositionValue(read(in), read(in));
}
else
{
throw new IOException("Unknown TimeValue type \"" + type + "\"");
}
in.endArray();
return p;
case STRING:
String string = in.nextString();
if(string.equals("#identity"))
{
return IdentityValue.INSTANCE;
}
if(!string.startsWith("#"))
{
throw new IOException("Expected TimeValue reference, got \"" + string + "\"");
}
// User Parameter TimeValue
return new ParameterValue(string.substring(1), valueResolver.get());
default:
throw new IOException("Expected TimeValue, got " + in.peek());
}
}
};
}
}
}
@@ -1,62 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.capabilities;
import java.lang.annotation.*;
/**
* When placed on a FIELD, the field will be set to an
* instance of Capability once that capability is registered.
* That field must be static and be able to hold a instance
* of 'Capability'
*
* Example:
* <pre>{@code
* @CapabilityInject(IExampleCapability.class)
* private static final Capability<IExampleCapability> TEST_CAP = null;
* }</pre>
*
* When placed on a METHOD, the method will be invoked once the
* capability is registered. This allows you to have a 'enable features'
* callback. It MUST have one parameter of type 'Capability;
*
* Example:
* <pre>{@code
* @CapabilityInject(IExampleCapability.class)
* private static void capRegistered(Capability<IExampleCapability> cap) {}
* }</pre>
*
* <b>Warning</b>: Capability injections are run in the thread that the capablity is registered.
* Due to parallel mod loading, this can potentially be off of the main thread.
*
* @deprecated Use {@link CapabilityManager#get(CapabilityToken)}
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Deprecated(since = "1.18", forRemoval = true)
public @interface CapabilityInject
{
/**
* The capability interface to listen for registration.
* Note:
* When reading annotations, DO NOT call this function as it will cause a hard dependency on the class.
*/
Class<?> value();
}
@@ -19,23 +19,13 @@
package net.minecraftforge.common.capabilities;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import net.minecraftforge.fml.ModLoader;
import net.minecraftforge.forgespi.language.ModFileScanData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Type;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.IdentityHashMap;
import java.util.List;
import static net.minecraftforge.fml.Logging.CAPABILITIES;
@@ -43,23 +33,6 @@ public enum CapabilityManager
{
INSTANCE;
static final Logger LOGGER = LogManager.getLogger();
private static final Type CAP_INJECT = Type.getType(CapabilityInject.class);
/**
* Registers a capability to be consumed by others.
* APIs who define the capability should call this.
* To retrieve the Capability instance, use the @CapabilityInject annotation.
* This method is safe to call during parallel mod loading.
*
* @param type The class type to be registered
* @deprecated use {@link RegisterCapabilitiesEvent}
*/
@Deprecated(since = "1.18", forRemoval = true)
public <T> void register(Class<T> type)
{
Objects.requireNonNull(type,"Attempted to register a capability with invalid type");
get(Type.getInternalName(type), true);
}
public static <T> Capability<T> get(CapabilityToken<T> type)
@@ -103,81 +76,7 @@ public enum CapabilityManager
private final IdentityHashMap<String, Capability<?>> providers = new IdentityHashMap<>();
public void injectCapabilities(List<ModFileScanData> data)
{
final List<ModFileScanData.AnnotationData> elementsToInject = data.stream()
.map(ModFileScanData::getAnnotations)
.flatMap(Collection::stream)
.filter(a -> CAP_INJECT.equals(a.annotationType()))
.collect(Collectors.toList());
final IdentityHashMap<String, List<Function<Capability<?>, Object>>> callbacks = new IdentityHashMap<>();
elementsToInject.forEach(entry -> gatherCallbacks(callbacks, entry));
var event = new RegisterCapabilitiesEvent();
ModLoader.get().postEvent(event);
}
private void gatherCallbacks(Map<String, List<Function<Capability<?>, Object>>> callbacks, ModFileScanData.AnnotationData annotationData)
{
final String targetClass = annotationData.clazz().getClassName();
final String targetName = annotationData.memberName();
Type type = (Type)annotationData.annotationData().get("value");
if (type == null)
{
LOGGER.warn(CAPABILITIES,"Unable to inject capability at {}.{} (Invalid Annotation)", targetClass, targetName);
return;
}
final String capabilityName = type.getInternalName();
final Capability<?> cap = get(capabilityName, false);
if (annotationData.memberName().indexOf('(') > 0)
{
cap.addListener(input ->
{
try
{
for (Method mtd : Class.forName(targetClass).getDeclaredMethods())
{
if (targetName.equals(mtd.getName() + Type.getMethodDescriptor(mtd)))
{
if ((mtd.getModifiers() & Modifier.STATIC) != Modifier.STATIC)
{
LOGGER.warn(CAPABILITIES,"Unable to inject capability {} at {}.{} (Non-Static)", capabilityName, targetClass, targetName);
return;
}
mtd.setAccessible(true);
mtd.invoke(null, input);
return;
}
}
LOGGER.warn(CAPABILITIES,"Unable to inject capability {} at {}.{} (Method Not Found)", capabilityName, targetClass, targetName);
}
catch (Exception e)
{
LOGGER.warn(CAPABILITIES,"Unable to inject capability {} at {}.{}", capabilityName, targetClass, targetName, e);
}
});
}
else
{
cap.addListener(input ->
{
try
{
Field field = Class.forName(targetClass).getDeclaredField(targetName);
if ((field.getModifiers() & Modifier.STATIC) != Modifier.STATIC)
{
LOGGER.warn(CAPABILITIES,"Unable to inject capability {} at {}.{} (Non-Static)", capabilityName, targetClass, targetName);
return;
}
field.setAccessible(true);
field.set(null, input);
}
catch (Exception e)
{
LOGGER.warn(CAPABILITIES,"Unable to inject capability {} at {}.{}", capabilityName, targetClass, targetName, e);
}
});
}
}
}
@@ -27,6 +27,7 @@ import com.google.common.annotations.VisibleForTesting;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.core.Direction;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.ForgeEventFactory;
@@ -34,7 +35,7 @@ import java.util.function.Supplier;
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implements ICapabilityProvider
public abstract class CapabilityProvider<B extends ICapabilityProviderImpl<B>> implements ICapabilityProviderImpl<B>
{
@VisibleForTesting
static boolean SUPPORTS_LAZY_CAPABILITIES = true;
@@ -188,4 +189,38 @@ public abstract class CapabilityProvider<B extends CapabilityProvider<B>> implem
final CapabilityDispatcher disp = getCapabilities();
return !valid || disp == null ? LazyOptional.empty() : disp.getCapability(cap, side);
}
/**
* Special implementation for cases which have a superclass and can't extend CapabilityProvider directly.
* See {@link LevelChunk}
*/
public static class AsField<B extends ICapabilityProviderImpl<B>> extends CapabilityProvider<B>
{
public AsField(Class<B> baseClass)
{
super(baseClass);
}
public AsField(Class<B> baseClass, boolean isLazy)
{
super(baseClass, isLazy);
}
public void initInternal()
{
gatherCapabilities();
}
@Nullable
public CompoundTag serializeInternal()
{
return serializeCaps();
}
public void deserializeInternal(CompoundTag tag)
{
deserializeCaps(tag);
}
};
}
@@ -19,9 +19,11 @@
package net.minecraftforge.common.capabilities;
import net.minecraftforge.fml.common.asm.CapabilityTokenSubclass;
/**
* Inspired by {@link com.google.common.reflect.TypeToken TypeToken}, use a subclass to capture
* generic types. Then uses {@link net.minecraftforge.common.asm.CapabilityTokenSubclass a transformer}
* generic types. Then uses {@link CapabilityTokenSubclass a transformer}
* to convert that generic into a string returned by {@link #getType}
* This allows us to know the generic type, without having a hard reference to the
* class.
@@ -0,0 +1,11 @@
package net.minecraftforge.common.capabilities;
import javax.annotation.Nullable;
public interface ICapabilityProviderImpl<B extends ICapabilityProviderImpl<B>> extends ICapabilityProvider
{
boolean areCapsCompatible(CapabilityProvider<B> other);
boolean areCapsCompatible(@Nullable CapabilityDispatcher other);
void invalidateCaps();
void reviveCaps();
}
@@ -43,11 +43,6 @@ public class ConditionalAdvancement
return new Builder();
}
@Deprecated
public static boolean processConditions(JsonObject json) {
return processConditional(json) != null;
}
/**
* Processes the conditional advancement during loading.
* @param json The incoming json from the advancement file.
@@ -28,10 +28,10 @@ import com.google.gson.JsonObject;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient.Value;
public class StackList implements Value
public class MultiItemValue implements Value
{
private Collection<ItemStack> items;
public StackList(Collection<ItemStack> items)
public MultiItemValue(Collection<ItemStack> items)
{
this.items = Collections.unmodifiableCollection(items);
}
@@ -82,9 +82,9 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider
tag(Tags.Items.GEMS_PRISMARINE).add(Items.PRISMARINE_CRYSTALS);
tag(Tags.Items.GEMS_QUARTZ).add(Items.QUARTZ);
copy(Tags.Blocks.GLASS, Tags.Items.GLASS);
func_240521_a_Colored(Tags.Blocks.GLASS, Tags.Items.GLASS);
copyColored(Tags.Blocks.GLASS, Tags.Items.GLASS);
copy(Tags.Blocks.GLASS_PANES, Tags.Items.GLASS_PANES);
func_240521_a_Colored(Tags.Blocks.GLASS_PANES, Tags.Items.GLASS_PANES);
copyColored(Tags.Blocks.GLASS_PANES, Tags.Items.GLASS_PANES);
copy(Tags.Blocks.GRAVEL, Tags.Items.GRAVEL);
tag(Tags.Items.GUNPOWDER).add(Items.GUNPOWDER);
tag(Tags.Items.HEADS).add(Items.CREEPER_HEAD, Items.DRAGON_HEAD, Items.PLAYER_HEAD, Items.SKELETON_SKULL, Items.WITHER_SKELETON_SKULL, Items.ZOMBIE_HEAD);
@@ -157,7 +157,7 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider
}
}
private void func_240521_a_Colored(Tag.Named<Block> blockGroup, Tag.Named<Item> itemGroup)
private void copyColored(Tag.Named<Block> blockGroup, Tag.Named<Item> itemGroup)
{
String blockPre = blockGroup.getName().getPath().toUpperCase(Locale.ENGLISH) + '_';
String itemPre = itemGroup.getName().getPath().toUpperCase(Locale.ENGLISH) + '_';
@@ -174,7 +174,7 @@ public interface IForgeBlock
* @param fluid The current fluid state at current position
* @return True if the block is actually destroyed.
*/
default boolean removedByPlayer(BlockState state, Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
default boolean onDestroyedByPlayer(BlockState state, Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
{
self().playerWillDestroy(world, pos, state, player);
return world.setBlock(pos, fluid.createLegacyBlock(), world.isClientSide ? 11 : 3);
@@ -227,7 +227,7 @@ public interface IForgeBlock
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(BlockState state, BlockGetter world, BlockPos pos, SpawnPlacements.Type type, EntityType<?> entityType)
default boolean isValidSpawn(BlockState state, BlockGetter world, BlockPos pos, SpawnPlacements.Type type, EntityType<?> entityType)
{
return state.isValidSpawn(world, pos, entityType);
}
@@ -280,7 +280,7 @@ public interface IForgeBlock
* @param target The full target the player is looking at
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
*/
default ItemStack getPickBlock(BlockState state, HitResult target, BlockGetter world, BlockPos pos, Player player)
default ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, Player player)
{
return self().getCloneItemStack(world, pos, state);
}
@@ -574,7 +574,7 @@ public interface IForgeBlock
* @param face The face that the fire is coming from
* @param igniter The entity that lit the fire
*/
default void catchFire(BlockState state, Level world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {}
default void onCaughtFire(BlockState state, Level world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {}
/**
* Called when fire is updating on a neighbor block.
@@ -23,6 +23,8 @@ import javax.annotation.Nonnull;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
@@ -66,7 +68,13 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
* @param net The NetworkManager the packet originated from
* @param pkt The data packet
*/
default void onDataPacket(net.minecraft.network.Connection net, net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket pkt){ }
default void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt)
{
CompoundTag compoundtag = pkt.getTag();
if (compoundtag != null) {
self().load(compoundtag);
}
}
/**
* Called when the chunk's TE update tag, gotten from {@link BlockEntity#getUpdateTag()}, is received on the client.
@@ -131,9 +131,9 @@ public interface IForgeBlockState
* @param fluid The current fluid and block state for the position in the world.
* @return True if the block is actually destroyed.
*/
default boolean removedByPlayer(Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
default boolean onDestroyedByPlayer(Level world, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
{
return self().getBlock().removedByPlayer(self(), world, pos, player, willHarvest, fluid);
return self().getBlock().onDestroyedByPlayer(self(), world, pos, player, willHarvest, fluid);
}
/**
@@ -160,9 +160,9 @@ public interface IForgeBlockState
* @param type The Mob Category Type
* @return True to allow a mob of the specified category to spawn, false to prevent it.
*/
default boolean canCreatureSpawn(LevelReader world, BlockPos pos, Type type, EntityType<?> entityType)
default boolean isValidSpawn(LevelReader world, BlockPos pos, Type type, EntityType<?> entityType)
{
return self().getBlock().canCreatureSpawn(self(), world, pos, type, entityType);
return self().getBlock().isValidSpawn(self(), world, pos, type, entityType);
}
/**
@@ -227,9 +227,9 @@ public interface IForgeBlockState
* @param target The full target the player is looking at
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
*/
default ItemStack getPickBlock(HitResult target, BlockGetter world, BlockPos pos, Player player)
default ItemStack getCloneItemStack(HitResult target, BlockGetter world, BlockPos pos, Player player)
{
return self().getBlock().getPickBlock(self(), target, world, pos, player);
return self().getBlock().getCloneItemStack(self(), target, world, pos, player);
}
/**
@@ -490,9 +490,9 @@ public interface IForgeBlockState
* @param face The face that the fire is coming from
* @param igniter The entity that lit the fire
*/
default void catchFire(Level world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter)
default void onCaughtFire(Level world, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter)
{
self().getBlock().catchFire(self(), world, pos, face, igniter);
self().getBlock().onCaughtFire(self(), world, pos, face, igniter);
}
/**
@@ -550,14 +550,14 @@ public interface IForgeBlockState
}
/**
* Get the {@code PathNodeType} for this block. Return {@code null} for vanilla behavior.
* Get the {@code BlockPathTypes} for this block. Return {@code null} for vanilla behavior.
*
* @return the PathNodeType
*/
@Nullable
default BlockPathTypes getAiPathNodeType(BlockGetter world, BlockPos pos)
default BlockPathTypes getBlockPathType(BlockGetter world, BlockPos pos)
{
return getAiPathNodeType(world, pos, null);
return getBlockPathType(world, pos, null);
}
/**
@@ -566,7 +566,7 @@ public interface IForgeBlockState
* @return the PathNodeType
*/
@Nullable
default BlockPathTypes getAiPathNodeType(BlockGetter world, BlockPos pos, @Nullable Mob entity)
default BlockPathTypes getBlockPathType(BlockGetter world, BlockPos pos, @Nullable Mob entity)
{
return self().getBlock().getAiPathNodeType(self(), world, pos, entity);
}
@@ -100,7 +100,7 @@ public interface IForgeFluid
/**
* Queries if this fluid should render in a given layer.
* A custom {@link IBakedModel} can use {@link net.minecraftforge.client.MinecraftForgeClient#getRenderLayer()} to alter the model based on layer.
* A custom {@link IBakedModel} can use {@link net.minecraftforge.client.MinecraftForgeClient#getRenderType()} to alter the model based on layer.
*/
/* TODO: reimplement
default boolean canRenderInLayer(IFluidState state, BlockRenderLayer layer)
@@ -52,8 +52,6 @@ public interface IForgeFluidState
return self().getType().isEntityInside(self(), world, pos, entity, yToTest, tag, testingHead);
}
/**
* Location sensitive version of getExplosionResistance
*
@@ -67,13 +65,4 @@ public interface IForgeFluidState
return self().getType().getExplosionResistance(self(), world, pos, explosion);
}
/**
* Queries if this fluidstate should render in a given layer.
* A custom {@link IBakedModel} can use {@link net.minecraftforge.client.MinecraftForgeClient#getRenderLayer()} to alter the model based on layer.
*/
/* TODO: reimplement
default boolean canRenderInLayer(BlockRenderLayer layer)
{
return getFluidState().getFluid().canRenderInLayer(getFluidState(), layer);
}*/
}
@@ -55,7 +55,7 @@ import net.minecraftforge.common.ToolAction;
import net.minecraftforge.common.ToolActions;
import net.minecraftforge.registries.IForgeRegistryEntry;
// TODO review most of the methods in this "patch"
// TODO systemic review of all extension functions. lots of unused -C
public interface IForgeItem
{
private Item self()
@@ -324,19 +324,6 @@ public interface IForgeItem
return java.util.Collections.singletonList(self().getItemCategory());
}
/**
* Determines the base experience for a player when they remove this item from a
* furnace slot. This number must be between 0 and 1 for it to be valid. This
* number will be multiplied by the stack size to get the total experience.
*
* @param item The item stack the player is picking up.
* @return The amount to award for each item.
*/
default float getSmeltingExperience(ItemStack item)
{
return -1; // -1 will default to the old lookups.
}
/**
*
* Should this item, when held, allow sneak-clicks to pass through to the
@@ -443,51 +430,6 @@ public interface IForgeItem
return !stack.hasTag() ? 0 : stack.getTag().getInt("Damage");
}
/**
* Determines if the durability bar should be rendered for this item. Defaults
* to vanilla stack.isDamaged behavior. But modders can use this for any data
* they wish.
*
* @param stack The current Item Stack
* @return True if it should render the 'durability' bar.
* @deprecated To be removed in 1.18. Override {@link Item#isBarVisible(ItemStack)} instead.
*/
@Deprecated(forRemoval = true, since = "1.17.1")
default boolean showDurabilityBar(ItemStack stack)
{
return stack.isDamaged();
}
/**
* Queries the percentage of the 'Durability' bar that should be drawn.
*
* @param stack The current ItemStack
* @return 0.0 for 100% (no damage / full bar), 1.0 for 0% (fully damaged /
* empty bar)
* @deprecated To be removed in 1.18. Override {@link Item#getBarWidth(ItemStack)} instead, with the notable difference
* that the new method returns the width of the colored bar in pixels (where a full bar is 13px wide).
*/
@Deprecated(forRemoval = true, since = "1.17.1")
default double getDurabilityForDisplay(ItemStack stack)
{
return (double) stack.getDamageValue() / (double) stack.getMaxDamage();
}
/**
* Returns the packed int RGB value used to render the durability bar in the
* GUI. Defaults to a value based on the hue scaled based on
* {@link #getDurabilityForDisplay}, but can be overriden.
*
* @param stack Stack to get durability from
* @return A packed RGB value for the durability colour (0x00RRGGBB)
* @deprecated To be removed in 1.18. Override {@link Item#getBarColor(ItemStack)} instead.
*/
@Deprecated(forRemoval = true, since = "1.17.1")
default int getRGBDurabilityForDisplay(ItemStack stack)
{
return Mth.hsvToRgb(Math.max(0.0F, (float) (1.0F - getDurabilityForDisplay(stack))) / 3.0F, 1.0F, 1.0F);
}
/**
* Return the maxDamage for this ItemStack. Defaults to the maxDamage field in
* this item, but can be overridden here for other sources such as NBT.
@@ -534,8 +476,7 @@ public interface IForgeItem
*/
default boolean canPerformAction(ItemStack stack, ToolAction toolAction)
{
// Temporary patch to keep #isShield working until its removed; change to `return false` once removed
return isShield(stack, null) && ToolActions.DEFAULT_SHIELD_ACTIONS.contains(toolAction);
return false;
}
/**
@@ -676,14 +617,6 @@ public interface IForgeItem
return null;
}
//TODO, properties dont exist anymore
// default ImmutableMap<String, ITimeValue> getAnimationParameters(final ItemStack stack, final World world, final LivingEntity entity)
// {
// com.google.common.collect.ImmutableMap.Builder<String, ITimeValue> builder = ImmutableMap.builder();
// getItem().properties.forEach((k,v) -> builder.put(k.toString(), input -> v.call(stack, world, entity)));
// return builder.build();
// }
/**
* Can this Item disable a shield
*
@@ -698,21 +631,6 @@ public interface IForgeItem
return this instanceof AxeItem;
}
/**
* {@return {@code true} if this item is considered a shield}
*
* @param stack the item stack
* @param entity the entity holding the item stack
* @deprecated To be removed in 1.18. Override {@link #canPerformAction(ItemStack, ToolAction)} and return
* {@code true} if the passed in tool action is contained in {@link ToolActions#DEFAULT_SHIELD_ACTIONS} or is
* equals to {@link ToolActions#SHIELD_BLOCK}.
*/
@Deprecated(since = "1.17.1", forRemoval = true)
default boolean isShield(ItemStack stack, @Nullable LivingEntity entity)
{
return stack.getItem() == Items.SHIELD;
}
/**
* @return the fuel burn time for this itemStack in a furnace. Return 0 to make
* it not act as a fuel. Return -1 to let the default vanilla logic
@@ -206,20 +206,6 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
return self().getItem().canDisableShield(self(), shield, entity, attacker);
}
/**
* {@return {@code true} if this item is considered a shield}
*
* @param entity the entity holding the item stack
* @deprecated To be removed in 1.18. Call {@link #canPerformAction(ToolAction)} with
* {@link ToolActions#SHIELD_BLOCK} instead.
*/
@SuppressWarnings("removal")
@Deprecated(since = "1.17.1", forRemoval = true)
default boolean isShield(@Nullable LivingEntity entity)
{
return self().getItem().isShield(self(), entity);
}
/**
* Called when a entity tries to play the 'swing' animation.
*
@@ -23,9 +23,9 @@ import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.fmllegacy.network.IContainerFactory;
import net.minecraftforge.network.IContainerFactory;
public interface IForgeContainerType<T>
public interface IForgeMenuType<T>
{
static <T extends AbstractContainerMenu> MenuType<T> create(IContainerFactory<T> factory)
{
@@ -51,7 +51,7 @@ public interface IForgeMobEffect
* @param potionEffect the {@code PotionEffect} instance containing the potion
* @return a value used to sort {@code PotionEffect}s in GUIs
*/
default int getGuiSortColor(MobEffectInstance potionEffect) {
default int getSortOrder(MobEffectInstance potionEffect) {
return self().getColor();
}
}
Loaded 100 of 538 files, more files were not shown because too many files have changed in this diff. Show more