diff --git a/build.gradle b/build.gradle index 4f18588..b477c6e 100644 --- a/build.gradle +++ b/build.gradle @@ -16,8 +16,8 @@ subprojects { dependencies { minecraft "com.mojang:minecraft:${rootProject.minecraft_version}" - //mappings loom.officialMojangMappings() - mappings "net.fabricmc:yarn:${rootProject.yarn_mappings}:v2" + mappings loom.officialMojangMappings() + //mappings "net.fabricmc:yarn:${rootProject.yarn_mappings}:v2" } } diff --git a/common/src/main/java/com/xtracr/realcamera/KeyBindings.java b/common/src/main/java/com/xtracr/realcamera/KeyBindings.java index 9fe4970..0c8b915 100644 --- a/common/src/main/java/com/xtracr/realcamera/KeyBindings.java +++ b/common/src/main/java/com/xtracr/realcamera/KeyBindings.java @@ -3,8 +3,8 @@ import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.gui.ModelViewScreen; import com.xtracr.realcamera.util.LocUtil; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.option.KeyBinding; +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; import org.lwjgl.glfw.GLFW; import java.util.HashMap; @@ -12,7 +12,7 @@ import java.util.function.Consumer; public final class KeyBindings { - private static final Map> KEY_BINDINGS = new HashMap<>(); + private static final Map> KEY_BINDINGS = new HashMap<>(); static { createKeyBinding("modelViewScreen", client -> client.setScreen(new ModelViewScreen())); @@ -32,22 +32,22 @@ public final class KeyBindings { createKeyBinding("adjustRIGHT", client -> ConfigFile.config().adjustOffsetZ(-1)); } - private static void createKeyBinding(String id, Consumer whenPressed) { + private static void createKeyBinding(String id, Consumer whenPressed) { createKeyBinding(id, GLFW.GLFW_KEY_UNKNOWN, whenPressed); } - private static void createKeyBinding(String id, int code, Consumer whenPressed) { - KEY_BINDINGS.put(new KeyBinding("key." + RealCamera.FULL_ID + "." + id, code, LocUtil.KEY_MOD_NAME), whenPressed); + private static void createKeyBinding(String id, int code, Consumer whenPressed) { + KEY_BINDINGS.put(new KeyMapping("key." + RealCamera.FULL_ID + "." + id, code, LocUtil.KEY_MOD_NAME), whenPressed); } - public static void register(Consumer registerer) { + public static void register(Consumer registerer) { KEY_BINDINGS.keySet().forEach(registerer); } - public static void handle(MinecraftClient client) { + public static void handle(Minecraft client) { if (client.player == null) return; KEY_BINDINGS.forEach((keyBinding, whenPressed) -> { - while (keyBinding.wasPressed()) { + while (keyBinding.consumeClick()) { whenPressed.accept(client); ConfigFile.save(); } diff --git a/common/src/main/java/com/xtracr/realcamera/RealCameraCore.java b/common/src/main/java/com/xtracr/realcamera/RealCameraCore.java index 6a0bbf9..41085e0 100644 --- a/common/src/main/java/com/xtracr/realcamera/RealCameraCore.java +++ b/common/src/main/java/com/xtracr/realcamera/RealCameraCore.java @@ -1,30 +1,27 @@ package com.xtracr.realcamera; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; import com.xtracr.realcamera.compat.DisableHelper; import com.xtracr.realcamera.config.BindingTarget; import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.util.LocUtil; import com.xtracr.realcamera.util.MathUtil; import com.xtracr.realcamera.util.VertexRecorder; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.EntityRenderDispatcher; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.RotationAxis; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; -import java.util.Arrays; -import java.util.Objects; - public class RealCameraCore { private static final VertexRecorder recorder = new VertexRecorder(); public static BindingTarget currentTarget = new BindingTarget(); - private static Vec3d pos = Vec3d.ZERO, cameraPos = Vec3d.ZERO, offset = Vec3d.ZERO; + private static Vec3 pos = Vec3.ZERO, cameraPos = Vec3.ZERO, offset = Vec3.ZERO; private static boolean active = false, rendering = false, readyToSendMessage = true; private static float pitch, yaw, roll; @@ -44,21 +41,21 @@ public static float getRoll(float f) { return f; } - public static Vec3d getPos(Vec3d vec3d) { - return new Vec3d(currentTarget.bindX ? pos.getX() : vec3d.getX(), currentTarget.bindY ? pos.getY() : vec3d.getY(), currentTarget.bindZ ? pos.getZ() : vec3d.getZ()); + public static Vec3 getPos(Vec3 vec) { + return new Vec3(currentTarget.bindX ? pos.x() : vec.x(), currentTarget.bindY ? pos.y() : vec.y(), currentTarget.bindZ ? pos.z() : vec.z()); } - public static Vec3d getCameraPos(Vec3d vec3d) { - return new Vec3d(currentTarget.bindX ? cameraPos.getX() : vec3d.getX(), currentTarget.bindY ? cameraPos.getY() : vec3d.getY(), currentTarget.bindZ ? cameraPos.getZ() : vec3d.getZ()); + public static Vec3 getCameraPos(Vec3 vec) { + return new Vec3(currentTarget.bindX ? cameraPos.x() : vec.x(), currentTarget.bindY ? cameraPos.y() : vec.y(), currentTarget.bindZ ? cameraPos.z() : vec.z()); } - public static void setCameraPos(Vec3d vec3d) { - cameraPos = vec3d; + public static void setCameraPos(Vec3 vec) { + cameraPos = vec; } - public static void initialize(MinecraftClient client) { + public static void initialize(Minecraft client) { Entity entity = client.getCameraEntity(); - active = ConfigFile.config().enabled() && client.options.getPerspective().isFirstPerson() && client.gameRenderer.getCamera() != null && entity != null && !DisableHelper.isDisabled("mainFeature", entity); + active = ConfigFile.config().enabled() && client.options.getCameraType().isFirstPerson() && entity != null && !DisableHelper.isDisabled("mainFeature", entity); rendering = active && ConfigFile.config().renderModel() && !DisableHelper.isDisabled("renderModel", entity); } @@ -74,38 +71,44 @@ public static boolean isRendering() { return active && rendering; } - public static void updateModel(MinecraftClient client, float tickDelta) { + public static void updateModel(Minecraft client, float tickDelta) { recorder.clear(); // WorldRenderer.render Entity entity = client.getCameraEntity(); EntityRenderDispatcher dispatcher = client.getEntityRenderDispatcher(); - dispatcher.configure(client.world, client.gameRenderer.getCamera(), client.targetedEntity); - if (entity.age == 0) { - entity.lastRenderX = entity.getX(); - entity.lastRenderY = entity.getY(); - entity.lastRenderZ = entity.getZ(); + dispatcher.prepare(client.level, client.gameRenderer.getMainCamera(), client.crosshairPickEntity); + if (entity.tickCount == 0) { + entity.xOld = entity.getX(); + entity.yOld = entity.getY(); + entity.zOld = entity.getZ(); } // WorldRenderer.renderEntity - offset = new Vec3d(MathHelper.lerp(tickDelta, entity.lastRenderX, entity.getX()), MathHelper.lerp(tickDelta, entity.lastRenderY, entity.getY()), MathHelper.lerp(tickDelta, entity.lastRenderZ, entity.getZ())); - dispatcher.render(entity, 0, 0, 0, MathHelper.lerp(tickDelta, entity.prevYaw, entity.getYaw()), tickDelta, new MatrixStack(), recorder, dispatcher.getLight(entity, tickDelta)); + offset = new Vec3(Mth.lerp(tickDelta, entity.xOld, entity.getX()), Mth.lerp(tickDelta, entity.yOld, entity.getY()), Mth.lerp(tickDelta, entity.zOld, entity.getZ())); + dispatcher.render(entity, 0, 0, 0, Mth.lerp(tickDelta, entity.yRotO, entity.getYRot()), tickDelta, new PoseStack(), recorder, dispatcher.getPackedLightCoords(entity, tickDelta)); recorder.buildRecords(); } - public static void renderCameraEntity(VertexConsumerProvider vertexConsumers) { - Matrix3f normalMatrix = new Matrix3f().rotate(RotationAxis.POSITIVE_Z.rotationDegrees(roll)) - .rotate(RotationAxis.POSITIVE_X.rotationDegrees(pitch)) - .rotate(RotationAxis.POSITIVE_Y.rotationDegrees(yaw + 180.0f)) - .transpose().invert(); + public static void renderCameraEntity(MultiBufferSource bufferSource) { + Matrix3f normalMatrix = new Matrix3f().rotateZ((float) Math.toRadians(roll)).rotateX((float) Math.toRadians(pitch)).rotateY((float) Math.toRadians(yaw + 180.0f)).transpose().invert(); Matrix4f positionMatrix = new Matrix4f(normalMatrix).translate(offset.subtract(pos).toVector3f()); - recorder.drawByAnother(vertexConsumers, record -> currentTarget.disabledTextureIds.stream().noneMatch(record.textureId()::contains), record -> { + recorder.forEachRecord(record -> { + if (currentTarget.disabledTextureIds.stream().anyMatch(record.textureId()::contains)) return; + VertexConsumer buffer = bufferSource.getBuffer(record.renderType()); + if (!record.renderType().canConsolidateConsecutiveGeometry()) { + VertexRecorder.renderVertices(record.vertices(), buffer); + return; + } final double depth = currentTarget.disablingDepth; - final int primitiveLength = record.primitiveLength(); - return Arrays.stream(record.primitives()).map(primitive -> { + final int primitiveLength = record.renderType().mode().primitiveLength; + for (VertexRecorder.Vertex[] primitive : record.primitives()) { VertexRecorder.Vertex[] newPrimitive = new VertexRecorder.Vertex[primitiveLength]; for (int j = 0; j < primitiveLength ; j++) newPrimitive[j] = primitive[j].transform(positionMatrix, normalMatrix); - for (VertexRecorder.Vertex vertex : newPrimitive) if (vertex.z() < -depth) return newPrimitive; - return null; - }).filter(Objects::nonNull).toArray(VertexRecorder.Vertex[][]::new); + for (VertexRecorder.Vertex vertex : newPrimitive) { + if (vertex.z() > -depth) continue; + VertexRecorder.renderVertices(newPrimitive, buffer); + break; + } + } }); } @@ -115,21 +118,21 @@ public static void computeCamera() { for (BindingTarget target : ConfigFile.config().getTargetList()) { Vector3f position = new Vector3f(); if (recorder.getTargetPosAndRot(target, normal, position) == null || !(Math.abs(normal.determinant() - 1) <= 0.01f) || !Float.isFinite(position.lengthSquared())) continue; - pos = new Vec3d(position).add(offset); + pos = new Vec3(position).add(offset); currentTarget = target; break; } if (currentTarget.isEmpty()) { - Entity player = MinecraftClient.getInstance().player; - if (readyToSendMessage && player != null) player.sendMessage(LocUtil.MESSAGE("bindingFailed", LocUtil.MOD_NAME(), LocUtil.MODEL_VIEW_TITLE())); + Entity player = Minecraft.getInstance().player; + if (readyToSendMessage && player != null) player.sendSystemMessage(LocUtil.MESSAGE("bindingFailed", LocUtil.MOD_NAME(), LocUtil.MODEL_VIEW_TITLE())); active = readyToSendMessage = false; } else readyToSendMessage = true; normal.rotateLocal((float) Math.toRadians(currentTarget.getYaw()), normal.m10, normal.m11, normal.m12); normal.rotateLocal((float) Math.toRadians(currentTarget.getPitch()), normal.m00, normal.m01, normal.m02); normal.rotateLocal((float) Math.toRadians(currentTarget.getRoll()), normal.m20, normal.m21, normal.m22); - Vec3d eulerAngle = MathUtil.getEulerAngleYXZ(normal).multiply(Math.toDegrees(1)); - pitch = (float) eulerAngle.getX(); - yaw = (float) -eulerAngle.getY(); - roll = (float) eulerAngle.getZ(); + Vec3 eulerAngle = MathUtil.getEulerAngleYXZ(normal).scale(Math.toDegrees(1)); + pitch = (float) eulerAngle.x(); + yaw = (float) -eulerAngle.y(); + roll = (float) eulerAngle.z(); } } diff --git a/common/src/main/java/com/xtracr/realcamera/compat/DisableHelper.java b/common/src/main/java/com/xtracr/realcamera/compat/DisableHelper.java index 970a518..376408b 100644 --- a/common/src/main/java/com/xtracr/realcamera/compat/DisableHelper.java +++ b/common/src/main/java/com/xtracr/realcamera/compat/DisableHelper.java @@ -1,10 +1,10 @@ package com.xtracr.realcamera.compat; import com.xtracr.realcamera.config.ConfigFile; -import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.registry.Registries; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; import java.util.HashMap; import java.util.Map; @@ -15,9 +15,9 @@ public class DisableHelper { public static void initialize() { registerOr("mainFeature", LivingEntity::isSleeping); - registerOr("renderModel", entity -> entity instanceof PlayerEntity player && player.isUsingSpyglass()); - registerOr("renderModel", entity -> ConfigFile.config().getDisableRenderItems().contains(Registries.ITEM.getId(entity.getMainHandStack().getItem()).toString())); - registerOr("renderModel", entity -> ConfigFile.config().getDisableRenderItems().contains(Registries.ITEM.getId(entity.getOffHandStack().getItem()).toString())); + registerOr("renderModel", entity -> entity instanceof Player player && player.isScoping()); + registerOr("renderModel", entity -> ConfigFile.config().getDisableRenderItems().contains(BuiltInRegistries.ITEM.getKey(entity.getMainHandItem().getItem()).toString())); + registerOr("renderModel", entity -> ConfigFile.config().getDisableRenderItems().contains(BuiltInRegistries.ITEM.getKey(entity.getOffhandItem().getItem()).toString())); } public static void registerOr(String type, Predicate predicate) { diff --git a/common/src/main/java/com/xtracr/realcamera/config/BindingTarget.java b/common/src/main/java/com/xtracr/realcamera/config/BindingTarget.java index 884c6c6..633886e 100644 --- a/common/src/main/java/com/xtracr/realcamera/config/BindingTarget.java +++ b/common/src/main/java/com/xtracr/realcamera/config/BindingTarget.java @@ -1,6 +1,6 @@ package com.xtracr.realcamera.config; -import net.minecraft.util.math.MathHelper; +import net.minecraft.util.Mth; import java.util.List; @@ -45,7 +45,7 @@ public double getOffsetX() { } public void setOffsetX(double offsetX) { - this.offsetX = MathHelper.clamp(offsetX, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); + this.offsetX = Mth.clamp(offsetX, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); } public double getOffsetY() { @@ -53,7 +53,7 @@ public double getOffsetY() { } public void setOffsetY(double offsetY) { - this.offsetY = MathHelper.clamp(offsetY, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); + this.offsetY = Mth.clamp(offsetY, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); } public double getOffsetZ() { @@ -61,7 +61,7 @@ public double getOffsetZ() { } public void setOffsetZ(double offsetZ) { - this.offsetZ = MathHelper.clamp(offsetZ, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); + this.offsetZ = Mth.clamp(offsetZ, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); } public float getPitch() { @@ -69,7 +69,7 @@ public float getPitch() { } public void setPitch(float pitch) { - this.pitch = MathHelper.wrapDegrees(pitch); + this.pitch = Mth.wrapDegrees(pitch); } public float getYaw() { @@ -77,7 +77,7 @@ public float getYaw() { } public void setYaw(float yaw) { - this.yaw = MathHelper.wrapDegrees(yaw); + this.yaw = Mth.wrapDegrees(yaw); } public float getRoll() { @@ -85,7 +85,7 @@ public float getRoll() { } public void setRoll(float roll) { - this.roll = MathHelper.wrapDegrees(roll); + this.roll = Mth.wrapDegrees(roll); } public BindingTarget priority(int priority) { diff --git a/common/src/main/java/com/xtracr/realcamera/config/ConfigFile.java b/common/src/main/java/com/xtracr/realcamera/config/ConfigFile.java index f3ee396..eefa33e 100644 --- a/common/src/main/java/com/xtracr/realcamera/config/ConfigFile.java +++ b/common/src/main/java/com/xtracr/realcamera/config/ConfigFile.java @@ -3,7 +3,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.xtracr.realcamera.RealCamera; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -18,7 +18,7 @@ public class ConfigFile { private static final Path PATH; static { - File configDir = new File(MinecraftClient.getInstance().runDirectory, "config"); + File configDir = new File(Minecraft.getInstance().gameDirectory, "config"); if (!configDir.exists()) configDir.mkdirs(); PATH = configDir.toPath().resolve(FILE_NAME); } diff --git a/common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java b/common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java index f2d083e..076cb2b 100644 --- a/common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java +++ b/common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java @@ -5,8 +5,8 @@ import me.shedaniel.clothconfig2.api.ConfigCategory; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; import me.shedaniel.clothconfig2.impl.builders.SubCategoryBuilder; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.util.Formatting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.screens.Screen; public class ConfigScreen { public static Screen create(Screen parent) { @@ -120,7 +120,7 @@ public static Screen create(Screen parent) { classic.addEntry(classicCameraRotation.build()); binding.addEntry(entryBuilder.startTextDescription(LocUtil.CONFIG_OPTION("toModelViewScreen", - LocUtil.MODEL_VIEW_TITLE().styled(s -> s.withColor(Formatting.BLUE)))) + LocUtil.MODEL_VIEW_TITLE().withStyle(s -> s.withColor(ChatFormatting.BLUE)))) .build()); binding.addEntry(entryBuilder.startBooleanToggle(LocUtil.CONFIG_OPTION("adjustOffset"), config.binding.adjustOffset) .setDefaultValue(true) diff --git a/common/src/main/java/com/xtracr/realcamera/config/ModConfig.java b/common/src/main/java/com/xtracr/realcamera/config/ModConfig.java index 088ef6f..6a21e55 100644 --- a/common/src/main/java/com/xtracr/realcamera/config/ModConfig.java +++ b/common/src/main/java/com/xtracr/realcamera/config/ModConfig.java @@ -1,7 +1,7 @@ package com.xtracr.realcamera.config; import com.xtracr.realcamera.RealCameraCore; -import net.minecraft.util.math.MathHelper; +import net.minecraft.util.Mth; import java.util.ArrayList; import java.util.Comparator; @@ -30,7 +30,7 @@ public void set(ModConfig modConfig) { } public void clamp() { - adjustStep = MathHelper.clamp(adjustStep, 0.0d, MAX_DOUBLE); + adjustStep = Mth.clamp(adjustStep, 0.0d, MAX_DOUBLE); classic.clamp(); binding.clamp(); } @@ -187,16 +187,16 @@ public static class Classic { private void clamp() { if (adjustMode == null) adjustMode = AdjustMode.CAMERA; - scale = MathHelper.clamp(scale, 0.0, 64.0); - cameraX = MathHelper.clamp(cameraX, MIN_DOUBLE, MAX_DOUBLE); - cameraY = MathHelper.clamp(cameraY, MIN_DOUBLE, MAX_DOUBLE); - cameraZ = MathHelper.clamp(cameraZ, MIN_DOUBLE, MAX_DOUBLE); - centerX = MathHelper.clamp(centerX, MIN_DOUBLE, MAX_DOUBLE); - centerY = MathHelper.clamp(centerY, MIN_DOUBLE, MAX_DOUBLE); - centerZ = MathHelper.clamp(centerZ, MIN_DOUBLE, MAX_DOUBLE); - pitch = MathHelper.wrapDegrees(pitch); - yaw = MathHelper.wrapDegrees(yaw); - roll = MathHelper.wrapDegrees(roll); + scale = Mth.clamp(scale, 0.0, 64.0); + cameraX = Mth.clamp(cameraX, MIN_DOUBLE, MAX_DOUBLE); + cameraY = Mth.clamp(cameraY, MIN_DOUBLE, MAX_DOUBLE); + cameraZ = Mth.clamp(cameraZ, MIN_DOUBLE, MAX_DOUBLE); + centerX = Mth.clamp(centerX, MIN_DOUBLE, MAX_DOUBLE); + centerY = Mth.clamp(centerY, MIN_DOUBLE, MAX_DOUBLE); + centerZ = Mth.clamp(centerZ, MIN_DOUBLE, MAX_DOUBLE); + pitch = Mth.wrapDegrees(pitch); + yaw = Mth.wrapDegrees(yaw); + roll = Mth.wrapDegrees(roll); } public enum AdjustMode { @@ -214,11 +214,11 @@ public static class Binding { protected static final List defaultDisableRenderItems = List.of("minecraft:filled_map"); public boolean adjustOffset = true; public boolean renderStuckObjects = true; - public List disableRenderItems = new ArrayList<>(defaultDisableRenderItems); + public List disableRenderItems = defaultDisableRenderItems; public List targetList = new ArrayList<>(BindingTarget.defaultTargets); private void clamp() { - if (disableRenderItems == null) disableRenderItems = new ArrayList<>(); + if (disableRenderItems == null) disableRenderItems = List.of(); if (targetList == null || targetList.isEmpty()) targetList = new ArrayList<>(BindingTarget.defaultTargets); } } diff --git a/common/src/main/java/com/xtracr/realcamera/gui/CyclingTexturedButton.java b/common/src/main/java/com/xtracr/realcamera/gui/CyclingTexturedButton.java index 0b4aeb9..42dce5f 100644 --- a/common/src/main/java/com/xtracr/realcamera/gui/CyclingTexturedButton.java +++ b/common/src/main/java/com/xtracr/realcamera/gui/CyclingTexturedButton.java @@ -1,14 +1,14 @@ package com.xtracr.realcamera.gui; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; -import net.minecraft.client.gui.widget.PressableWidget; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; - -public class CyclingTexturedButton extends PressableWidget { - protected final Identifier texture; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.AbstractButton; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +public class CyclingTexturedButton extends AbstractButton { + protected final ResourceLocation texture; protected final int textureWidth, textureHeight, u, v, vOffset, size; private int value; @@ -20,8 +20,8 @@ public CyclingTexturedButton(int x, int y, int width, int height, int u, int v, this(x, y, width, height, u, v, height, value, size, TexturedButton.ICON_TEXTURE, 256, 256); } - public CyclingTexturedButton(int x, int y, int width, int height, int u, int v, int vOffset, int value, int size, Identifier texture, int textureWidth, int textureHeight) { - super(x, y, width, height, Text.empty()); + public CyclingTexturedButton(int x, int y, int width, int height, int u, int v, int vOffset, int value, int size, ResourceLocation texture, int textureWidth, int textureHeight) { + super(x, y, width, height, Component.empty()); this.u = u; this.v = v; this.vOffset = vOffset; @@ -47,14 +47,14 @@ public void onPress() { } @Override - public void renderButton(DrawContext context, int mouseX, int mouseY, float delta) { - context.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0xFF646464); - context.drawTexture(texture, getX(), getY(), u, v + value * vOffset, width, height, textureWidth, textureHeight); - if (isSelected()) context.drawBorder(getX(), getY(), getWidth(), getHeight(), 0xFFFFFFFF); + public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0xFF646464); + graphics.blit(texture, getX(), getY(), u, v + value * vOffset, width, height, textureWidth, textureHeight); + if (isHoveredOrFocused()) graphics.renderOutline(getX(), getY(), getWidth(), getHeight(), 0xFFFFFFFF); } @Override - protected void appendClickableNarrations(NarrationMessageBuilder builder) { - appendDefaultNarrations(builder); + protected void updateWidgetNarration(NarrationElementOutput builder) { + defaultButtonNarrationText(builder); } } diff --git a/common/src/main/java/com/xtracr/realcamera/gui/DoubleSlider.java b/common/src/main/java/com/xtracr/realcamera/gui/DoubleSlider.java new file mode 100644 index 0000000..7089fcb --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/gui/DoubleSlider.java @@ -0,0 +1,38 @@ +package com.xtracr.realcamera.gui; + +import net.minecraft.client.gui.components.AbstractSliderButton; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; + +import java.util.function.Function; + +public class DoubleSlider extends AbstractSliderButton { + private final Function textFactory; + private final double min, max; + + public DoubleSlider(int width, int height, double value, double min, double max, Function textFactory) { + super(0, 0, width, height, textFactory.apply(value), Mth.clamp(0, (value - min) / (max - min), 1)); + this.textFactory = textFactory; + this.min = min; + this.max = max; + } + + public double getValue() { + return min + (max - min) * value; + } + + public void setValue(double value) { + this.value = Mth.clamp(0, (value - min) / (max - min), 1); + applyValue(); + } + + @Override + protected void updateMessage() { + setMessage(textFactory.apply(getValue())); + } + + @Override + protected void applyValue() { + updateMessage(); + } +} diff --git a/common/src/main/java/com/xtracr/realcamera/gui/DoubleSliderWidget.java b/common/src/main/java/com/xtracr/realcamera/gui/DoubleSliderWidget.java deleted file mode 100644 index 866a418..0000000 --- a/common/src/main/java/com/xtracr/realcamera/gui/DoubleSliderWidget.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xtracr.realcamera.gui; - -import net.minecraft.client.gui.widget.SliderWidget; -import net.minecraft.text.Text; -import net.minecraft.util.math.MathHelper; - -import java.util.function.Function; - -public class DoubleSliderWidget extends SliderWidget { - private final Function textFactory; - private final double min, max; - - public DoubleSliderWidget(int width, int height, double value, double min, double max, Function textFactory) { - super(0, 0, width, height, textFactory.apply(value), MathHelper.clamp(0, (value - min) / (max - min), 1)); - this.textFactory = textFactory; - this.min = min; - this.max = max; - } - - public double getValue() { - return min + (max - min) * value; - } - - public void setValue(double value) { - this.value = MathHelper.clamp(0, (value - min) / (max - min), 1); - applyValue(); - } - - @Override - protected void updateMessage() { - setMessage(textFactory.apply(getValue())); - } - - @Override - protected void applyValue() { - updateMessage(); - } -} diff --git a/common/src/main/java/com/xtracr/realcamera/gui/ModelAnalyser.java b/common/src/main/java/com/xtracr/realcamera/gui/ModelAnalyser.java index 93a6fe7..3edc524 100644 --- a/common/src/main/java/com/xtracr/realcamera/gui/ModelAnalyser.java +++ b/common/src/main/java/com/xtracr/realcamera/gui/ModelAnalyser.java @@ -1,12 +1,12 @@ package com.xtracr.realcamera.gui; +import com.mojang.blaze3d.vertex.VertexConsumer; import com.xtracr.realcamera.config.BindingTarget; import com.xtracr.realcamera.util.VertexRecorder; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.render.RenderLayer; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.util.math.Vec2f; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import org.joml.Matrix3f; import org.joml.Vector3f; @@ -18,7 +18,7 @@ import java.util.Set; public class ModelAnalyser extends VertexRecorder { - private static final Set unfocusableLayers = Set.of(RenderLayer.getArmorGlint(), RenderLayer.getArmorEntityGlint(), RenderLayer.getGlintTranslucent(), RenderLayer.getGlint(), RenderLayer.getDirectGlint(), RenderLayer.getEntityGlint(), RenderLayer.getDirectEntityGlint()); + private static final Set UNFOCUSABLE_RENDER_TYPES = Set.of(RenderType.armorEntityGlint(), RenderType.glintTranslucent(), RenderType.glint(), RenderType.entityGlint(), RenderType.entityGlintDirect()); private static final int primitiveArgb = 0x6F3333CC, forwardArgb = 0xFF00CC00, upwardArgb = 0xFFCC0000, leftArgb = 0xFF0000CC; private static final int focusedArgb = 0x7FFFFFFF, sideArgb = 0x3FFFFFFF; private final BindingTarget target; @@ -34,26 +34,26 @@ public ModelAnalyser(BindingTarget target) { private static boolean intersects(Vertex[] p1, List primitives) { final float precision = 1.0E-05f; - for (Vertex[] p2 : primitives) for (Vertex v1 : p1) for (Vertex v2 : p2) if (v1.pos().squaredDistanceTo(v2.pos()) < precision) return true; + for (Vertex[] p2 : primitives) for (Vertex v1 : p1) for (Vertex v2 : p2) if (v1.pos().distanceToSqr(v2.pos()) < precision) return true; return false; } - private static void drawPrimitive(DrawContext context, Vertex[] primitive, int argb, int offset) { - VertexConsumer vertexConsumer = context.getVertexConsumers().getBuffer(RenderLayer.getGui()); - for (Vertex vertex : primitive) vertexConsumer.vertex(vertex.x(), vertex.y(), vertex.z() + offset).color(argb).next(); - if (primitive.length == 3) vertexConsumer.vertex(primitive[2].x(), primitive[2].y(), primitive[2].z() + offset).color(argb).next(); - context.draw(); + private static void drawPrimitive(GuiGraphics graphics, Vertex[] primitive, int argb, int offset) { + VertexConsumer buffer = graphics.bufferSource().getBuffer(RenderType.gui()); + for (Vertex vertex : primitive) buffer.vertex(vertex.x(), vertex.y(), vertex.z() + offset).color(argb).endVertex(); + if (primitive.length == 3) buffer.vertex(primitive[2].x(), primitive[2].y(), primitive[2].z() + offset).color(argb).endVertex(); + graphics.flush(); } - private static void drawNormal(DrawContext context, Vec3d start, Vec3d normal, int length, int argb) { - Vec3d end = normal.multiply(length).add(start); - VertexConsumer vertexConsumer = context.getVertexConsumers().getBuffer(RenderLayer.getLineStrip()); - vertexConsumer.vertex(start.getX(), start.getY(), start.getZ() + 1200f).color(argb).normal((float) normal.getX(), (float) normal.getY(), (float) normal.getZ()).next(); - vertexConsumer.vertex(end.getX(), end.getY(), end.getZ() + 1200f).color(argb).normal((float) normal.getX(), (float) normal.getY(), (float) normal.getZ()).next(); - context.draw(); + private static void drawNormal(GuiGraphics graphics, Vec3 start, Vec3 normal, int length, int argb) { + Vec3 end = normal.scale(length).add(start); + VertexConsumer buffer = graphics.bufferSource().getBuffer(RenderType.lineStrip()); + buffer.vertex((float) start.x(), (float) start.y(), (float) (start.z() + 1200f)).color(argb).normal((float) normal.x(), (float) normal.y(), (float) normal.z()).endVertex(); + buffer.vertex((float) end.x(), (float) end.y(), (float) (end.z() + 1200f)).color(argb).normal((float) normal.x(), (float) normal.y(), (float) normal.z()).endVertex(); + graphics.flush(); } - public void initialize(int entitySize, int mouseX, int mouseY, int layers, boolean hideDisabled, String idInField) { + public void analyse(int entitySize, int mouseX, int mouseY, int layers, boolean hideDisabled, String idInField) { buildRecords(); List removedRecords = records.stream().filter(record -> { boolean isIdInField = !idInField.isBlank() && record.textureId().contains(idInField); @@ -61,7 +61,7 @@ public void initialize(int entitySize, int mouseX, int mouseY, int layers, boole }).toList(); records.removeAll(removedRecords); List sortByDepth = new ArrayList<>(); - records.stream().filter(record -> !unfocusableLayers.contains(record.renderLayer())).forEach(record -> { + records.stream().filter(record -> !UNFOCUSABLE_RENDER_TYPES.contains(record.renderType())).forEach(record -> { Vertex[][] primitives = record.primitives(); for (int i = 0, primitiveCount = primitives.length; i < primitiveCount; i++) { Polygon polygon = new Polygon(); @@ -69,9 +69,8 @@ public void initialize(int entitySize, int mouseX, int mouseY, int layers, boole for (Vertex vertex : primitive) polygon.addPoint((int) vertex.x(), (int) vertex.y()); if (!polygon.contains(mouseX, mouseY)) continue; Vertex point = primitive[0]; - double deltaZ = 0; - if (point.normalZ() != 0) deltaZ = (point.normalX() * (mouseX - point.x()) + point.normalY() * (mouseY - point.y())) / point.normalZ(); - sortByDepth.add(new Triple(point.z() + deltaZ, record, i)); + double deltaZ = point.normalZ() == 0 ? 0 : (point.normalX() * (mouseX - point.x()) + point.normalY() * (mouseY - point.y())) / point.normalZ(); + sortByDepth.add(new Triple(point.z() - deltaZ, record, i)); } }); if (!sortByDepth.isEmpty()) { @@ -94,7 +93,7 @@ public String focusedTextureId() { return focusedRecord.textureId(); } - public Vec2f getFocusedUV() { + public Vec2 getFocusedUV() { if (focusedIndex == -1 || focusedRecord == null) return null; float u = 0, v = 0; Vertex[] primitive = focusedRecord.primitives()[focusedIndex]; @@ -102,43 +101,39 @@ public Vec2f getFocusedUV() { u += vertex.u(); v += vertex.v(); } - return new Vec2f(u / primitive.length, v / primitive.length); + return new Vec2(u / primitive.length, v / primitive.length); } - public void previewEffect(DrawContext context, int entitySize, boolean canSelect) { - drawByAnother(context.getVertexConsumers(), record -> true, BuiltRecord::primitives); - context.draw(); - if (canSelect) drawFocused(context); + public void previewEffect(GuiGraphics graphics, int entitySize, boolean canSelect) { + if (canSelect) drawFocused(graphics); if (normal.m00() == 0 && normal.m11() == 0 && normal.m22() == 0) return; - Vec3d start = new Vec3d(position); - drawNormal(context, start, new Vec3d(normal.m20(), normal.m21(), -normal.m22()), entitySize / 3, forwardArgb); - drawNormal(context, start, new Vec3d(normal.m10(), normal.m11(), -normal.m12()), entitySize / 6, upwardArgb); - drawNormal(context, start, new Vec3d(normal.m00(), normal.m01(), -normal.m02()), entitySize / 6, leftArgb); + Vec3 start = new Vec3(position); + drawNormal(graphics, start, new Vec3(normal.m20(), normal.m21(), -normal.m22()), entitySize / 3, forwardArgb); + drawNormal(graphics, start, new Vec3(normal.m10(), normal.m11(), -normal.m12()), entitySize / 6, upwardArgb); + drawNormal(graphics, start, new Vec3(normal.m00(), normal.m01(), -normal.m02()), entitySize / 6, leftArgb); } - public void drawModelWithNormals(DrawContext context, int entitySize) { - drawByAnother(context.getVertexConsumers(), record -> true, BuiltRecord::primitives); - context.draw(); - drawPolyhedron(context); - drawFocused(context); + public void drawNormals(GuiGraphics graphics, int entitySize) { + drawPolyhedron(graphics); + drawFocused(graphics); if (currentRecord == null) return; Vertex[] primitive; - if ((primitive = getPrimitive(currentRecord, target.posU, target.posV)) != null) drawPrimitive(context, primitive, primitiveArgb, 1000); - if ((primitive = getPrimitive(currentRecord, target.forwardU, target.forwardV)) != null) drawNormal(context, getPos(primitive, target.forwardU, target.forwardV), primitive[0].normal(), entitySize / 2, forwardArgb); - if ((primitive = getPrimitive(currentRecord, target.upwardU, target.upwardV)) != null) drawNormal(context, getPos(primitive, target.upwardU, target.upwardV), primitive[0].normal(), entitySize / 2, upwardArgb); + if ((primitive = getPrimitive(currentRecord, target.posU, target.posV)) != null) drawPrimitive(graphics, primitive, primitiveArgb, 1000); + if ((primitive = getPrimitive(currentRecord, target.forwardU, target.forwardV)) != null) drawNormal(graphics, getPos(primitive, target.forwardU, target.forwardV), primitive[0].normal(), entitySize / 2, forwardArgb); + if ((primitive = getPrimitive(currentRecord, target.upwardU, target.upwardV)) != null) drawNormal(graphics, getPos(primitive, target.upwardU, target.upwardV), primitive[0].normal(), entitySize / 2, upwardArgb); } - private void drawFocused(DrawContext context) { + private void drawFocused(GuiGraphics graphics) { if (focusedIndex == -1 || focusedRecord == null) return; Vertex[] focused = focusedRecord.primitives()[focusedIndex]; - drawPrimitive(context, focused, focusedArgb, 1100); + drawPrimitive(graphics, focused, focusedArgb, 1100); int length = focused.length; Vertex[] reversed = new Vertex[length]; for (int i = 0; i < length; i++) reversed[i] = focused[length - 1 - i]; - drawPrimitive(context, reversed, focusedArgb, 1100); + drawPrimitive(graphics, reversed, focusedArgb, 1100); } - private void drawPolyhedron(DrawContext context) { + private void drawPolyhedron(GuiGraphics graphics) { if (focusedIndex == -1 || focusedRecord == null) return; List polyhedron = new ArrayList<>(); polyhedron.add(focusedRecord.primitives()[focusedIndex]); @@ -165,7 +160,7 @@ private void drawPolyhedron(DrawContext context) { if (!indexes.contains(i)) break; resultIndexes.add(i); } - resultIndexes.forEach(i -> drawPrimitive(context, primitives[i], sideArgb, 1000)); + resultIndexes.forEach(i -> drawPrimitive(graphics, primitives[i], sideArgb, 1000)); } record Triple(double depth, BuiltRecord record, int index) {} diff --git a/common/src/main/java/com/xtracr/realcamera/gui/ModelViewScreen.java b/common/src/main/java/com/xtracr/realcamera/gui/ModelViewScreen.java index 0e2af5b..de4722b 100644 --- a/common/src/main/java/com/xtracr/realcamera/gui/ModelViewScreen.java +++ b/common/src/main/java/com/xtracr/realcamera/gui/ModelViewScreen.java @@ -1,24 +1,26 @@ package com.xtracr.realcamera.gui; +import com.mojang.blaze3d.platform.InputConstants; +import com.mojang.blaze3d.platform.Lighting; import com.xtracr.realcamera.RealCameraCore; import com.xtracr.realcamera.config.BindingTarget; import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.config.ModConfig; import com.xtracr.realcamera.util.LocUtil; import com.xtracr.realcamera.util.MathUtil; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.tooltip.Tooltip; -import net.minecraft.client.gui.widget.*; -import net.minecraft.client.render.DiffuseLighting; -import net.minecraft.client.render.entity.EntityRenderDispatcher; -import net.minecraft.client.util.InputUtil; -import net.minecraft.entity.LivingEntity; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec2f; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.*; +import net.minecraft.client.gui.layouts.FrameLayout; +import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.layouts.LayoutSettings; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.phys.Vec2; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.joml.Quaternionf; @@ -37,16 +39,16 @@ public class ModelViewScreen extends Screen { private double entityX, entityY; private float xRot, yRot; private String focusedTextureId; - private Vec2f focusedUV; - private TextFieldWidget textureIdField, nameField, disabledIdField; - private NumberFieldWidget forwardUField, forwardVField, upwardUField, upwardVField, posUField, posVField, scaleField, depthField; - private NumberFieldWidget priorityField; + private Vec2 focusedUV; + private EditBox textureIdField, nameField, disabledIdField; + private NumberField forwardUField, forwardVField, upwardUField, upwardVField, posUField, posVField, scaleField, depthField; + private NumberField priorityField; private List idsInClipBoard = new ArrayList<>(); private final List disabledIds = new ArrayList<>(); - private final CyclingButtonWidget selectingButton = createCyclingButton(Map.of( - 0, LocUtil.MODEL_VIEW_WIDGET("forwardMode").styled(s -> s.withColor(Formatting.GREEN)), - 1, LocUtil.MODEL_VIEW_WIDGET("upwardMode").styled(s -> s.withColor(Formatting.RED)), - 2, LocUtil.MODEL_VIEW_WIDGET("posMode").styled(s -> s.withColor(Formatting.BLUE))), + private final CycleButton selectingButton = createCyclingButton(Map.of( + 0, LocUtil.MODEL_VIEW_WIDGET("forwardMode").withStyle(s -> s.withColor(ChatFormatting.GREEN)), + 1, LocUtil.MODEL_VIEW_WIDGET("upwardMode").withStyle(s -> s.withColor(ChatFormatting.RED)), + 2, LocUtil.MODEL_VIEW_WIDGET("posMode").withStyle(s -> s.withColor(ChatFormatting.BLUE))), widgetWidth * 2 + 4, LocUtil.MODEL_VIEW_WIDGET("selectMode")); private final CyclingTexturedButton pauseButton = new CyclingTexturedButton(0, 16, 0, 2); private final CyclingTexturedButton bindXButton = new CyclingTexturedButton(16, 16, 1, 2); @@ -54,14 +56,14 @@ public class ModelViewScreen extends Screen { private final CyclingTexturedButton bindZButton = new CyclingTexturedButton(16, 16, 1, 2); private final CyclingTexturedButton bindRotButton = new CyclingTexturedButton(16, 16, 1, 2); private final CyclingTexturedButton showDisabled = new CyclingTexturedButton(32, 16, 0, 2); - private final DoubleSliderWidget entityPitchSlider = createSlider("pitch", widgetWidth * 2 + 4, -90.0, 90.0); - private final DoubleSliderWidget entityYawSlider = createSlider("yaw", widgetWidth * 2 + 4, -60.0, 60.0); - private final DoubleSliderWidget offsetXSlider = createSlider("offsetX", widgetWidth * 2 - 18, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); - private final DoubleSliderWidget offsetYSlider = createSlider("offsetY", widgetWidth * 2 - 18, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); - private final DoubleSliderWidget offsetZSlider = createSlider("offsetZ", widgetWidth * 2 - 18, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); - private final DoubleSliderWidget pitchSlider = createSlider("pitch", widgetWidth * 2 - 18, -180.0, 180.0); - private final DoubleSliderWidget yawSlider = createSlider("yaw", widgetWidth * 2 - 18, -180.0, 180.0); - private final DoubleSliderWidget rollSlider = createSlider("roll", widgetWidth * 2 - 18, -180.0, 180.0); + private final DoubleSlider entityPitchSlider = createSlider("pitch", widgetWidth * 2 + 4, -90.0, 90.0); + private final DoubleSlider entityYawSlider = createSlider("yaw", widgetWidth * 2 + 4, -60.0, 60.0); + private final DoubleSlider offsetXSlider = createSlider("offsetX", widgetWidth * 2 - 18, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); + private final DoubleSlider offsetYSlider = createSlider("offsetY", widgetWidth * 2 - 18, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); + private final DoubleSlider offsetZSlider = createSlider("offsetZ", widgetWidth * 2 - 18, ModConfig.MIN_DOUBLE, ModConfig.MAX_DOUBLE); + private final DoubleSlider pitchSlider = createSlider("pitch", widgetWidth * 2 - 18, -180.0, 180.0); + private final DoubleSlider yawSlider = createSlider("yaw", widgetWidth * 2 - 18, -180.0, 180.0); + private final DoubleSlider rollSlider = createSlider("roll", widgetWidth * 2 - 18, -180.0, 180.0); public ModelViewScreen() { super(LocUtil.MODEL_VIEW_TITLE()); @@ -80,10 +82,10 @@ protected void init() { private void initWidgets(int category, int page) { this.category = category; this.page = page; - clearChildren(); + clearWidgets(); initLeftWidgets(category); - addDrawableChild(pauseButton).setPosition(x + (xSize - ySize) / 2 + 4, y + 4); - addDrawableChild(new TexturedButton(x + (xSize - ySize) / 2 + 22, y + 4, 16, 16, 0, 0, button -> { + addRenderableWidget(pauseButton).setPosition(x + (xSize - ySize) / 2 + 4, y + 4); + addRenderableWidget(new TexturedButton(x + (xSize - ySize) / 2 + 22, y + 4, 16, 16, 0, 0, button -> { entitySize = 80; entityYawSlider.setValue(0); entityPitchSlider.setValue(0); @@ -101,74 +103,74 @@ private void initLeftWidgets(final int category) { upwardVField = createFloatField(widgetWidth, 0, upwardVField); posUField = createFloatField(widgetWidth, 0, posUField); posVField = createFloatField(widgetWidth, 0, posVField); - String textureId = textureIdField != null ? textureIdField.getText() : ""; + String textureId = textureIdField != null ? textureIdField.getValue() : ""; textureIdField = createTextField(widgetWidth * 2 + 4, null); textureIdField.setMaxLength(1024); - textureIdField.setText(textureId); + textureIdField.setValue(textureId); scaleField = createFloatField(widgetWidth, 1.0f, scaleField).setMax(64.0f); depthField = createFloatField(widgetWidth, 0.2f, depthField).setMax(16.0f); - GridWidget gridWidget = new GridWidget(); - gridWidget.getMainPositioner().margin(4, 2, 0, 0); - Positioner smallPositioner = gridWidget.copyPositioner().margin(5, 3, 1, 1); - GridWidget.Adder adder = gridWidget.createAdder(2); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("settings"), widgetWidth, button -> initWidgets(0, page))); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("preview"), widgetWidth, button -> initWidgets(category | 0b01, page))); + GridLayout grid = new GridLayout(); + grid.defaultCellSetting().padding(4, 2, 0, 0); + LayoutSettings smallSettings = grid.newCellSettings().padding(5, 3, 1, 1); + GridLayout.RowHelper rows = grid.createRowHelper(2); + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("settings"), widgetWidth, button -> initWidgets(0, page))); + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("preview"), widgetWidth, button -> initWidgets(category | 0b01, page))); if ((category & 0b1) == 0) { - adder.add(entityPitchSlider, 2); - adder.add(entityYawSlider, 2); - adder.add(selectingButton, 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("selectMode")); - adder.add(forwardUField, 1, smallPositioner); - adder.add(forwardVField, 1, smallPositioner); - adder.add(upwardUField, 1, smallPositioner); - adder.add(upwardVField, 1, smallPositioner); - adder.add(posUField, 1, smallPositioner); - adder.add(posVField, 1, smallPositioner); - adder.add(textureIdField, 2, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("textureId")); + rows.addChild(entityPitchSlider, 2); + rows.addChild(entityYawSlider, 2); + rows.addChild(selectingButton, 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("selectMode")); + rows.addChild(forwardUField, 1, smallSettings); + rows.addChild(forwardVField, 1, smallSettings); + rows.addChild(upwardUField, 1, smallSettings); + rows.addChild(upwardVField, 1, smallSettings); + rows.addChild(posUField, 1, smallSettings); + rows.addChild(posVField, 1, smallSettings); + rows.addChild(textureIdField, 2, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("textureId")); } else { - Positioner sliderPositioner = gridWidget.copyPositioner().margin(-20, 2, 0, 0); - adder.add(bindXButton, 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); - adder.add(offsetXSlider, 1, sliderPositioner); - adder.add(bindYButton, 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); - adder.add(offsetYSlider, 1, sliderPositioner); - adder.add(bindZButton, 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); - adder.add(offsetZSlider, 1, sliderPositioner); - adder.add(bindRotButton, 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); - adder.add(pitchSlider, 1, sliderPositioner); - adder.add(yawSlider, 2, gridWidget.copyPositioner().margin(26, 2, 0, 0)); - adder.add(new TexturedButton(0, 0, button -> { + LayoutSettings sliderSettings = grid.newCellSettings().padding(-20, 2, 0, 0); + rows.addChild(bindXButton, 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); + rows.addChild(offsetXSlider, 1, sliderSettings); + rows.addChild(bindYButton, 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); + rows.addChild(offsetYSlider, 1, sliderSettings); + rows.addChild(bindZButton, 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); + rows.addChild(offsetZSlider, 1, sliderSettings); + rows.addChild(bindRotButton, 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("bindButtons")); + rows.addChild(pitchSlider, 1, sliderSettings); + rows.addChild(yawSlider, 2, grid.newCellSettings().padding(26, 2, 0, 0)); + rows.addChild(new TexturedButton(0, 0, button -> { offsetXSlider.setValue(0); offsetYSlider.setValue(0); offsetZSlider.setValue(0); pitchSlider.setValue(0); yawSlider.setValue(0); rollSlider.setValue(0); - }), 1, smallPositioner); - adder.add(rollSlider, 1, sliderPositioner); - adder.add(scaleField, 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("scale")); - adder.add(depthField, 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("depth")); + }), 1, smallSettings); + rows.addChild(rollSlider, 1, sliderSettings); + rows.addChild(scaleField, 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("scale")); + rows.addChild(depthField, 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("depth")); } - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("save"), widgetWidth, button -> { + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("save"), widgetWidth, button -> { ConfigFile.config().putTarget(generateBindingTarget()); ConfigFile.save(); initWidgets(category, page); })); - adder.add(priorityField = NumberFieldWidget.ofInt(textRenderer, widgetWidth - 2, widgetHeight - 2, 0, priorityField), 1, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("priority")); - adder.add(nameField = createTextField(widgetWidth * 2 + 4, nameField), 2, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("targetName")); + rows.addChild(priorityField = NumberField.ofInt(font, widgetWidth - 2, widgetHeight - 2, 0, priorityField), 1, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("priority")); + rows.addChild(nameField = createTextField(widgetWidth * 2 + 4, nameField), 2, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("targetName")); nameField.setMaxLength(20); - gridWidget.refreshPositions(); - SimplePositioningWidget.setPos(gridWidget, x, y + 2, x + (xSize - ySize) / 2 - 4, y + ySize, 0, 0); - gridWidget.forEachChild(this::addDrawableChild); + grid.arrangeElements(); + FrameLayout.alignInRectangle(grid, x, y + 2, x + (xSize - ySize) / 2 - 4, y + ySize, 0, 0); + grid.visitWidgets(this::addRenderableWidget); } private void initRightWidgets(final int category, final int page) { disabledIdField = createTextField(widgetWidth * 2 + 4, disabledIdField); disabledIdField.setMaxLength(1024); - GridWidget gridWidget = new GridWidget(); - gridWidget.getMainPositioner().margin(4, 2, 0, 0); - Positioner smallPositioner = gridWidget.copyPositioner().margin(5, 3, 1, 1); - GridWidget.Adder adder = gridWidget.createAdder(4); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("configs"), widgetWidth, button -> initWidgets(category & 0b01, 0)), 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("configs")); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("disable"), widgetWidth, button -> initWidgets(0b11, 0)), 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("disable")); + GridLayout grid = new GridLayout(); + grid.defaultCellSetting().padding(4, 2, 0, 0); + LayoutSettings smallSettings = grid.newCellSettings().padding(5, 3, 1, 1); + GridLayout.RowHelper rows = grid.createRowHelper(4); + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("configs"), widgetWidth, button -> initWidgets(category & 0b01, 0)), 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("configs")); + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("disable"), widgetWidth, button -> initWidgets(0b11, 0)), 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("disable")); final int widgetsPerPage, size; if ((category & 0b10) == 0) { widgetsPerPage = 8; @@ -177,137 +179,139 @@ private void initRightWidgets(final int category, final int page) { for (int i = page * widgetsPerPage; i < Math.min((page + 1) * widgetsPerPage, size); i++) { BindingTarget target = targetList.get(i); String name = target.name; - adder.add(createButton(LocUtil.literal(name), widgetWidth * 2 - 18, button -> loadBindingTarget(target)), 3).setTooltip(Tooltip.of(LocUtil.literal(name))); - adder.add(new TexturedButton(48, 0, button -> { + rows.addChild(createButton(LocUtil.literal(name), widgetWidth * 2 - 18, button -> loadBindingTarget(target)), 3).setTooltip(Tooltip.create(LocUtil.literal(name))); + rows.addChild(new TexturedButton(48, 0, button -> { targetList.remove(target); ConfigFile.save(); initWidgets(category, page * widgetsPerPage > size - 2 && size > 1 ? page - 1 : page); - }), 1, smallPositioner); + }), 1, smallSettings); } } else { widgetsPerPage = 5; size = disabledIds.size(); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("copy"), widgetWidth, button -> idsInClipBoard = List.copyOf(disabledIds)), 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("copy")); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("paste"), widgetWidth, button -> { + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("copy"), widgetWidth, button -> idsInClipBoard = List.copyOf(disabledIds)), 2).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("copy")); + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("paste"), widgetWidth, button -> { idsInClipBoard.stream().filter(textureId -> !disabledIds.contains(textureId)).forEach(disabledIds::add); initWidgets(category, 0); }), 2); - adder.add(disabledIdField, 4, smallPositioner).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("disabledIdField")); - adder.add(createButton(LocUtil.MODEL_VIEW_WIDGET("clear"), widgetWidth, button -> { + rows.addChild(disabledIdField, 4, smallSettings).setTooltip(LocUtil.MODEL_VIEW_TOOLTIP("disabledIdField")); + rows.addChild(createButton(LocUtil.MODEL_VIEW_WIDGET("clear"), widgetWidth, button -> { disabledIds.clear(); initWidgets(category, 0); }), 2); - adder.add(showDisabled, 1, gridWidget.copyPositioner().margin(7, 3, 1, 1)); - adder.add(new TexturedButton(64, 0, button -> { - String disabledId = disabledIdField.getText(); + rows.addChild(showDisabled, 1, grid.newCellSettings().padding(7, 3, 1, 1)); + rows.addChild(new TexturedButton(64, 0, button -> { + String disabledId = disabledIdField.getValue(); if (disabledId.isBlank() || disabledIds.contains(disabledId)) return; disabledIds.add(disabledId); initWidgets(category, page); - }), 1, smallPositioner); + }), 1, smallSettings); for (int i = page * widgetsPerPage; i < Math.min((page + 1) * widgetsPerPage, size); i++) { String textureId = disabledIds.get(i); - adder.add(createButton(LocUtil.literal(textureId), widgetWidth * 2 - 18, button -> disabledIdField.setText(textureId)), 3).setTooltip(Tooltip.of(LocUtil.literal(textureId))); - adder.add(new TexturedButton(48, 0, button -> { + rows.addChild(createButton(LocUtil.literal(textureId), widgetWidth * 2 - 18, button -> disabledIdField.setValue(textureId)), 3).setTooltip(Tooltip.create(LocUtil.literal(textureId))); + rows.addChild(new TexturedButton(48, 0, button -> { disabledIds.remove(textureId); initWidgets(category, page * widgetsPerPage > size - 2 && size > 1 ? page - 1 : page); - }), 1, smallPositioner); + }), 1, smallSettings); } } - gridWidget.refreshPositions(); - SimplePositioningWidget.setPos(gridWidget, x + (xSize + ySize) / 2 + 4, y + 2, x + xSize, y + ySize, 0, 0); - gridWidget.forEachChild(this::addDrawableChild); + grid.arrangeElements(); + FrameLayout.alignInRectangle(grid, x + (xSize + ySize) / 2 + 4, y + 2, x + xSize, y + ySize, 0, 0); + grid.visitWidgets(this::addRenderableWidget); final int pages = (size - 1) / widgetsPerPage + 1; - addDrawableChild(new TexturedButton(x + (xSize + ySize) / 2 + 8, y + ySize - 20, 16, 16, 16, 0, button -> initWidgets(category, (page - 1 + pages) % pages))); - addDrawableChild(new TextWidget(x + (xSize + ySize) / 2 + 30, y + ySize - 20, widgetWidth * 2 - 40, widgetHeight, LocUtil.literal((page + 1) + " / " + pages), textRenderer)); - addDrawableChild(new TexturedButton(x + xSize - 21, y + ySize - 20, 16, 16, 32, 0, button -> initWidgets(category, (page + 1) % pages))); + addRenderableWidget(new TexturedButton(x + (xSize + ySize) / 2 + 8, y + ySize - 20, 16, 16, 16, 0, button -> initWidgets(category, (page - 1 + pages) % pages))); + addRenderableWidget(new StringWidget(x + (xSize + ySize) / 2 + 30, y + ySize - 20, widgetWidth * 2 - 40, widgetHeight, LocUtil.literal((page + 1) + " / " + pages), font)); + addRenderableWidget(new TexturedButton(x + xSize - 21, y + ySize - 20, 16, 16, 32, 0, button -> initWidgets(category, (page + 1) % pages))); } @Override - public void render(DrawContext context, int mouseX, int mouseY, float delta) { - renderBackground(context);// 1.20.1 only - drawEntity(context, x + (xSize - ySize) / 2, y, x + (xSize + ySize) / 2, y + ySize, mouseX, mouseY, client.player); - super.render(context, mouseX, mouseY, delta); + public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + renderBackground(graphics);// 1.20.1 only + drawEntity(graphics, x + (xSize - ySize) / 2, y, x + (xSize + ySize) / 2, y + ySize, mouseX, mouseY, minecraft.player); + super.render(graphics, mouseX, mouseY, delta); } @Override - public void renderBackground(DrawContext context) { - super.renderBackground(context); - context.fill(x, y, x + (xSize - ySize) / 2 - 4, y + ySize, 0xFF444444); - context.fill(x + (xSize - ySize) / 2, y, x + (xSize + ySize) / 2, y + ySize, 0xFF222222); - context.fill(x + (xSize + ySize) / 2 + 4, y, x + xSize, y + ySize, 0xFF444444); + public void renderBackground(GuiGraphics graphics) { + super.renderBackground(graphics); + graphics.fill(x, y, x + (xSize - ySize) / 2 - 4, y + ySize, 0xFF444444); + graphics.fill(x + (xSize - ySize) / 2, y, x + (xSize + ySize) / 2, y + ySize, 0xFF222222); + graphics.fill(x + (xSize + ySize) / 2 + 4, y, x + xSize, y + ySize, 0xFF444444); } - protected void drawEntity(DrawContext context, int x1, int y1, int x2, int y2, int mouseX, int mouseY, LivingEntity entity) { + protected void drawEntity(GuiGraphics graphics, int x1, int y1, int x2, int y2, int mouseX, int mouseY, LivingEntity entity) { float centerX = (float) (x1 + x2) / 2.0f; float centerY = (float) (y1 + y2) / 2.0f; - context.enableScissor(x1, y1, x2, y2); + graphics.enableScissor(x1, y1, x2, y2); Quaternionf quaternionf = new Quaternionf().rotateX((float) Math.PI / 6 + xRot).rotateY((float) Math.PI / 6 + yRot).rotateZ((float) Math.PI); - float entityBodyYaw = entity.bodyYaw; - float entityYaw = entity.getYaw(); - float entityPitch = entity.getPitch(); - float entityPrevHeadYaw = entity.prevHeadYaw; - float entityHeadYaw = entity.headYaw; - entity.bodyYaw = 180.0f; - entity.setYaw(180.0f + (float) entityYawSlider.getValue()); - entity.setPitch((float) entityPitchSlider.getValue()); - entity.headYaw = entity.getYaw(); - entity.prevHeadYaw = entity.getYaw(); + float entityBodyYaw = entity.yBodyRot; + float entityYaw = entity.getYRot(); + float entityPitch = entity.getXRot(); + float entityPrevHeadYaw = entity.yHeadRotO; + float entityHeadYaw = entity.yHeadRot; + entity.yBodyRot = 180.0f; + entity.setYRot(180.0f + (float) entityYawSlider.getValue()); + entity.setXRot((float) entityPitchSlider.getValue()); + entity.yHeadRot = entity.getYRot(); + entity.yHeadRotO = entity.getYRot(); Vector3f vector3f = new Vector3f((float) entityX, (float) entityY, -2.0f); - drawEntity(context, centerX, centerY, mouseX, mouseY, vector3f, quaternionf, entity); - entity.bodyYaw = entityBodyYaw; - entity.setYaw(entityYaw); - entity.setPitch(entityPitch); - entity.prevHeadYaw = entityPrevHeadYaw; - entity.headYaw = entityHeadYaw; - context.disableScissor(); + drawEntity(graphics, centerX, centerY, mouseX, mouseY, vector3f, quaternionf, entity); + entity.yBodyRot = entityBodyYaw; + entity.setYRot(entityYaw); + entity.setXRot(entityPitch); + entity.yHeadRotO = entityPrevHeadYaw; + entity.yHeadRot = entityHeadYaw; + graphics.disableScissor(); } - protected void drawEntity(DrawContext context, float x, float y, int mouseX, int mouseY, Vector3f offset, Quaternionf quaternionf, LivingEntity entity) { - context.getMatrices().push(); - context.getMatrices().translate(x, y, 0); - context.getMatrices().multiplyPositionMatrix(new Matrix4f().scaling(entitySize, entitySize, -entitySize)); - context.getMatrices().translate(offset.x(), offset.y(), offset.z()); - context.getMatrices().multiply(quaternionf); - DiffuseLighting.method_34742(); - EntityRenderDispatcher entityRenderDispatcher = MinecraftClient.getInstance().getEntityRenderDispatcher(); - entityRenderDispatcher.setRenderShadows(false); + protected void drawEntity(GuiGraphics graphics, float x, float y, int mouseX, int mouseY, Vector3f offset, Quaternionf quaternionf, LivingEntity entity) { + graphics.pose().pushPose(); + graphics.pose().translate(x, y, 0); + graphics.pose().mulPoseMatrix(new Matrix4f().scaling(entitySize, entitySize, -entitySize)); + graphics.pose().translate(offset.x(), offset.y(), offset.z()); + graphics.pose().mulPose(quaternionf); + Lighting.setupForEntityInInventory(); + EntityRenderDispatcher entityRenderDispatcher = Minecraft.getInstance().getEntityRenderDispatcher(); + entityRenderDispatcher.setRenderShadow(false); ModelAnalyser analyser = new ModelAnalyser(generateBindingTarget()); - entityRenderDispatcher.render(entity, 0, -entity.getHeight() / 2.0f, 0, 0.0f, 1.0f, context.getMatrices(), analyser, 0xF000f0); - analyser.initialize(entitySize, mouseX, mouseY, layers, showDisabled.getValue() == 1, disabledIdField.getText()); + entityRenderDispatcher.render(entity, 0, -entity.getBbHeight() / 2.0f, 0, 0.0f, 1.0f, graphics.pose(), analyser, 0xF000f0); + analyser.analyse(entitySize, mouseX, mouseY, layers, showDisabled.getValue() == 1, disabledIdField.getValue()); focusedUV = analyser.getFocusedUV(); focusedTextureId = analyser.focusedTextureId(); - if ((category & 0b1) == 0) analyser.drawModelWithNormals(context, entitySize); - else analyser.previewEffect(context, entitySize, (category & 0b10) == 2); - entityRenderDispatcher.setRenderShadows(true); - context.getMatrices().pop(); - DiffuseLighting.enableGuiDepthLighting(); + analyser.forEachRecord(record -> ModelAnalyser.renderVertices(record.vertices(), graphics.bufferSource().getBuffer(record.renderType()))); + graphics.flush(); + if ((category & 0b1) == 0) analyser.drawNormals(graphics, entitySize); + else analyser.previewEffect(graphics, entitySize, (category & 0b10) == 2); + entityRenderDispatcher.setRenderShadow(true); + graphics.pose().popPose(); + Lighting.setupFor3DItems(); } protected BindingTarget generateBindingTarget() { - return new BindingTarget(nameField.getText(), textureIdField.getText()).priority(priorityField.getValue()) - .forwardU(forwardUField.getValue()).forwardV(forwardVField.getValue()) - .upwardU(upwardUField.getValue()).upwardV(upwardVField.getValue()) - .posU(posUField.getValue()).posV(posVField.getValue()) - .disablingDepth(depthField.getValue()) + return new BindingTarget(nameField.getValue(), textureIdField.getValue()).priority(priorityField.getNumber()) + .forwardU(forwardUField.getNumber()).forwardV(forwardVField.getNumber()) + .upwardU(upwardUField.getNumber()).upwardV(upwardVField.getNumber()) + .posU(posUField.getNumber()).posV(posVField.getNumber()) + .disablingDepth(depthField.getNumber()) .bindX(bindXButton.getValue() == 0).bindY(bindYButton.getValue() == 0).bindZ(bindZButton.getValue() == 0).bindRotation(bindRotButton.getValue() == 0) - .scale(scaleField.getValue()).offsetX(offsetXSlider.getValue()).offsetY(offsetYSlider.getValue()).offsetZ(offsetZSlider.getValue()) + .scale(scaleField.getNumber()).offsetX(offsetXSlider.getValue()).offsetY(offsetYSlider.getValue()).offsetZ(offsetZSlider.getValue()) .pitch((float) pitchSlider.getValue()).yaw((float) yawSlider.getValue()).roll((float) rollSlider.getValue()) .disabledTextureIds(List.copyOf(disabledIds)); } protected void loadBindingTarget(BindingTarget target) { if (target.isEmpty()) return; - nameField.setText(target.name); - textureIdField.setText(target.textureId); - priorityField.setValue(target.priority); - forwardUField.setValue(target.forwardU); - forwardVField.setValue(target.forwardV); - upwardUField.setValue(target.upwardU); - upwardVField.setValue(target.upwardV); - posUField.setValue(target.posU); - posVField.setValue(target.posV); - depthField.setValue(target.disablingDepth); - scaleField.setValue((float) target.scale); + nameField.setValue(target.name); + textureIdField.setValue(target.textureId); + priorityField.setNumber(target.priority); + forwardUField.setNumber(target.forwardU); + forwardVField.setNumber(target.forwardV); + upwardUField.setNumber(target.upwardU); + upwardVField.setNumber(target.upwardV); + posUField.setNumber(target.posU); + posVField.setNumber(target.posV); + depthField.setNumber(target.disablingDepth); + scaleField.setNumber((float) target.scale); bindXButton.setValue(target.bindX ? 0 : 1); offsetXSlider.setValue(target.offsetX); bindYButton.setValue(target.bindY ? 0 : 1); @@ -322,24 +326,24 @@ protected void loadBindingTarget(BindingTarget target) { disabledIds.addAll(target.disabledTextureIds); } - private ButtonWidget createButton(Text message, int width, ButtonWidget.PressAction onPress) { - return ButtonWidget.builder(message, onPress).size(width, widgetHeight).build(); + private Button createButton(Component message, int width, Button.OnPress onPress) { + return Button.builder(message, onPress).size(width, widgetHeight).build(); } - private CyclingButtonWidget createCyclingButton(Map messages, int width, Text optionText) { - return new CyclingButtonWidget.Builder(messages::get).values(messages.keySet()).build(0, 0, width, widgetHeight, optionText); + private CycleButton createCyclingButton(Map messages, int width, Component optionText) { + return new CycleButton.Builder(messages::get).withValues(messages.keySet()).create(0, 0, width, widgetHeight, optionText); } - private DoubleSliderWidget createSlider(String key, int width, double min, double max) { - return new DoubleSliderWidget(width, widgetHeight, 0, min, max, d -> LocUtil.MODEL_VIEW_WIDGET(key, MathUtil.round(d, 2))); + private DoubleSlider createSlider(String key, int width, double min, double max) { + return new DoubleSlider(width, widgetHeight, 0, min, max, d -> LocUtil.MODEL_VIEW_WIDGET(key, MathUtil.round(d, 2))); } - private NumberFieldWidget createFloatField(int width, float defaultValue, @Nullable NumberFieldWidget copyFrom) { - return NumberFieldWidget.ofFloat(textRenderer, width - 2, widgetHeight - 2, defaultValue, copyFrom).setMax(1.0f).setMin(0f); + private NumberField createFloatField(int width, float defaultValue, @Nullable NumberField copyFrom) { + return NumberField.ofFloat(font, width - 2, widgetHeight - 2, defaultValue, copyFrom).setMax(1.0f).setMin(0f); } - private TextFieldWidget createTextField(int width, @Nullable TextFieldWidget copyFrom) { - return new TextFieldWidget(textRenderer, 0, 0, width - 2, widgetHeight - 2, copyFrom, Text.empty()); + private EditBox createTextField(int width, @Nullable EditBox copyFrom) { + return new EditBox(font, 0, 0, width - 2, widgetHeight - 2, copyFrom, Component.empty()); } protected boolean mouseInViewArea(double mouseX, double mouseY) { @@ -349,22 +353,22 @@ protected boolean mouseInViewArea(double mouseX, double mouseY) { @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { if (mouseInViewArea(mouseX, mouseY) && focusedUV != null && button == GLFW.GLFW_MOUSE_BUTTON_LEFT && - InputUtil.isKeyPressed(client.getWindow().getHandle(), GLFW.GLFW_KEY_LEFT_ALT)) { + InputConstants.isKeyDown(minecraft.getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { if (category == 0) { if (selectingButton.getValue() == 0) { - forwardUField.setValue(focusedUV.x); - forwardVField.setValue(focusedUV.y); + forwardUField.setNumber(focusedUV.x); + forwardVField.setNumber(focusedUV.y); } else if (selectingButton.getValue() == 1) { - upwardUField.setValue(focusedUV.x); - upwardVField.setValue(focusedUV.y); + upwardUField.setNumber(focusedUV.x); + upwardVField.setNumber(focusedUV.y); } else { - posUField.setValue(focusedUV.x); - posVField.setValue(focusedUV.y); + posUField.setNumber(focusedUV.x); + posVField.setNumber(focusedUV.y); } - textureIdField.setText(focusedTextureId); + textureIdField.setValue(focusedTextureId); return true; } else if (category == 0b11) { - disabledIdField.setText(focusedTextureId); + disabledIdField.setValue(focusedTextureId); return true; } } @@ -374,7 +378,7 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { @Override public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { if (mouseInViewArea(mouseX, mouseY)) { - if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT && !InputUtil.isKeyPressed(client.getWindow().getHandle(), GLFW.GLFW_KEY_LEFT_ALT)) { + if (button == GLFW.GLFW_MOUSE_BUTTON_LEFT && !InputConstants.isKeyDown(minecraft.getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { xRot += (float) (Math.PI * deltaY / ySize); yRot -= (float) (Math.PI * deltaX / ySize); return true; @@ -390,10 +394,10 @@ public boolean mouseDragged(double mouseX, double mouseY, int button, double del @Override public boolean mouseScrolled(double mouseX, double mouseY, double amount) { if (mouseInViewArea(mouseX, mouseY)) { - if (InputUtil.isKeyPressed(client.getWindow().getHandle(), GLFW.GLFW_KEY_LEFT_ALT)) { + if (InputConstants.isKeyDown(minecraft.getWindow().getWindow(), GLFW.GLFW_KEY_LEFT_ALT)) { layers = Math.max(0, layers + (int) amount); } else { - entitySize = MathHelper.clamp(entitySize + (int) amount * entitySize / 16, 16, 1024); + entitySize = Mth.clamp(entitySize + (int) amount * entitySize / 16, 16, 1024); } return true; } @@ -401,7 +405,7 @@ public boolean mouseScrolled(double mouseX, double mouseY, double amount) { } @Override - public boolean shouldPause() { + public boolean isPauseScreen() { return pauseButton.getValue() == 1; } } diff --git a/common/src/main/java/com/xtracr/realcamera/gui/NumberField.java b/common/src/main/java/com/xtracr/realcamera/gui/NumberField.java new file mode 100644 index 0000000..13b25d1 --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/gui/NumberField.java @@ -0,0 +1,120 @@ +package com.xtracr.realcamera.gui; + +import com.xtracr.realcamera.util.LocUtil; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import net.minecraft.util.FormattedCharSequence; +import org.jetbrains.annotations.Nullable; + +public abstract class NumberField> extends EditBox { + private final T defaultValue; + protected T maximum, minimum; + private Tooltip tooltip; + + NumberField(Font font, int width, int height, T defaultValue, T maximum, T minimum, @Nullable NumberField copyFrom) { + super(font, 0, 0, width, height, Component.empty()); + this.defaultValue = defaultValue; + this.maximum = maximum; + this.minimum = minimum; + setNumber(defaultValue); + if (copyFrom != null) setNumber(copyFrom.getNumber()); + } + + public static NumberField ofFloat(Font font, int width, int height, float defaultValue, @Nullable NumberField copyFrom) { + return new FloatField(font, width, height, defaultValue, copyFrom); + } + + public static NumberField ofInt(Font font, int width, int height, int defaultValue, @Nullable NumberField copyFrom) { + return new IntField(font, width, height, defaultValue, copyFrom); + } + + public T getNumber() { + try { + return getNumberInternal(); + } catch (Exception exception) { + return defaultValue; + } + } + + public void setNumber(T value) { + try { + if (value.compareTo(minimum) < 0) value = minimum; + else if (value.compareTo(maximum) > 0) value = maximum; + setValue(value.toString()); + } catch (Exception ignored) { + } + } + + public NumberField setMax(T maximum) { + this.maximum = maximum; + return this; + } + + public NumberField setMin(T minimum) { + this.minimum = minimum; + return this; + } + + abstract protected T getNumberInternal(); + + protected void checkText() { + super.setTooltip(tooltip); + setFormatter((string, firstCharacterIndex) -> FormattedCharSequence.forward(string, Style.EMPTY)); + if (getValue().isEmpty()) return; + try { + T value = getNumberInternal(); + if (value.compareTo(minimum) < 0) throw new Exception("< " + minimum); + if (value.compareTo(maximum) > 0) throw new Exception("> " + maximum); + } catch (Exception exception) { + super.setTooltip(Tooltip.create(LocUtil.literal("Invalid number: " + exception.getMessage()).withStyle(s -> s.withColor(ChatFormatting.RED)))); + setFormatter((string, firstCharacterIndex) -> FormattedCharSequence.forward(string, Style.EMPTY.withColor(ChatFormatting.RED))); + } + } + + @Override + public void setTooltip(Tooltip tooltip) { + this.tooltip = tooltip; + super.setTooltip(tooltip); + } + + @Override + public boolean charTyped(char chr, int modifiers) { + if (chr != '-' && chr != '.' && (chr < '0' || chr > '9')) return false; + return super.charTyped(chr, modifiers); + } + + @Override + public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + checkText(); + super.renderWidget(graphics, mouseX, mouseY, delta); + } + + private static class FloatField extends NumberField { + FloatField(Font font, int width, int height, float defaultValue, @Nullable NumberField copyFrom) { + super(font, width, height, defaultValue, Float.MAX_VALUE, -Float.MAX_VALUE, copyFrom); + setMaxLength(8); + } + + @Override + protected Float getNumberInternal() { + return Float.parseFloat(getValue()); + } + } + + private static class IntField extends NumberField { + IntField(Font font, int width, int height, int defaultValue, @Nullable NumberField copyFrom) { + super(font, width, height, defaultValue, Integer.MAX_VALUE, Integer.MIN_VALUE, copyFrom); + setMaxLength(8); + } + + @Override + protected Integer getNumberInternal() { + return Integer.parseInt(getValue()); + } + } +} diff --git a/common/src/main/java/com/xtracr/realcamera/gui/NumberFieldWidget.java b/common/src/main/java/com/xtracr/realcamera/gui/NumberFieldWidget.java deleted file mode 100644 index 15a58ec..0000000 --- a/common/src/main/java/com/xtracr/realcamera/gui/NumberFieldWidget.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.xtracr.realcamera.gui; - -import com.xtracr.realcamera.util.LocUtil; -import net.minecraft.client.font.TextRenderer; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.tooltip.Tooltip; -import net.minecraft.client.gui.widget.TextFieldWidget; -import net.minecraft.text.OrderedText; -import net.minecraft.text.Style; -import net.minecraft.text.Text; -import net.minecraft.util.Formatting; -import org.jetbrains.annotations.Nullable; - -public abstract class NumberFieldWidget> extends TextFieldWidget { - private final T defaultValue; - protected T maximum, minimum; - private Tooltip tooltip; - - NumberFieldWidget(TextRenderer textRenderer, int width, int height, T defaultValue, T maximum, T minimum, @Nullable NumberFieldWidget copyFrom) { - super(textRenderer, 0, 0, width, height, Text.empty()); - this.defaultValue = defaultValue; - this.maximum = maximum; - this.minimum = minimum; - setValue(defaultValue); - if (copyFrom != null) setValue(copyFrom.getValue()); - } - - public static NumberFieldWidget ofFloat(TextRenderer textRenderer, int width, int height, float defaultValue, @Nullable NumberFieldWidget copyFrom) { - return new FloatFieldWidget(textRenderer, width, height, defaultValue, copyFrom); - } - - public static NumberFieldWidget ofInt(TextRenderer textRenderer, int width, int height, int defaultValue, @Nullable NumberFieldWidget copyFrom) { - return new IntFieldWidget(textRenderer, width, height, defaultValue, copyFrom); - } - - public T getValue() { - try { - return getValueInternal(); - } catch (Exception exception) { - return defaultValue; - } - } - - public void setValue(T value) { - try { - if (value.compareTo(minimum) < 0) value = minimum; - else if (value.compareTo(maximum) > 0) value = maximum; - setText(value.toString()); - } catch (Exception ignored) { - } - } - - public NumberFieldWidget setMax(T maximum) { - this.maximum = maximum; - return this; - } - - public NumberFieldWidget setMin(T minimum) { - this.minimum = minimum; - return this; - } - - abstract protected T getValueInternal(); - - protected void checkText() { - super.setTooltip(tooltip); - setRenderTextProvider((string, firstCharacterIndex) -> OrderedText.styledForwardsVisitedString(string, Style.EMPTY)); - if (getText().isEmpty()) return; - try { - T value = getValueInternal(); - if (value.compareTo(minimum) < 0) throw new Exception("< " + minimum); - if (value.compareTo(maximum) > 0) throw new Exception("> " + maximum); - } catch (Exception exception) { - super.setTooltip(Tooltip.of(LocUtil.literal("Invalid number: " + exception.getMessage()).styled(s -> s.withColor(Formatting.RED)))); - setRenderTextProvider((string, firstCharacterIndex) -> OrderedText.styledForwardsVisitedString(string, Style.EMPTY.withColor(Formatting.RED))); - } - } - - @Override - public void setTooltip(Tooltip tooltip) { - this.tooltip = tooltip; - super.setTooltip(tooltip); - } - - @Override - public boolean charTyped(char chr, int modifiers) { - if (chr != '-' && chr != '.' && (chr < '0' || chr > '9')) return false; - return super.charTyped(chr, modifiers); - } - - @Override - public void renderButton(DrawContext context, int mouseX, int mouseY, float delta) { - checkText(); - super.renderButton(context, mouseX, mouseY, delta); - } - - private static class FloatFieldWidget extends NumberFieldWidget { - FloatFieldWidget(TextRenderer textRenderer, int width, int height, float defaultValue, @Nullable NumberFieldWidget copyFrom) { - super(textRenderer, width, height, defaultValue, Float.MAX_VALUE, -Float.MAX_VALUE, copyFrom); - setMaxLength(8); - } - - @Override - protected Float getValueInternal() { - return Float.parseFloat(getText()); - } - } - - private static class IntFieldWidget extends NumberFieldWidget { - IntFieldWidget(TextRenderer textRenderer, int width, int height, int defaultValue, @Nullable NumberFieldWidget copyFrom) { - super(textRenderer, width, height, defaultValue, Integer.MAX_VALUE, Integer.MIN_VALUE, copyFrom); - setMaxLength(8); - } - - @Override - protected Integer getValueInternal() { - return Integer.parseInt(getText()); - } - } -} diff --git a/common/src/main/java/com/xtracr/realcamera/gui/TexturedButton.java b/common/src/main/java/com/xtracr/realcamera/gui/TexturedButton.java index 4cda1f2..e7c8a37 100644 --- a/common/src/main/java/com/xtracr/realcamera/gui/TexturedButton.java +++ b/common/src/main/java/com/xtracr/realcamera/gui/TexturedButton.java @@ -1,17 +1,17 @@ package com.xtracr.realcamera.gui; import com.xtracr.realcamera.RealCamera; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; -import net.minecraft.client.gui.widget.PressableWidget; -import net.minecraft.text.Text; -import net.minecraft.util.Identifier; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.AbstractButton; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; import java.util.function.Consumer; -public class TexturedButton extends PressableWidget { - public static final Identifier ICON_TEXTURE = new Identifier(RealCamera.MODID, "textures/gui/icon.png"); - protected final Identifier texture; +public class TexturedButton extends AbstractButton { + public static final ResourceLocation ICON_TEXTURE = new ResourceLocation(RealCamera.MODID, "textures/gui/icon.png"); + protected final ResourceLocation texture; protected final int textureWidth, textureHeight, u, v; private final Consumer onPress; @@ -23,8 +23,8 @@ public TexturedButton(int x, int y, int width, int height, int u, int v, Consume this(x, y, width, height, u, v, ICON_TEXTURE, 256, 256, onPress); } - public TexturedButton(int x, int y, int width, int height, int u, int v, Identifier texture, int textureWidth, int textureHeight, Consumer onPress) { - super(x, y, width, height, Text.empty()); + public TexturedButton(int x, int y, int width, int height, int u, int v, ResourceLocation texture, int textureWidth, int textureHeight, Consumer onPress) { + super(x, y, width, height, Component.empty()); this.textureWidth = textureWidth; this.textureHeight = textureHeight; this.onPress = onPress; @@ -39,14 +39,14 @@ public void onPress() { } @Override - public void renderButton(DrawContext context, int mouseX, int mouseY, float delta) { - context.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0xFF646464); - context.drawTexture(texture, getX(), getY(), u, v, width, height, textureWidth, textureHeight); - if (isSelected()) context.drawBorder(getX(), getY(), getWidth(), getHeight(), 0xFFFFFFFF); + public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float delta) { + graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0xFF646464); + graphics.blit(texture, getX(), getY(), u, v, width, height, textureWidth, textureHeight); + if (isHoveredOrFocused()) graphics.renderOutline(getX(), getY(), getWidth(), getHeight(), 0xFFFFFFFF); } @Override - protected void appendClickableNarrations(NarrationMessageBuilder builder) { - this.appendDefaultNarrations(builder); + protected void updateWidgetNarration(NarrationElementOutput builder) { + this.defaultButtonNarrationText(builder); } } diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/CameraAccessor.java b/common/src/main/java/com/xtracr/realcamera/mixin/CameraAccessor.java index dda5ee0..9451e4c 100644 --- a/common/src/main/java/com/xtracr/realcamera/mixin/CameraAccessor.java +++ b/common/src/main/java/com/xtracr/realcamera/mixin/CameraAccessor.java @@ -1,12 +1,12 @@ package com.xtracr.realcamera.mixin; -import net.minecraft.client.render.Camera; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.Camera; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(Camera.class) public interface CameraAccessor { @Invoker - void invokeSetPos(Vec3d pos); + void invokeSetPosition(Vec3 position); } diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinCamera.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinCamera.java index f5b5c94..6f95e8f 100644 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinCamera.java +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinCamera.java @@ -3,16 +3,15 @@ import com.xtracr.realcamera.RealCameraCore; import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.config.ModConfig; -import net.minecraft.client.render.Camera; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityDimensions; -import net.minecraft.entity.EntityType; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.BlockView; -import net.minecraft.world.RaycastContext; +import net.minecraft.client.Camera; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; @@ -23,68 +22,67 @@ @Mixin(Camera.class) public abstract class MixinCamera { @Shadow - private BlockView area; + private BlockGetter level; @Shadow - private Entity focusedEntity; + private Entity entity; @Shadow - private Vec3d pos; + private Vec3 position; @Shadow - private float pitch; + private float xRot; @Shadow - private float yaw; + private float yRot; - @Inject(method = "update", at = @At("RETURN")) - private void realcamera$updateCamera(BlockView area, Entity focusedEntity, boolean thirdPerson, boolean inverseView, float tickDelta, CallbackInfo cInfo) { + @Inject(method = "setup", at = @At("RETURN")) + private void realcamera$setupCamera(BlockGetter area, Entity focusedEntity, boolean thirdPerson, boolean inverseView, float tickDelta, CallbackInfo cInfo) { if (!RealCameraCore.isActive()) return; ModConfig config = ConfigFile.config(); - Vec3d startVec = pos; - Box box = focusedEntity.getBoundingBox(); + Vec3 startVec = position; + AABB box = focusedEntity.getBoundingBox(); if (config.isClassic()) { - EntityDimensions playerDimensions = EntityType.PLAYER.getDimensions(); - double scale = 2 * box.getAverageSideLength() / (playerDimensions.height + playerDimensions.width); - Vec3d offset = new Vec3d(config.getClassicX(), config.getClassicY(), config.getClassicZ()).multiply(scale); - Vec3d center = new Vec3d(config.getCenterX(), config.getCenterY(), config.getCenterZ()).multiply(scale); - float newPitch = pitch + config.getClassicPitch(); - float newYaw = yaw - config.getClassicYaw(); - setRotation(yaw, 0.0f); - moveBy(center.getX(), center.getY(), center.getZ()); + double scale = focusedEntity instanceof LivingEntity livingEntity ? livingEntity.getScale() : 1; + Vec3 offset = new Vec3(config.getClassicX(), config.getClassicY(), -config.getClassicZ()).scale(scale); + Vec3 center = new Vec3(config.getCenterX(), config.getCenterY(), -config.getCenterZ()).scale(scale); + float newPitch = xRot + config.getClassicPitch(); + float newYaw = yRot - config.getClassicYaw(); + setRotation(yRot, 0.0f); + move(center.x(), center.y(), center.z()); setRotation(newYaw, newPitch); - moveBy(offset.getX(), offset.getY(), offset.getZ()); + move(offset.x(), offset.y(), offset.z()); } else { - Vec3d prevPos = RealCameraCore.getPos(pos); - double restrictedY = MathHelper.clamp(prevPos.getY(), box.minY + 0.1D, box.maxY - 0.1D); - startVec = new Vec3d(pos.getX(), restrictedY, pos.getZ()); - setPos(prevPos); - setRotation(RealCameraCore.getYaw(yaw), RealCameraCore.getPitch(pitch)); + Vec3 prevPos = RealCameraCore.getPos(position); + double restrictedY = Mth.clamp(prevPos.y(), box.minY + 0.1D, box.maxY - 0.1D); + startVec = new Vec3(position.x(), restrictedY, position.z()); + setPosition(prevPos); + setRotation(RealCameraCore.getYaw(yRot), RealCameraCore.getPitch(xRot)); } realcamera$clipToSpace(startVec); - RealCameraCore.setCameraPos(pos); + RealCameraCore.setCameraPos(position); } @Unique - private void realcamera$clipToSpace(Vec3d startVec) { - Vec3d offset = pos.subtract(startVec); - final float depth = 0.085F; + private void realcamera$clipToSpace(Vec3 startVec) { + Vec3 offset = position.subtract(startVec); + final float depth = 0.085f; for (int i = 0; i < 8; ++i) { float f = depth * ((i & 1) * 2 - 1); float g = depth * ((i >> 1 & 1) * 2 - 1); float h = depth * ((i >> 2 & 1) * 2 - 1); - Vec3d start = startVec.add(f, g, h); - Vec3d end = startVec.add(offset).add(f, g, h); - HitResult hitResult = area.raycast(new RaycastContext(start, end, RaycastContext.ShapeType.VISUAL, RaycastContext.FluidHandling.NONE, focusedEntity)); - double l = hitResult.getPos().distanceTo(start); + Vec3 start = startVec.add(f, g, h); + Vec3 end = startVec.add(offset).add(f, g, h); + HitResult hitResult = level.clip(new ClipContext(start, end, ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, entity)); + double l = hitResult.getLocation().distanceTo(start); if (hitResult.getType() == HitResult.Type.MISS || l >= offset.length()) continue; - offset = offset.multiply(l / offset.length()); + offset = offset.scale(l / offset.length()); } - setPos(startVec.add(offset)); + setPosition(startVec.add(offset)); } @Shadow - protected abstract void moveBy(double x, double y, double z); + protected abstract void move(double x, double y, double z); @Shadow protected abstract void setRotation(float yaw, float pitch); @Shadow - protected abstract void setPos(Vec3d pos); + protected abstract void setPosition(Vec3 position); } diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinClientPlayerEntity.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinClientPlayerEntity.java deleted file mode 100644 index 49e55e3..0000000 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinClientPlayerEntity.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.xtracr.realcamera.mixin; - -import com.mojang.authlib.GameProfile; -import com.xtracr.realcamera.RealCameraCore; -import com.xtracr.realcamera.config.ConfigFile; -import com.xtracr.realcamera.util.RaycastUtil; -import net.minecraft.client.network.AbstractClientPlayerEntity; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.world.ClientWorld; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.RaycastContext; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(ClientPlayerEntity.class) -public abstract class MixinClientPlayerEntity extends AbstractClientPlayerEntity { - public MixinClientPlayerEntity(ClientWorld world, GameProfile profile) { - super(world, profile); - } - - @Inject(method = "getLeashPos", at = @At("HEAD"), cancellable = true) - private void realcamera$atGetLeashPosHEAD(float delta, CallbackInfoReturnable cInfo) { - if (RealCameraCore.isRendering()) cInfo.setReturnValue(super.getLeashPos(delta)); - } - - @Override - public HitResult raycast(double maxDistance, float tickDelta, boolean includeFluids) { - if (!ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { - RaycastUtil.update(this, maxDistance * maxDistance, tickDelta); - return getWorld().raycast(RaycastUtil.getRaycastContext(RaycastContext.ShapeType.OUTLINE, - includeFluids ? RaycastContext.FluidHandling.ANY : RaycastContext.FluidHandling.NONE, this)); - } - return super.raycast(maxDistance, tickDelta, includeFluids); - } -} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinGameRenderer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinGameRenderer.java index dc5880b..bfb3070 100644 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinGameRenderer.java +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinGameRenderer.java @@ -1,19 +1,19 @@ package com.xtracr.realcamera.mixin; +import com.mojang.blaze3d.vertex.PoseStack; import com.xtracr.realcamera.RealCameraCore; import com.xtracr.realcamera.compat.CompatibilityHelper; import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.util.CrosshairUtil; import com.xtracr.realcamera.util.RaycastUtil; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.Camera; -import net.minecraft.client.render.GameRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.Entity; -import net.minecraft.entity.projectile.ProjectileUtil; -import net.minecraft.util.hit.EntityHitResult; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.projectile.ProjectileUtil; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.EntityHitResult; +import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -25,38 +25,38 @@ @Mixin(GameRenderer.class) public abstract class MixinGameRenderer { @Shadow - @Final MinecraftClient client; + @Final Minecraft minecraft; @Shadow - @Final private Camera camera; + @Final private Camera mainCamera; - @ModifyVariable(method = "updateTargetedEntity", at = @At("STORE"), ordinal = 0) + @ModifyVariable(method = "pick", at = @At("STORE"), ordinal = 0) private EntityHitResult realcamera$modifyEntityHitResult(EntityHitResult entityHitResult) { CrosshairUtil.capturedEntityHitResult = entityHitResult; if (!ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { - Vec3d startVec = RaycastUtil.getStartVec(); - Vec3d endVec = RaycastUtil.getEndVec(); - double sqDistance = (client.crosshairTarget != null ? client.crosshairTarget.getPos().squaredDistanceTo(startVec) : endVec.squaredDistanceTo(startVec)); - Entity cameraEntity = client.getCameraEntity(); - Box box = cameraEntity.getBoundingBox().stretch(cameraEntity.getRotationVec(client.getTickDelta()).multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0); - CrosshairUtil.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance); + Vec3 startVec = RaycastUtil.getStartVec(); + Vec3 endVec = RaycastUtil.getEndVec(); + double sqDistance = (minecraft.hitResult != null ? minecraft.hitResult.getLocation().distanceToSqr(startVec) : endVec.distanceToSqr(startVec)); + Entity cameraEntity = minecraft.getCameraEntity(); + AABB box = cameraEntity.getBoundingBox().expandTowards(cameraEntity.getViewVector(minecraft.getFrameTime()).scale(minecraft.gameMode.getPickRange())).inflate(1.0, 1.0, 1.0); + CrosshairUtil.capturedEntityHitResult = ProjectileUtil.getEntityHitResult(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.isPickable(), sqDistance); } return CrosshairUtil.capturedEntityHitResult; } - @Inject(method = "renderWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V")) - private void realcamera$onBeforeCameraUpdate(float tickDelta, long limitTime, MatrixStack matrices, CallbackInfo cInfo) { + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setup(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/world/entity/Entity;ZZF)V")) + private void realcamera$atBeforeCameraSetup(float tickDelta, long limitTime, PoseStack poseStack, CallbackInfo ci) { CompatibilityHelper.NEA_setDeltaTick(tickDelta); - RealCameraCore.initialize(client); + RealCameraCore.initialize(minecraft); if (RealCameraCore.isActive() && !ConfigFile.config().isClassic()) { - RealCameraCore.updateModel(client, tickDelta); + RealCameraCore.updateModel(minecraft, tickDelta); RealCameraCore.computeCamera(); } } - @Inject(method = "renderWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;setupFrustum(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/util/math/Vec3d;Lorg/joml/Matrix4f;)V")) - private void realcamera$onBeforeSetupFrustum(CallbackInfo cInfo) { + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;prepareCullFrustum(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/world/phys/Vec3;Lorg/joml/Matrix4f;)V")) + private void realcamera$atBeforePrePareFrustum(CallbackInfo cInfo) { if (RealCameraCore.isActive() && !ConfigFile.config().isClassic()) { - ((CameraAccessor) camera).invokeSetPos(RealCameraCore.getCameraPos(camera.getPos())); + ((CameraAccessor) mainCamera).invokeSetPosition(RealCameraCore.getCameraPos(mainCamera.getPosition())); } } } diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinGui.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinGui.java new file mode 100644 index 0000000..e80db27 --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinGui.java @@ -0,0 +1,29 @@ +package com.xtracr.realcamera.mixin; + +import com.xtracr.realcamera.RealCameraCore; +import com.xtracr.realcamera.config.ConfigFile; +import com.xtracr.realcamera.util.CrosshairUtil; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiGraphics; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Gui.class) +public abstract class MixinGui { + @Inject(method = "renderCrosshair", at = @At("HEAD")) + private void realcamera$atRenderCrosshairHEAD(GuiGraphics guiGraphics, CallbackInfo ci) { + if (ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { + guiGraphics.pose().pushPose(); + CrosshairUtil.translateMatrices(guiGraphics.pose()); + } + } + + @Inject(method = "renderCrosshair", at = @At("RETURN")) + private void realcamera$atRenderCrosshairRETURN(GuiGraphics guiGraphics, CallbackInfo ci) { + if (ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { + guiGraphics.pose().popPose(); + } + } +} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinHeldItemRenderer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinHeldItemRenderer.java deleted file mode 100644 index 47f1271..0000000 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinHeldItemRenderer.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.xtracr.realcamera.mixin; - -import com.xtracr.realcamera.RealCameraCore; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.item.HeldItemRenderer; -import net.minecraft.client.util.math.MatrixStack; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(HeldItemRenderer.class) -public abstract class MixinHeldItemRenderer { - @Inject(method = "renderItem(FLnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;Lnet/minecraft/client/network/ClientPlayerEntity;I)V", at = @At("HEAD"), cancellable = true) - private void realcamera$cancelRender(float tickDelta, MatrixStack matrices, VertexConsumerProvider.Immediate vertexConsumers, ClientPlayerEntity player, int light, CallbackInfo cInfo) { - if (player instanceof ClientPlayerEntity && RealCameraCore.isRendering()) { - cInfo.cancel(); - } - } -} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinInGameHud.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinInGameHud.java deleted file mode 100644 index 37ac3f2..0000000 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinInGameHud.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xtracr.realcamera.mixin; - -import com.xtracr.realcamera.RealCameraCore; -import com.xtracr.realcamera.config.ConfigFile; -import com.xtracr.realcamera.util.CrosshairUtil; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.hud.InGameHud; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(InGameHud.class) -public abstract class MixinInGameHud { - @Inject(method = "renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V", at = @At("HEAD")) - private void realcamera$atRenderCrosshairHEAD(DrawContext context, CallbackInfo cInfo) { - if (ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { - context.getMatrices().push(); - CrosshairUtil.translateMatrices(context.getMatrices()); - } - } - - @Inject(method = "renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V", at = @At("RETURN")) - private void realcamera$atRenderCrosshairRETURN(DrawContext context, CallbackInfo cInfo) { - if (ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { - context.getMatrices().pop(); - } - } -} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinItem.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinItem.java index 9ea8391..bfafb6f 100644 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinItem.java +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinItem.java @@ -3,11 +3,11 @@ import com.xtracr.realcamera.RealCameraCore; import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.util.RaycastUtil; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.Item; -import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.world.RaycastContext; -import net.minecraft.world.World; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.BlockHitResult; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -15,12 +15,11 @@ @Mixin(Item.class) public abstract class MixinItem { - @Inject(method = "raycast", at = @At("HEAD"), cancellable = true) - private static void realcamera$coverRaycast(World world, PlayerEntity player, RaycastContext.FluidHandling fluidHandling, - CallbackInfoReturnable cInfo) { + @Inject(method = "getPlayerPOVHitResult", at = @At("HEAD"), cancellable = true) + private static void realcamera$coverHitResult(Level world, Player player, ClipContext.Fluid fluidHandling, CallbackInfoReturnable cInfo) { if (!ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { RaycastUtil.update(player, 25.0d, 1.0f); - cInfo.setReturnValue(world.raycast(RaycastUtil.getRaycastContext(RaycastContext.ShapeType.OUTLINE, fluidHandling, player))); + cInfo.setReturnValue(world.clip(RaycastUtil.getClipContext(ClipContext.Block.OUTLINE, fluidHandling, player))); } } } diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinItemInHandRenderer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinItemInHandRenderer.java new file mode 100644 index 0000000..cea89fc --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinItemInHandRenderer.java @@ -0,0 +1,19 @@ +package com.xtracr.realcamera.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.xtracr.realcamera.RealCameraCore; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ItemInHandRenderer.class) +public abstract class MixinItemInHandRenderer { + @Inject(method = "renderHandsWithItems", at = @At("HEAD"), cancellable = true) + private void realcamera$cancelRender(float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, LocalPlayer localPlayer, int i, CallbackInfo cInfo) { + if (RealCameraCore.isRendering()) cInfo.cancel(); + } +} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinLevelRenderer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinLevelRenderer.java new file mode 100644 index 0000000..8f1148d --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinLevelRenderer.java @@ -0,0 +1,37 @@ +package com.xtracr.realcamera.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.xtracr.realcamera.RealCameraCore; +import com.xtracr.realcamera.config.ConfigFile; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.*; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(LevelRenderer.class) +public abstract class MixinLevelRenderer { + @Shadow + @Final private Minecraft minecraft; + @Shadow + @Final private RenderBuffers renderBuffers; + + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;endLastBatch()V", ordinal = 0)) + private void realcamera$renderLocalPlayer(PoseStack poseStack, float tickDelta, long limitTime, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, CallbackInfo ci) { + if (!RealCameraCore.isRendering()) return; + MultiBufferSource.BufferSource bufferSource = this.renderBuffers.bufferSource(); + Vec3 cameraPos = camera.getPosition(); + if (!ConfigFile.config().isClassic()) RealCameraCore.renderCameraEntity(bufferSource); + else renderEntity(camera.getEntity(), cameraPos.x(), cameraPos.y(), cameraPos.z(), tickDelta, new PoseStack(), bufferSource); + } + + @Shadow + protected abstract void renderEntity(Entity entity, double cameraX, double cameraY, double cameraZ, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers); +} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinLocalPlayer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinLocalPlayer.java new file mode 100644 index 0000000..94a8101 --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinLocalPlayer.java @@ -0,0 +1,38 @@ +package com.xtracr.realcamera.mixin; + +import com.mojang.authlib.GameProfile; +import com.xtracr.realcamera.RealCameraCore; +import com.xtracr.realcamera.config.ConfigFile; +import com.xtracr.realcamera.util.RaycastUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(LocalPlayer.class) +public abstract class MixinLocalPlayer extends AbstractClientPlayer { + public MixinLocalPlayer(ClientLevel world, GameProfile profile) { + super(world, profile); + } + + @Inject(method = "getRopeHoldPosition", at = @At("HEAD"), cancellable = true) + private void realcamera$atGetRopePosHEAD(float delta, CallbackInfoReturnable cInfo) { + if (RealCameraCore.isRendering()) cInfo.setReturnValue(super.getRopeHoldPosition(delta)); + } + + @Override + public HitResult pick(double maxDistance, float tickDelta, boolean includeFluids) { + if (!ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { + RaycastUtil.update(this, maxDistance * maxDistance, tickDelta); + return level().clip(RaycastUtil.getClipContext(ClipContext.Block.OUTLINE, + includeFluids ? ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, this)); + } + return super.pick(maxDistance, tickDelta, includeFluids); + } +} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinStuckInBodyLater.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinStuckInBodyLater.java new file mode 100644 index 0000000..8b442d8 --- /dev/null +++ b/common/src/main/java/com/xtracr/realcamera/mixin/MixinStuckInBodyLater.java @@ -0,0 +1,23 @@ +package com.xtracr.realcamera.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.xtracr.realcamera.RealCameraCore; +import com.xtracr.realcamera.config.ConfigFile; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.layers.StuckInBodyLayer; +import net.minecraft.world.entity.LivingEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(StuckInBodyLayer.class) +public abstract class MixinStuckInBodyLater { + @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/LivingEntity;FFFFFF)V", at = @At("HEAD"), cancellable = true) + private void realcamera$cancelRender(PoseStack poseStack, MultiBufferSource multiBufferSource, int i, T livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo cInfo) { + if (livingEntity instanceof LocalPlayer && RealCameraCore.isRendering() && !ConfigFile.config().isClassic() && !ConfigFile.config().renderStuckObjects()) { + cInfo.cancel(); + } + } +} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinStuckObjectsFeatureRenderer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinStuckObjectsFeatureRenderer.java deleted file mode 100644 index 27ddf29..0000000 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinStuckObjectsFeatureRenderer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.xtracr.realcamera.mixin; - -import com.xtracr.realcamera.RealCameraCore; -import com.xtracr.realcamera.config.ConfigFile; -import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.entity.feature.StuckObjectsFeatureRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.LivingEntity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(StuckObjectsFeatureRenderer.class) -public abstract class MixinStuckObjectsFeatureRenderer { - @Inject(method = "render(Lnet/minecraft/client/util/math/MatrixStack;Lnet/minecraft/client/render/VertexConsumerProvider;ILnet/minecraft/entity/LivingEntity;FFFFFF)V", at = @At("HEAD"), cancellable = true) - private void realcamera$cancelRender(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, T livingEntity, float f, float g, float h, float j, float k, float l, CallbackInfo cInfo) { - if (livingEntity instanceof ClientPlayerEntity && RealCameraCore.isRendering() && !ConfigFile.config().isClassic() && !ConfigFile.config().renderStuckObjects()) { - cInfo.cancel(); - } - } -} diff --git a/common/src/main/java/com/xtracr/realcamera/mixin/MixinWorldRenderer.java b/common/src/main/java/com/xtracr/realcamera/mixin/MixinWorldRenderer.java deleted file mode 100644 index dee4a75..0000000 --- a/common/src/main/java/com/xtracr/realcamera/mixin/MixinWorldRenderer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xtracr.realcamera.mixin; - -import com.xtracr.realcamera.RealCameraCore; -import com.xtracr.realcamera.config.ConfigFile; -import net.minecraft.client.render.*; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.Vec3d; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(WorldRenderer.class) -public abstract class MixinWorldRenderer { - @Shadow - @Final private BufferBuilderStorage bufferBuilders; - - @Inject(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/VertexConsumerProvider$Immediate;drawCurrentLayer()V", ordinal = 0)) - private void realcamera$renderClientPlayer(MatrixStack matrices, float tickDelta, long limitTime, boolean renderBlockOutline, - Camera camera, GameRenderer gameRenderer, LightmapTextureManager lightmapTextureManager, Matrix4f projectionMatrix, CallbackInfo cInfo) { - if (!RealCameraCore.isRendering()) return; - VertexConsumerProvider.Immediate immediate = this.bufferBuilders.getEntityVertexConsumers(); - Vec3d cameraPos = camera.getPos(); - if (!ConfigFile.config().isClassic()) RealCameraCore.renderCameraEntity(immediate); - else renderEntity(camera.getFocusedEntity(), cameraPos.getX(), cameraPos.getY(), cameraPos.getZ(), tickDelta, matrices, immediate); - } - - @Shadow - protected abstract void renderEntity(Entity entity, double cameraX, double cameraY, double cameraZ, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers); -} diff --git a/common/src/main/java/com/xtracr/realcamera/util/CrosshairUtil.java b/common/src/main/java/com/xtracr/realcamera/util/CrosshairUtil.java index da2a901..143b36b 100644 --- a/common/src/main/java/com/xtracr/realcamera/util/CrosshairUtil.java +++ b/common/src/main/java/com/xtracr/realcamera/util/CrosshairUtil.java @@ -1,29 +1,29 @@ package com.xtracr.realcamera.util; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.Camera; -import net.minecraft.client.util.Window; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.util.hit.EntityHitResult; -import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.Vec3d; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.world.phys.EntityHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; import org.joml.Matrix4f; public class CrosshairUtil { public static EntityHitResult capturedEntityHitResult; - private static Vec3d offset = Vec3d.ZERO; + private static Vec3 offset = Vec3.ZERO; - public static void translateMatrices(MatrixStack matrixStack) { - matrixStack.translate(offset.getX(), -offset.getY(), 0.0d); + public static void translateMatrices(PoseStack poseStack) { + poseStack.translate(offset.x(), -offset.y(), 0.0d); } - public static void update(MinecraftClient client, Camera camera, Matrix4f... projectionMatrices) { - HitResult hitResult = client.crosshairTarget; - offset = Vec3d.ZERO; - if (client.targetedEntity != null) hitResult = capturedEntityHitResult; + public static void update(Minecraft client, Camera camera, Matrix4f... projectionMatrices) { + HitResult hitResult = client.hitResult; + offset = Vec3.ZERO; + if (client.crosshairPickEntity != null) hitResult = capturedEntityHitResult; if (hitResult == null) return; Window window = client.getWindow(); - offset = MathUtil.projectToVec2d(hitResult.getPos().subtract(camera.getPos()), projectionMatrices) - .multiply(0.5 * window.getScaledWidth(), 0.5 * window.getScaledHeight(), 0.0d); + offset = MathUtil.projectToVec2d(hitResult.getLocation().subtract(camera.getPosition()), projectionMatrices) + .multiply(0.5 * window.getGuiScaledWidth(), 0.5 * window.getGuiScaledHeight(), 0.0d); } } diff --git a/common/src/main/java/com/xtracr/realcamera/util/LocUtil.java b/common/src/main/java/com/xtracr/realcamera/util/LocUtil.java index 7c7f630..9855aff 100644 --- a/common/src/main/java/com/xtracr/realcamera/util/LocUtil.java +++ b/common/src/main/java/com/xtracr/realcamera/util/LocUtil.java @@ -1,46 +1,46 @@ package com.xtracr.realcamera.util; import com.xtracr.realcamera.RealCamera; -import net.minecraft.client.gui.tooltip.Tooltip; -import net.minecraft.text.MutableText; -import net.minecraft.text.Text; +import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; public class LocUtil { public static final String KEY_MOD_NAME = "general." + RealCamera.FULL_ID + ".modName"; - public static MutableText MOD_NAME() { - return Text.translatable(KEY_MOD_NAME); + public static MutableComponent MOD_NAME() { + return Component.translatable(KEY_MOD_NAME); } - public static MutableText CONFIG_CATEGORY(String key) { - return Text.translatable("config.category." + RealCamera.FULL_ID + "." + key); + public static MutableComponent CONFIG_CATEGORY(String key) { + return Component.translatable("config.category." + RealCamera.FULL_ID + "." + key); } - public static MutableText CONFIG_OPTION(String key, Object... args) { - return Text.translatable("config.option." + RealCamera.FULL_ID + "." + key, args); + public static MutableComponent CONFIG_OPTION(String key, Object... args) { + return Component.translatable("config.option." + RealCamera.FULL_ID + "." + key, args); } - public static MutableText CONFIG_TOOLTIP(String key) { - return Text.translatable("config.tooltip." + RealCamera.FULL_ID + "." + key); + public static MutableComponent CONFIG_TOOLTIP(String key) { + return Component.translatable("config.tooltip." + RealCamera.FULL_ID + "." + key); } - public static MutableText MESSAGE(String key, Object... args) { - return Text.translatable("message." + RealCamera.FULL_ID + "." + key, args); + public static MutableComponent MESSAGE(String key, Object... args) { + return Component.translatable("message." + RealCamera.FULL_ID + "." + key, args); } - public static MutableText MODEL_VIEW_TITLE() { - return Text.translatable("screen." + RealCamera.FULL_ID + ".modelView_title"); + public static MutableComponent MODEL_VIEW_TITLE() { + return Component.translatable("screen." + RealCamera.FULL_ID + ".modelView_title"); } - public static MutableText MODEL_VIEW_WIDGET(String key, Object... args) { - return Text.translatable("screen.widget." + RealCamera.FULL_ID + ".modelView_" + key, args); + public static MutableComponent MODEL_VIEW_WIDGET(String key, Object... args) { + return Component.translatable("screen.widget." + RealCamera.FULL_ID + ".modelView_" + key, args); } public static Tooltip MODEL_VIEW_TOOLTIP(String key, Object... args) { - return Tooltip.of(Text.translatable("screen.tooltip." + RealCamera.FULL_ID + ".modelView_" + key, args)); + return Tooltip.create(Component.translatable("screen.tooltip." + RealCamera.FULL_ID + ".modelView_" + key, args)); } - public static MutableText literal(String string) { - return Text.literal(string); + public static MutableComponent literal(String string) { + return Component.literal(string); } } diff --git a/common/src/main/java/com/xtracr/realcamera/util/MathUtil.java b/common/src/main/java/com/xtracr/realcamera/util/MathUtil.java index dc07bfa..5f84c53 100644 --- a/common/src/main/java/com/xtracr/realcamera/util/MathUtil.java +++ b/common/src/main/java/com/xtracr/realcamera/util/MathUtil.java @@ -1,6 +1,6 @@ package com.xtracr.realcamera.util; -import net.minecraft.util.math.Vec3d; +import net.minecraft.world.phys.Vec3; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector4f; @@ -10,24 +10,24 @@ public static double round(double d, int digits) { return Math.round(d * Math.pow(10, digits)) / Math.pow(10, digits); } - public static Vec3d getEulerAngleYXZ(Matrix3f normal) { - if (normal.m21 <= -1.0) return new Vec3d(Math.PI / 2, Math.atan2(normal.m10, normal.m00), 0.0); - else if (normal.m21 >= 1.0) return new Vec3d(-Math.PI / 2, -Math.atan2(normal.m10, normal.m00), 0.0); + public static Vec3 getEulerAngleYXZ(Matrix3f normal) { + if (normal.m21 <= -1.0) return new Vec3(Math.PI / 2, Math.atan2(normal.m10, normal.m00), 0.0); + else if (normal.m21 >= 1.0) return new Vec3(-Math.PI / 2, -Math.atan2(normal.m10, normal.m00), 0.0); double xRot = Math.asin(-normal.m21); double yRot = Math.atan2(normal.m20, normal.m22); double zRot = Math.atan2(normal.m01, normal.m11); - return new Vec3d(xRot, yRot, zRot); + return new Vec3(xRot, yRot, zRot); } - public static Vec3d getIntersectionPoint(Vec3d planePoint, Vec3d planeNormal, Vec3d linePoint, Vec3d lineNormal) { - double distance = planeNormal.dotProduct(planePoint.subtract(linePoint)) / planeNormal.dotProduct(lineNormal); - return linePoint.add(lineNormal.multiply(distance)); + public static Vec3 getIntersectionPoint(Vec3 planePoint, Vec3 planeNormal, Vec3 linePoint, Vec3 lineNormal) { + double distance = planeNormal.dot(planePoint.subtract(linePoint)) / planeNormal.dot(lineNormal); + return linePoint.add(lineNormal.scale(distance)); } - public static Vec3d projectToVec2d(Vec3d vec3d, Matrix4f... projectionMatrices) { - Vector4f vector4f = new Vector4f((float) vec3d.getX(), (float) vec3d.getY(), (float) vec3d.getZ(), 1.0f); + public static Vec3 projectToVec2d(Vec3 vec3d, Matrix4f... projectionMatrices) { + Vector4f vector4f = new Vector4f((float) vec3d.x(), (float) vec3d.y(), (float) vec3d.z(), 1.0f); for (Matrix4f matrix4f : projectionMatrices) vector4f.mul(matrix4f); - if (vector4f.w() == 0.0) return Vec3d.ZERO; - return new Vec3d(vector4f.x(), vector4f.y(), 0).multiply(1 / (double) vector4f.w()); + if (vector4f.w() == 0.0) return Vec3.ZERO; + return new Vec3(vector4f.x(), vector4f.y(), 0).scale(1 / (double) vector4f.w()); } } diff --git a/common/src/main/java/com/xtracr/realcamera/util/RaycastUtil.java b/common/src/main/java/com/xtracr/realcamera/util/RaycastUtil.java index 681d1e3..9e6acc3 100644 --- a/common/src/main/java/com/xtracr/realcamera/util/RaycastUtil.java +++ b/common/src/main/java/com/xtracr/realcamera/util/RaycastUtil.java @@ -1,44 +1,44 @@ package com.xtracr.realcamera.util; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.render.Camera; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.RaycastContext; -import net.minecraft.world.RaycastContext.FluidHandling; -import net.minecraft.world.RaycastContext.ShapeType; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.ClipContext.Block; +import net.minecraft.world.level.ClipContext.Fluid; +import net.minecraft.world.phys.Vec3; public class RaycastUtil { - private static Vec3d startVec = Vec3d.ZERO; - private static Vec3d endVec = Vec3d.ZERO; + private static Vec3 startVec = Vec3.ZERO; + private static Vec3 endVec = Vec3.ZERO; - public static Vec3d getStartVec() { + public static Vec3 getStartVec() { return startVec; } - public static Vec3d getEndVec() { + public static Vec3 getEndVec() { return endVec; } - public static RaycastContext getRaycastContext(ShapeType shapeType, FluidHandling fluidHandling, Entity entity) { - return new RaycastContext(startVec, endVec, shapeType, fluidHandling, entity); + public static ClipContext getClipContext(Block shapeType, Fluid fluidHandling, Entity entity) { + return new ClipContext(startVec, endVec, shapeType, fluidHandling, entity); } public static void update(Entity entity, double sqDistance, float tickDelta) { - Camera camera = MinecraftClient.getInstance().gameRenderer.getCamera(); - Vec3d eyePos = entity.getCameraPosVec(tickDelta); - startVec = camera.getPos(); - Vec3d direction = Vec3d.fromPolar(camera.getPitch(), camera.getYaw()); - Vec3d offset = startVec.subtract(eyePos); - Vec3d footPoint = MathUtil.getIntersectionPoint(Vec3d.ZERO, direction, offset, direction); - if (footPoint.lengthSquared() > sqDistance) { + Camera camera = Minecraft.getInstance().gameRenderer.getMainCamera(); + Vec3 eyePos = entity.getEyePosition(tickDelta); + startVec = camera.getPosition(); + Vec3 direction = Vec3.directionFromRotation(camera.getXRot(), camera.getYRot()); + Vec3 offset = startVec.subtract(eyePos); + Vec3 footPoint = MathUtil.getIntersectionPoint(Vec3.ZERO, direction, offset, direction); + if (footPoint.lengthSqr() > sqDistance) { startVec = eyePos; - direction = entity.getRotationVec(tickDelta); - endVec = startVec.add(direction.multiply(Math.sqrt(sqDistance))); + direction = entity.getViewVector(tickDelta); + endVec = startVec.add(direction.scale(Math.sqrt(sqDistance))); return; - } else if (offset.lengthSquared() > sqDistance) { - startVec = startVec.add(direction.multiply(offset.distanceTo(footPoint) - Math.sqrt(sqDistance - footPoint.lengthSquared()))); + } else if (offset.lengthSqr() > sqDistance) { + startVec = startVec.add(direction.scale(offset.distanceTo(footPoint) - Math.sqrt(sqDistance - footPoint.lengthSqr()))); } - endVec = eyePos.add(footPoint.add(direction.multiply(Math.sqrt(sqDistance - footPoint.lengthSquared())))); + endVec = eyePos.add(footPoint.add(direction.scale(Math.sqrt(sqDistance - footPoint.lengthSqr())))); } } diff --git a/common/src/main/java/com/xtracr/realcamera/util/VertexRecorder.java b/common/src/main/java/com/xtracr/realcamera/util/VertexRecorder.java index 701b3a7..2157f21 100644 --- a/common/src/main/java/com/xtracr/realcamera/util/VertexRecorder.java +++ b/common/src/main/java/com/xtracr/realcamera/util/VertexRecorder.java @@ -1,33 +1,37 @@ package com.xtracr.realcamera.util; +import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexFormat; import com.xtracr.realcamera.config.BindingTarget; -import net.minecraft.client.render.RenderLayer; -import net.minecraft.client.render.VertexConsumer; -import net.minecraft.client.render.VertexConsumerProvider; -import net.minecraft.client.render.VertexFormat; -import net.minecraft.util.math.Vec3d; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; import java.awt.*; -import java.util.*; import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; +import java.util.*; +import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class VertexRecorder implements VertexConsumerProvider { +public class VertexRecorder implements MultiBufferSource { protected final List records = new ArrayList<>(); private final Stack recordStack = new Stack<>(); - protected static Vec3d getPos(Vertex[] primitive, float u, float v) { + public static void renderVertices(Vertex[] vertices, VertexConsumer buffer) { + for (Vertex vertex : vertices) vertex.render(buffer); + } + + protected static Vec3 getPos(Vertex[] primitive, float u, float v) { if (primitive.length < 3) return primitive[0].pos(); float u0 = primitive[0].u, v0 = primitive[0].v, u1 = primitive[1].u, v1 = primitive[1].v, u2 = primitive[2].u, v2 = primitive[2].v; float alpha = ((u - u1) * (v1 - v2) - (v - v1) * (u1 - u2)) / ((u0 - u1) * (v1 - v2) - (v0 - v1) * (u1 - u2)), beta = ((u - u2) * (v2 - v0) - (v - v2) * (u2 - u0)) / ((u1 - u2) * (v2 - v0) - (v1 - v2) * (u2 - u0)); - return primitive[0].pos().multiply(alpha).add(primitive[1].pos().multiply(beta)).add(primitive[2].pos().multiply(1 - alpha - beta)); + return primitive[0].pos().scale(alpha).add(primitive[1].pos().scale(beta)).add(primitive[2].pos().scale(1 - alpha - beta)); } protected static Vertex[] getPrimitive(BuiltRecord record, float u, float v) { @@ -52,35 +56,26 @@ public void buildRecords() { public BuiltRecord getTargetPosAndRot(BindingTarget target, Matrix3f normal, Vector3f position) { return records.stream().map(record -> { if (!record.textureId().contains(target.textureId)) return null; - Vec3d forward = getPrimitive(record, target.forwardU, target.forwardV)[0].normal().normalize(); - Vec3d left = getPrimitive(record, target.upwardU, target.upwardV)[0].normal().crossProduct(forward).normalize(); + Vec3 forward = getPrimitive(record, target.forwardU, target.forwardV)[0].normal().normalize(); + Vec3 left = getPrimitive(record, target.upwardU, target.upwardV)[0].normal().cross(forward).normalize(); Vertex[] face = getPrimitive(record, target.posU, target.posV); - if (face[0].normal().equals(Vec3d.ZERO) && forward.equals(Vec3d.ZERO) && left.equals(Vec3d.ZERO)) return null; - normal.set(left.toVector3f(), forward.crossProduct(left).toVector3f(), forward.toVector3f()); - Vec3d center = getPos(face, target.posU, target.posV); - if (!Double.isFinite(center.lengthSquared())) return null; + if (face[0].normal().equals(Vec3.ZERO) && forward.equals(Vec3.ZERO) && left.equals(Vec3.ZERO)) return null; + normal.set(left.toVector3f(), forward.cross(left).toVector3f(), forward.toVector3f()); + Vec3 center = getPos(face, target.posU, target.posV); + if (!Double.isFinite(center.lengthSqr())) return null; position.set((float) target.getOffsetZ(), (float) target.getOffsetY(), (float) target.getOffsetX()).mul(normal).add(center.toVector3f()); return record; }).filter(Objects::nonNull).findAny().orElse(null); } - public void drawByAnother(VertexConsumerProvider anotherProvider, Predicate predicate, Function function) { - records.forEach(record -> { - if (!predicate.test(record)) return; - VertexConsumer buffer = anotherProvider.getBuffer(record.renderLayer); - if (record.distinct) { - Vertex[][] primitives = function.apply(record); - for (Vertex[] primitive : primitives) for (Vertex vertex : primitive) vertex.apply(buffer); - } else { - for (Vertex vertex : record.vertices) vertex.apply(buffer); - } - }); + public void forEachRecord(Consumer consumer) { + records.forEach(consumer); } @Override - public VertexConsumer getBuffer(RenderLayer renderLayer) { - if (recordStack.isEmpty() || !Objects.equals(recordStack.peek().renderLayer, renderLayer) || !renderLayer.areVerticesNotShared()) { - return recordStack.push(new VertexRecord(renderLayer)); + public @NotNull VertexConsumer getBuffer(RenderType renderType) { + if (recordStack.isEmpty() || !Objects.equals(recordStack.peek().renderType, renderType) || !renderType.canConsolidateConsecutiveGeometry()) { + return recordStack.push(new VertexRecord(renderType)); } return recordStack.peek(); } @@ -88,73 +83,73 @@ public VertexConsumer getBuffer(RenderLayer renderLayer) { private static class VertexRecord implements VertexConsumer { private static final Pattern textureIdPattern = Pattern.compile("texture\\[Optional\\[(.*?)]"); private final List vertices = new ArrayList<>(); - private final RenderLayer renderLayer; - private Vec3d pos = Vec3d.ZERO, normal = Vec3d.ZERO; + private final RenderType renderType; + private final Vector3f pos = new Vector3f(), normal = new Vector3f(); private int argb, overlay, light; private float u, v; - VertexRecord(RenderLayer renderLayer) { - this.renderLayer = renderLayer; + VertexRecord(RenderType renderType) { + this.renderType = renderType; } private BuiltRecord build() { - String layerName = renderLayer.toString(); + String layerName = renderType.toString(); Matcher matcher = textureIdPattern.matcher(layerName); String textureId = matcher.find() ? matcher.group(1) : layerName; Vertex[] vertices = this.vertices.toArray(Vertex[]::new); - VertexFormat.DrawMode drawMode = renderLayer.getDrawMode(); - final int primitiveLength = drawMode.firstVertexCount, primitiveStride = drawMode.additionalVertexCount; + VertexFormat.Mode drawMode = renderType.mode(); + final int primitiveLength = drawMode.primitiveLength, primitiveStride = drawMode.primitiveStride; final int primitiveCount = (vertices.length - primitiveLength) / primitiveStride + 1; - final boolean startWithFirst = drawMode == VertexFormat.DrawMode.TRIANGLE_FAN; + final boolean startWithFirst = drawMode == VertexFormat.Mode.TRIANGLE_FAN; Vertex[][] primitives = new Vertex[primitiveCount][primitiveLength]; for (int i = 0, k = 0; i < primitiveCount; i++, k += primitiveStride) { primitives[i][0] = vertices[startWithFirst ? 0 : k]; System.arraycopy(vertices, k + 1, primitives[i], 1, primitiveLength - 1); } - return new BuiltRecord(renderLayer, textureId, vertices, primitives, primitiveLength, primitiveLength == primitiveStride); + return new BuiltRecord(renderType, textureId, vertices, primitives); } @Override - public VertexConsumer vertex(double x, double y, double z) { - pos = new Vec3d(x, y, z); + public @NotNull VertexConsumer vertex(double x, double y, double z) { + pos.set(x, y, z); return this; } @Override - public VertexConsumer color(int red, int green, int blue, int alpha) { + public @NotNull VertexConsumer color(int red, int green, int blue, int alpha) { argb = alpha << 24 | red << 16 | green << 8 | blue; return this; } @Override - public VertexConsumer texture(float u, float v) { + public @NotNull VertexConsumer uv(float u, float v) { this.u = u; this.v = v; return this; } @Override - public VertexConsumer overlay(int u, int v) { + public @NotNull VertexConsumer overlayCoords(int u, int v) { overlay = (short) u | (short) v << 16; return this; } @Override - public VertexConsumer light(int u, int v) { + public @NotNull VertexConsumer uv2(int u, int v) { light = (short) u | (short) v << 16; return this; } @Override - public VertexConsumer normal(float x, float y, float z) { - normal = new Vec3d(x, y, z); + public @NotNull VertexConsumer normal(float x, float y, float z) { + normal.set(x, y, z); return this; } @Override - public void next() { - vertices.add(new Vertex(pos.getX(), pos.getY(), pos.getZ(), argb, u, v, overlay, light, (float) normal.getX(), (float) normal.getY(), (float) normal.getZ())); - pos = normal = Vec3d.ZERO; + public void endVertex() { + vertices.add(new Vertex(pos.x(), pos.y(), pos.z(), argb, u, v, overlay, light, normal.x(), normal.y(), normal.z())); + pos.set(normal.set(0)); u = v = overlay = light = argb = 0; } @@ -165,33 +160,51 @@ public void vertex(float x, float y, float z, float red, float green, float blue } @Override - public void fixedColor(int red, int green, int blue, int alpha) { + public void defaultColor(int red, int green, int blue, int alpha) { } @Override - public void unfixColor() { + public void unsetDefaultColor() { + } + + @Override + public @NotNull VertexConsumer color(int argb) { + this.argb = argb; + return this; + } + + @Override + public @NotNull VertexConsumer overlayCoords(int overlay) { + this.overlay = overlay; + return this; + } + + @Override + public @NotNull VertexConsumer uv2(int light) { + this.light = light; + return this; } } - public record BuiltRecord(RenderLayer renderLayer, String textureId, Vertex[] vertices, Vertex[][] primitives, int primitiveLength, boolean distinct) {} + public record BuiltRecord(RenderType renderType, String textureId, Vertex[] vertices, Vertex[][] primitives) {} - public record Vertex(double x, double y, double z, int argb, float u, float v, int overlay, int light, float normalX, float normalY, float normalZ) { - public Vec3d pos() { - return new Vec3d(x, y, z); + public record Vertex(float x, float y, float z, int argb, float u, float v, int overlay, int light, float normalX, float normalY, float normalZ) { + public Vec3 pos() { + return new Vec3(x, y, z); } - public Vec3d normal() { - return new Vec3d(normalX, normalY, normalZ); + public Vec3 normal() { + return new Vec3(normalX, normalY, normalZ); } public Vertex transform(Matrix4f positionMatrix, Matrix3f normalMatrix) { - Vector3f pos = new Vector3f((float) x, (float) y, (float) z).mulPosition(positionMatrix); + Vector3f pos = new Vector3f(x, y, z).mulPosition(positionMatrix); Vector3f normal = new Vector3f(normalX, normalY, normalZ).mul(normalMatrix); return new Vertex(pos.x(), pos.y(), pos.z(), argb, u, v, overlay, light, normal.x(), normal.y(), normal.z()); } - public void apply(VertexConsumer buffer) { - buffer.vertex((float) x, (float) y, (float) z, + public void render(VertexConsumer buffer) { + buffer.vertex(x, y, z, (float) (argb >> 16 & 0xFF) / 255, (float) (argb >> 8 & 0xFF) / 255, (float) (argb & 0xFF) / 255, (float) (argb >> 24) / 255, u, v, overlay, light, normalX, normalY, normalZ); } diff --git a/common/src/main/resources/realcamera-common.mixins.json b/common/src/main/resources/realcamera-common.mixins.json index f73975b..f0c8eb8 100644 --- a/common/src/main/resources/realcamera-common.mixins.json +++ b/common/src/main/resources/realcamera-common.mixins.json @@ -2,19 +2,19 @@ "required": true, "minVersion": "0.8.5", "package": "com.xtracr.realcamera.mixin", - "compatibilityLevel": "JAVA_17", + "compatibilityLevel": "JAVA_21", "mixins": [ ], "client": [ "CameraAccessor", "MixinCamera", - "MixinClientPlayerEntity", "MixinGameRenderer", - "MixinHeldItemRenderer", - "MixinInGameHud", + "MixinGui", "MixinItem", - "MixinStuckObjectsFeatureRenderer", - "MixinWorldRenderer" + "MixinItemInHandRenderer", + "MixinLevelRenderer", + "MixinLocalPlayer", + "MixinStuckInBodyLater" ], "server": [ ], diff --git a/fabric/src/main/java/com/xtracr/realcamera/EventHandler.java b/fabric/src/main/java/com/xtracr/realcamera/EventHandler.java index 0bc65ef..6f9d84f 100644 --- a/fabric/src/main/java/com/xtracr/realcamera/EventHandler.java +++ b/fabric/src/main/java/com/xtracr/realcamera/EventHandler.java @@ -3,13 +3,12 @@ import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.util.CrosshairUtil; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; public class EventHandler { public static void onWorldRenderStart(WorldRenderContext context) { if (ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { - CrosshairUtil.update(MinecraftClient.getInstance(), context.camera(), - context.matrixStack().peek().getPositionMatrix(), context.projectionMatrix()); + CrosshairUtil.update(Minecraft.getInstance(), context.camera(), context.matrixStack().last().pose(), context.projectionMatrix()); } } } diff --git a/fabric/src/main/java/com/xtracr/realcamera/mixin/GameRendererEvents.java b/fabric/src/main/java/com/xtracr/realcamera/mixin/GameRendererEvents.java index 8f2378f..dbfe36d 100644 --- a/fabric/src/main/java/com/xtracr/realcamera/mixin/GameRendererEvents.java +++ b/fabric/src/main/java/com/xtracr/realcamera/mixin/GameRendererEvents.java @@ -1,9 +1,9 @@ package com.xtracr.realcamera.mixin; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; import com.xtracr.realcamera.RealCameraCore; -import net.minecraft.client.render.GameRenderer; -import net.minecraft.client.util.math.MatrixStack; -import net.minecraft.util.math.RotationAxis; +import net.minecraft.client.renderer.GameRenderer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -11,10 +11,10 @@ @Mixin(GameRenderer.class) public abstract class GameRendererEvents { - @Inject(method = "renderWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V", shift = At.Shift.AFTER)) - private void realcamera$onAfterCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) { + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setup(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/world/entity/Entity;ZZF)V", shift = At.Shift.AFTER)) + private void realcamera$onAfterCameraUpdate(float tickDelta, long limitTime, PoseStack poseStack, CallbackInfo cInfo) { if (RealCameraCore.isActive()) { - matrixStack.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(RealCameraCore.getRoll(0))); + poseStack.mulPose(Axis.ZP.rotationDegrees(RealCameraCore.getRoll(0))); } } } diff --git a/forge/src/main/java/com/xtracr/realcamera/EventHandler.java b/forge/src/main/java/com/xtracr/realcamera/EventHandler.java index 89a39ff..474a832 100644 --- a/forge/src/main/java/com/xtracr/realcamera/EventHandler.java +++ b/forge/src/main/java/com/xtracr/realcamera/EventHandler.java @@ -2,31 +2,26 @@ import com.xtracr.realcamera.config.ConfigFile; import com.xtracr.realcamera.util.CrosshairUtil; -import net.minecraft.client.MinecraftClient; -import net.minecraftforge.client.event.InputEvent.Key; +import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.RenderLevelStageEvent; import net.minecraftforge.client.event.ViewportEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.event.TickEvent; public class EventHandler { - @SubscribeEvent - public static void onKeyInput(Key event) { - KeyBindings.handle(MinecraftClient.getInstance()); + public static void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase == TickEvent.Phase.END) KeyBindings.handle(Minecraft.getInstance()); } - @SubscribeEvent - public static void onCameraUpdate(ViewportEvent.ComputeCameraAngles event) { + public static void onCameraSetup(ViewportEvent.ComputeCameraAngles event) { if (RealCameraCore.isActive()) { event.setRoll(RealCameraCore.getRoll(event.getRoll())); } } - @SubscribeEvent - public static void onRenderWorldStage(RenderLevelStageEvent event) { + public static void onRenderLevelStage(RenderLevelStageEvent event) { if (RenderLevelStageEvent.Stage.AFTER_SKY.equals(event.getStage())) { if (ConfigFile.config().dynamicCrosshair() && RealCameraCore.isActive()) { - CrosshairUtil.update(MinecraftClient.getInstance(), event.getCamera(), - event.getPoseStack().peek().getPositionMatrix(), event.getProjectionMatrix()); + CrosshairUtil.update(Minecraft.getInstance(), event.getCamera(), event.getPoseStack().last().pose(), event.getProjectionMatrix()); } } } diff --git a/forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java b/forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java index a743fad..ac2e4c0 100644 --- a/forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java +++ b/forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java @@ -6,7 +6,6 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; @@ -21,13 +20,12 @@ public RealCameraForge() { eventBus.addListener(this::onKeyRegister); } - @SubscribeEvent public void clientSetup(FMLClientSetupEvent event) { RealCamera.initialize(); - MinecraftForge.EVENT_BUS.addListener(EventHandler::onKeyInput); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, EventHandler::onCameraUpdate); - MinecraftForge.EVENT_BUS.addListener(EventHandler::onRenderWorldStage); + MinecraftForge.EVENT_BUS.addListener(EventHandler::onClientTick); + MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, EventHandler::onCameraSetup); + MinecraftForge.EVENT_BUS.addListener(EventHandler::onRenderLevelStage); if (ModList.get().isLoaded("cloth_config")) { ModLoadingContext.get().registerExtensionPoint(ConfigScreenFactory.class, @@ -35,7 +33,6 @@ public void clientSetup(FMLClientSetupEvent event) { } } - @SubscribeEvent public void onKeyRegister(RegisterKeyMappingsEvent event) { KeyBindings.register(event::register); } diff --git a/gradle.properties b/gradle.properties index ef9aa6d..094e41c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,14 +4,14 @@ org.gradle.parallel=true # Loader Properties minecraft_version=1.20.1 enabled_platforms=fabric,forge -forge_version=1.20.1-47.2.30 +forge_version=1.20.1-47.3.1 fabric_loader_version=0.15.10 -yarn_mappings=1.20.1+build.10 +#yarn_mappings=1.20.1+build.10 # Mod Properties mod_version=0.6.1-beta maven_group=com.xtracr.realcamera archives_base_name=realcamera # Dependencies -fabric_api_version=0.92.0+1.20.1 +fabric_api_version=0.92.2+1.20.1 cloth_config_version=11.1.118 -modmenu_version=7.1.0 +modmenu_version=7.2.2 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a80b22c..b82aa23 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew.bat b/gradlew.bat index 93e3f59..25da30d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail