diff --git a/build.gradle b/build.gradle index ec5e58e..dd97cef 100644 --- a/build.gradle +++ b/build.gradle @@ -68,6 +68,7 @@ dependencies { modCompileOnly("maven.modrinth:iris:kuOV4Ece") modCompileOnly("maven.modrinth:bobby:2cuVyTav") modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I") + modCompileOnly("maven.modrinth:replaymod:NtlpUQgI") modImplementation("maven.modrinth:modmenu:xhN1IvHi") // modCompileOnly("maven.modrinth:axiom:D3uDJmiB") diff --git a/src/main/java/com/moulberry/flashback/CachedChunkPacket.java b/src/main/java/com/moulberry/flashback/CachedChunkPacket.java index 3e1e94c..08694e0 100644 --- a/src/main/java/com/moulberry/flashback/CachedChunkPacket.java +++ b/src/main/java/com/moulberry/flashback/CachedChunkPacket.java @@ -14,14 +14,18 @@ import java.util.Arrays; import java.util.Comparator; public class CachedChunkPacket { + private final int x; + private final int z; private final byte[] bigHash; private final int hashCode; public int index; public CachedChunkPacket(ClientboundLevelChunkWithLightPacket packet, int index) { - this.index = index; + this.x = packet.getX(); + this.z = packet.getZ(); this.bigHash = computePacketBigHash(packet); this.hashCode = Arrays.hashCode(this.bigHash); + this.index = index; } private static byte[] computePacketBigHash(ClientboundLevelChunkWithLightPacket packet) { @@ -29,13 +33,19 @@ public class CachedChunkPacket { try { digest = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); + try { + digest = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e2) { + throw new RuntimeException(e2); + } } + digest.update(intToByteArray(packet.getX())); digest.update(intToByteArray(packet.getZ())); digest.update(packet.getChunkData().buffer); FriendlyByteBuf frenBuffer = new FriendlyByteBuf(Unpooled.buffer()); + packet.lightData.write(frenBuffer); digest.update(frenBuffer.array(), 0, frenBuffer.writerIndex()); frenBuffer.resetWriterIndex(); @@ -44,11 +54,12 @@ public class CachedChunkPacket { digest.update(frenBuffer.array(), 0, frenBuffer.writerIndex()); frenBuffer.resetWriterIndex(); - //Ensure stable ordering + // Sort to ensure stable ordering var copy = new ArrayList<>(packet.getChunkData().blockEntitiesData); - copy.sort(Comparator.comparing(a->a.y^a.packedXZ)); + copy.sort(Comparator.comparingInt(a -> (a.y << 8) | a.packedXZ)); + for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesData : copy) { - digest.update(intToByteArray(blockEntitiesData.packedXZ)); + digest.update((byte) blockEntitiesData.packedXZ); digest.update(intToByteArray(blockEntitiesData.y)); digest.update(BlockEntityType.getKey(blockEntitiesData.type).toString().getBytes(StandardCharsets.UTF_8)); if (blockEntitiesData.tag != null) { @@ -83,6 +94,9 @@ public class CachedChunkPacket { if (this.hashCode() != that.hashCode()) { return false; } + if (this.x != that.x || this.z != that.z) { + return false; + } return Arrays.compare(this.bigHash, that.bigHash) == 0; } diff --git a/src/main/java/com/moulberry/flashback/EnhancedFlight.java b/src/main/java/com/moulberry/flashback/EnhancedFlight.java new file mode 100644 index 0000000..b197280 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/EnhancedFlight.java @@ -0,0 +1,93 @@ +package com.moulberry.flashback; + +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.state.EditorState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +import java.util.function.Consumer; + +public class EnhancedFlight { + + public static float getFlightSpeed(LocalPlayer player, FlashbackConfig config) { + float momentum = (float) Math.sqrt(config.flightMomentum); + float sprintMult = Mth.lerp(momentum, 2.5f, 2.0f); + float baseMult = Mth.lerp(momentum, 10f, 1.0f); + + float sprintMultiplier = Minecraft.getInstance().options.keySprint.isDown() || player.isSprinting() ? sprintMult : 1f; + return player.getAbilities().getFlyingSpeed() * sprintMultiplier * baseMult; + } + + public static void doFlight(LocalPlayer player, FlashbackConfig config, Vec3 movementInput, float flyingSpeed, Consumer superTravel) { + boolean cameraDirection = config.flightCameraDirection; + + boolean originalHasNoGravity = player.isNoGravity(); + double oldX = player.getX(); + double oldY = player.getY(); + double oldZ = player.getZ(); + + if (cameraDirection) { + double sin = -Math.sin(Math.toRadians(player.getXRot())); + double cos = Math.cos(Math.toRadians(player.getXRot())); + + movementInput = new Vec3(movementInput.x, sin*movementInput.z, cos*movementInput.z); + + player.setNoGravity(true); + } + + float movementY = 0; + if (player.input.shiftKeyDown) movementY -= 1; + if (player.input.jumping) movementY += 1; + if (movementY != 0) { + player.move(MoverType.SELF, new Vec3(0, flyingSpeed * movementY * 0.98, 0)); + + if (movementY < 0 && !Minecraft.getInstance().gameMode.isAlwaysFlying()) { + double expectedY = oldY + flyingSpeed * movementY * 0.98; + if (Math.abs(player.getY() - expectedY) > 1E-5) { + player.setOnGround(true); + player.getAbilities().flying = false; + player.onUpdateAbilities(); + } + } + } + + double beforeY = player.getDeltaMovement().y; + superTravel.accept(movementInput); + + double momentum = Math.cbrt(config.flightMomentum); + Vector3f deltaMovement = player.getDeltaMovement().toVector3f(); + + if (config.flightLockX) { + player.setPos(oldX, player.getY(), player.getZ()); + deltaMovement.x = 0.0f; + } + if (config.flightLockY) { + player.setPos(player.getX(), oldY, player.getZ()); + deltaMovement.y = 0.0f; + } + if (config.flightLockZ) { + player.setPos(player.getX(), player.getY(), oldZ); + deltaMovement.z = 0.0f; + } + + if (cameraDirection) { + player.setDeltaMovement(deltaMovement.x * momentum, deltaMovement.y * 0.92857 * momentum, deltaMovement.z * momentum); + } else { + player.setDeltaMovement(deltaMovement.x * momentum, beforeY * 0.6 * momentum, deltaMovement.z * momentum); + } + + if (cameraDirection && movementY >= 0) { + player.setOnGround(false); + } + + + player.setNoGravity(originalHasNoGravity); + player.resetFallDistance(); + if (player.isFallFlying()) player.stopFallFlying(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java index e479385..601ef6d 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java @@ -23,7 +23,9 @@ public enum VideoCodec implements ComboOption { AV1("AV1", avcodec.AV_CODEC_ID_AV1), VP9("VP9", avcodec.AV_CODEC_ID_VP9), PRO_RES("Apple ProRes", avcodec.AV_CODEC_ID_PRORES), - QUICK_TIME("QuickTime", avcodec.AV_CODEC_ID_QTRLE); + QUICK_TIME("QuickTime", avcodec.AV_CODEC_ID_QTRLE), + WEBP("WebP", AV_CODEC_ID_WEBP), + GIF("GIF", AV_CODEC_ID_GIF); private final String text; private final int codecId; diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java b/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java index ea0063a..f09b8b1 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java @@ -12,7 +12,10 @@ public enum VideoContainer implements ComboOption { MP4("MP4", "mp4"), MKV("MKV", "mkv"), AVI("AVI", "avi"), - MOV("MOV", "mov"); + MOV("MOV", "mov"), + WEBP("WebP", "webp"), + WEBM("WebM", "webm"), + GIF("GIF", "gif"); private final String text; private final String extension; diff --git a/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java index 360600f..3ab99f2 100644 --- a/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java +++ b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java @@ -5,14 +5,19 @@ import com.moulberry.flashback.packet.FlashbackVoiceChatSound; import de.maxhenkel.voicechat.api.events.ClientReceiveSoundEvent; import de.maxhenkel.voicechat.api.events.ClientSoundEvent; import de.maxhenkel.voicechat.voice.client.ClientManager; +import net.minecraft.client.Minecraft; import net.minecraft.world.phys.Vec3; import java.util.UUID; public class SimpleVoiceChatRecorder { + private static boolean shouldWritePacket() { + return Flashback.RECORDER != null && Flashback.RECORDER.readyToWrite() && Flashback.getConfig().recordVoiceChat; + } + public static void onReceiveEntitySound(ClientReceiveSoundEvent.EntitySound event) { - if (Flashback.RECORDER == null) { + if (!shouldWritePacket()) { return; } @@ -21,7 +26,7 @@ public class SimpleVoiceChatRecorder { } public static void onReceiveLocationalSound(ClientReceiveSoundEvent.LocationalSound event) { - if (Flashback.RECORDER == null) { + if (!shouldWritePacket()) { return; } @@ -31,7 +36,7 @@ public class SimpleVoiceChatRecorder { } public static void onReceiveStaticSound(ClientReceiveSoundEvent.StaticSound event) { - if (Flashback.RECORDER == null) { + if (!shouldWritePacket()) { return; } @@ -40,7 +45,7 @@ public class SimpleVoiceChatRecorder { } public static void onSendSound(ClientSoundEvent event) { - if (Flashback.RECORDER == null) { + if (!shouldWritePacket()) { return; } @@ -58,14 +63,14 @@ public class SimpleVoiceChatRecorder { } private static void submitSoundPacket(FlashbackVoiceChatSound soundPacket) { - if (!Flashback.getConfig().recordVoiceChat) { - return; - } - - Flashback.RECORDER.submitCustomTask(writer -> { - writer.startAction(ActionSimpleVoiceChatSound.INSTANCE); - FlashbackVoiceChatSound.STREAM_CODEC.encode(writer.friendlyByteBuf(), soundPacket); - writer.finishAction(ActionSimpleVoiceChatSound.INSTANCE); + Minecraft.getInstance().submit(() -> { + if (shouldWritePacket()) { + Flashback.RECORDER.submitCustomTask(writer -> { + writer.startAction(ActionSimpleVoiceChatSound.INSTANCE); + FlashbackVoiceChatSound.STREAM_CODEC.encode(writer.friendlyByteBuf(), soundPacket); + writer.finishAction(ActionSimpleVoiceChatSound.INSTANCE); + }); + } }); } diff --git a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java index 185ed7b..e377e20 100644 --- a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java +++ b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java @@ -66,6 +66,14 @@ public class FlashbackConfig { public Set openedWindows = new HashSet<>(); public long nextUnsupportedModLoaderWarning = 0; + public boolean flightCameraDirection = false; + public float flightMomentum = 1.0f; + public boolean flightLockX = false; + public boolean flightLockY = false; + public boolean flightLockZ = false; + public boolean flightLockYaw = false; + public boolean flightLockPitch = false; + @SuppressWarnings("unchecked") public OptionInstance[] createOptionInstances() { List> options = new ArrayList<>(); diff --git a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java index 165d6bf..ebc101e 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java @@ -23,6 +23,7 @@ import imgui.flag.ImGuiMouseCursor; import imgui.flag.ImGuiNavInput; import imgui.flag.ImGuiViewportFlags; import imgui.lwjgl3.glfw.ImGuiImplGlfwNative; +import net.minecraft.client.KeyMapping; import net.minecraft.client.Minecraft; import net.minecraft.world.phys.Vec2; import org.lwjgl.PointerBuffer; @@ -127,9 +128,7 @@ public class CustomImGuiImplGlfw { private final double[] grabbedOriginalMouseX = new double[1]; private final double[] grabbedOriginalMouseY = new double[1]; private int grabLinkedKey = -1; - - private List interframeMousePositions = new ArrayList<>(); - private List capturedInterframeMousePositions = new ArrayList<>(); + private boolean releaseGrabOnUp = false; public float contentScale = 1.0f; @@ -168,7 +167,7 @@ public class CustomImGuiImplGlfw { GLFW.glfwSetCursorPos(this.mainWindowPtr, this.grabbedOriginalMouseX[0], this.grabbedOriginalMouseY[0]); } - public void setGrabbed(boolean passthroughToGame, int grabLinkedKey, double x, double y) { + public void setGrabbed(boolean passthroughToGame, int grabLinkedKey, boolean releaseGrabOnUp, double x, double y) { if (grabLinkedKey != 0) { if (grabLinkedKey < 0) { if (GLFW.glfwGetMouseButton(this.mainWindowPtr, -grabLinkedKey-1) == GLFW_RELEASE) { @@ -185,6 +184,7 @@ public class CustomImGuiImplGlfw { if (grabLinkedKey != 0) { this.grabLinkedKey = grabLinkedKey; + this.releaseGrabOnUp = releaseGrabOnUp; } if (x >= 0 && y >= 0) { this.grabbedOriginalMouseX[0] = x; @@ -232,8 +232,10 @@ public class CustomImGuiImplGlfw { return; } - if (this.grabbed != null && action == GLFW_RELEASE && this.grabLinkedKey < 0 && button == -this.grabLinkedKey-1) { - this.ungrab(); + if (this.grabbed != null && this.grabLinkedKey < 0 && button == -this.grabLinkedKey-1) { + if ((action == GLFW_RELEASE) == this.releaseGrabOnUp) { + this.ungrab(); + } } MouseHandledBy handledBy = this.getMouseHandledBy(); @@ -260,7 +262,7 @@ public class CustomImGuiImplGlfw { this.io.setMouseWheelH(this.io.getMouseWheelH() + (float) xOffset); this.io.setMouseWheel(this.io.getMouseWheel() + (float) yOffset); - if (Minecraft.getInstance().screen == null || !ReplayUI.isMainFrameHovered()) { + if (Minecraft.getInstance().screen == null || !ReplayUI.isMainFrameActive()) { return; } } @@ -328,27 +330,46 @@ public class CustomImGuiImplGlfw { } } - if (action != GLFW_RELEASE && GLFW.glfwGetKey(windowId, GLFW_KEY_F3) != GLFW_RELEASE) { + boolean forcePassToGame = action != GLFW_RELEASE && ((key == GLFW_KEY_ESCAPE && !io.getWantTextInput() && !ReplayUI.hasAnyPopupOpen) || + (key >= GLFW_KEY_F1 && key <= GLFW_KEY_F25) || GLFW.glfwGetKey(windowId, GLFW_KEY_F3) != GLFW_RELEASE); + if (forcePassToGame) { this.prevUserCallbackKey.invoke(windowId, minecraftKey, scancode, action, mods); - if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE; + if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = true; return; } - boolean passToMinecraft = (ReplayUI.isMainFrameHovered() && this.io.getMouseDown(ImGuiMouseButton.Left) || !this.io.getWantCaptureKeyboard()) && !this.io.getWantTextInput(); + boolean passToMinecraft = false; + boolean passToImGui = false; if (action == GLFW_RELEASE) { - if (keyInBoundsForGame && this.keyPressedGame[minecraftKey]) passToMinecraft = true; - } else if (passToMinecraft) { -// out: -// for (KeybindCategory category : Keybinds.categories) { -// if (!category.preventPassToGame()) continue; -// for (Keybind keybind : category.keybinds()) { -// if (keybind.wouldBePressed(key, shiftMod, ctrlMod, altMod, superMod)) { -// passToMinecraft = false; -// break out; -// } -// } -// } + if (keyInBoundsForGame && this.keyPressedGame[minecraftKey]) { + passToMinecraft = true; + } + if (key >= 0 && key < this.keyOwnerWindows.length) { + passToImGui = true; + } + } else { + if (io.getWantTextInput()) { + passToMinecraft = false; + } else if (this.grabbed == MouseHandledBy.GAME) { + passToMinecraft = true; + } else if (ReplayUI.isMainFrameActive()) { + for (KeyMapping keyMapping : Minecraft.getInstance().options.keyMappings) { + if (keyMapping.matches(key, scancode)) { + passToMinecraft = true; + break; + } + } + } else if (Minecraft.getInstance().options.keyUp.matches(key, scancode) || + Minecraft.getInstance().options.keyLeft.matches(key, scancode) || + Minecraft.getInstance().options.keyDown.matches(key, scancode) || + Minecraft.getInstance().options.keyRight.matches(key, scancode) || + Minecraft.getInstance().options.keyChat.matches(key, scancode) || + Minecraft.getInstance().options.keyCommand.matches(key, scancode)) { + passToMinecraft = true; + } + + passToImGui = !passToMinecraft; } if (passToMinecraft && this.prevUserCallbackKey != null && windowId == this.mainWindowPtr) { @@ -356,7 +377,7 @@ public class CustomImGuiImplGlfw { if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE; } - if (key >= 0 && key < this.keyOwnerWindows.length) { + if (passToImGui && key >= 0 && key < this.keyOwnerWindows.length) { if (action == GLFW_PRESS || action == GLFW_REPEAT) { io.setKeysDown(key, true); this.keyOwnerWindows[key] = windowId; @@ -392,8 +413,6 @@ public class CustomImGuiImplGlfw { if (handledBy == MouseHandledBy.EDITOR_GRABBED) { grabbedCurrMouseX = xpos; grabbedCurrMouseY = ypos; - } else { - this.interframeMousePositions.add(new Vec2((float)xpos, (float)ypos)); } } @@ -444,7 +463,7 @@ public class CustomImGuiImplGlfw { return; } - if (!this.io.getWantCaptureKeyboard() && this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) { + if (!this.io.getWantCaptureKeyboard() && !this.io.getWantTextInput() && this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) { this.prevUserCallbackChar.invoke(windowId, c, mods); } @@ -597,38 +616,12 @@ public class CustomImGuiImplGlfw { return true; } - public List getCapturedInterframeMousePositions() { - return this.capturedInterframeMousePositions; - } - /** * Updates {@link ImGuiIO} and {@link org.lwjgl.glfw.GLFW} state. */ public void newFrame() { this.io.ptr = ImGui.getIO().ptr; - if (this.interframeMousePositions.isEmpty()) { - this.capturedInterframeMousePositions.clear(); - } else { - this.capturedInterframeMousePositions = this.interframeMousePositions; - this.interframeMousePositions = new ArrayList<>(); - - if (this.io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { - // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) - long windowPtr = this.mouseWindowPtr; - if (windowPtr == 0) { - windowPtr = this.mainWindowPtr; - } - glfwGetWindowPos(windowPtr, this.windowX, this.windowY); - - List offset = new ArrayList<>(); - for (Vec2 pos : this.capturedInterframeMousePositions) { - offset.add(new Vec2(pos.x + this.windowX[0], pos.y + this.windowY[0])); - } - this.capturedInterframeMousePositions = offset; - } - } - glfwGetWindowSize(this.mainWindowPtr, this.winWidth, this.winHeight); glfwGetFramebufferSize(this.mainWindowPtr, this.fbWidth, this.fbHeight); diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java index b0415a7..cb1019d 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java @@ -6,8 +6,12 @@ import imgui.ImVec2; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiComboFlags; import imgui.flag.ImGuiHoveredFlags; +import imgui.flag.ImGuiInputTextFlags; +import imgui.flag.ImGuiNavInput; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; +import imgui.type.ImFloat; +import imgui.type.ImInt; import imgui.type.ImString; import net.minecraft.Util; import net.minecraft.client.Minecraft; @@ -132,12 +136,21 @@ public class ImGuiHelper { private static StringBuilder specialInput = new StringBuilder(); private static int backspaceCount = 0; + private static boolean handledFocusNext = false; + private static boolean focusNext = false; + private static int focusIndex = 0; + private static int focusLastIndex = 0; + public static void endFrame() { closeableModalOnTopLast = closeableModalOnTop; wantSpecialInputLastFrame = wantSpecialInputThisFrame; wantSpecialInputThisFrame = false; + handledFocusNext = false; + focusNext = false; + focusIndex = 0; + if (!wantSpecialInputLastFrame) specialInput.setLength(0); } @@ -316,6 +329,136 @@ public class ImGuiHelper { ImGui.textColored(ImGui.getColorU32(ImGuiCol.TextDisabled), text); } + public static boolean inputInt(String label, int[] value) { + if (value.length == 0) { + ImGui.text(label); + return false; + } + + boolean valueChanged = false; + float availableWidth = ImGui.calcItemWidth(); + float innerSpacing = ImGui.getStyle().getItemInnerSpacingX(); + float widthItemOne = Math.max(1, (float) Math.floor((availableWidth - innerSpacing * (value.length - 1)) / value.length)); + float widthItemLast = Math.max(1, (float) Math.floor(availableWidth - (widthItemOne + innerSpacing) * (value.length - 1))); + + ImGui.beginGroup(); + ImGui.pushID(label); + for (int i=0; i 0) { + ImGui.sameLine(0, innerSpacing); + } + + ImInt imInt = new ImInt(value[i]); + if (i < value.length-1) { + ImGui.setNextItemWidth(widthItemOne); + } else { + ImGui.setNextItemWidth(widthItemLast); + } + + focusIndex += 1; + + if (focusIndex == focusLastIndex || focusNext) { + ImGui.setKeyboardFocusHere(); + focusNext = false; + focusLastIndex = 0; + } + + if (ImGui.inputInt("", imInt, 0)) { + valueChanged = true; + value[i] = imInt.get(); + } + + if (!handledFocusNext && ImGui.isItemActive() && ImGui.isKeyPressed(GLFW.GLFW_KEY_TAB, false)) { + handledFocusNext = true; + if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) { + focusLastIndex = focusIndex - 1; + } else { + focusNext = true; + } + } + + ImGui.popID(); + } + ImGui.popID(); + + // Label + String renderedText = label.split("##")[0]; + if (!renderedText.isEmpty()) { + ImGui.sameLine(0, innerSpacing); + ImGui.text(renderedText); + } + + ImGui.endGroup(); + + return valueChanged; + } + + public static boolean inputFloat(String label, float[] value) { + if (value.length == 0) { + ImGui.text(label); + return false; + } + + boolean valueChanged = false; + float availableWidth = ImGui.calcItemWidth(); + float innerSpacing = ImGui.getStyle().getItemInnerSpacingX(); + float widthItemOne = Math.max(1, (float) Math.floor((availableWidth - innerSpacing * (value.length - 1)) / value.length)); + float widthItemLast = Math.max(1, (float) Math.floor(availableWidth - (widthItemOne + innerSpacing) * (value.length - 1))); + + ImGui.beginGroup(); + ImGui.pushID(label); + for (int i=0; i 0) { + ImGui.sameLine(0, innerSpacing); + } + + ImFloat imFloat = new ImFloat(value[i]); + if (i < value.length-1) { + ImGui.setNextItemWidth(widthItemOne); + } else { + ImGui.setNextItemWidth(widthItemLast); + } + + focusIndex += 1; + + if (focusIndex == focusLastIndex || focusNext) { + ImGui.setKeyboardFocusHere(); + focusNext = false; + focusLastIndex = 0; + } + + if (ImGui.inputFloat("", imFloat, 0)) { + valueChanged = true; + value[i] = imFloat.get(); + } + + if (!handledFocusNext && ImGui.isItemActive() && ImGui.isKeyPressed(GLFW.GLFW_KEY_TAB, false)) { + handledFocusNext = true; + if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) { + focusLastIndex = focusIndex - 1; + } else { + focusNext = true; + } + } + + ImGui.popID(); + } + ImGui.popID(); + + // Label + String renderedText = label.split("##")[0]; + if (!renderedText.isEmpty()) { + ImGui.sameLine(0, innerSpacing); + ImGui.text(renderedText); + } + + ImGui.endGroup(); + + return valueChanged; + } + public static boolean radio(String label, int[] currentItem, String[] values) { int item = currentItem[0]; int newItem = -1; diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java index 480d8ff..5c9ed7f 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java @@ -5,6 +5,7 @@ import com.mojang.blaze3d.platform.TextureUtil; import com.mojang.blaze3d.platform.Window; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.editor.ui.windows.ExportQueueWindow; +import com.moulberry.flashback.editor.ui.windows.MovementWindow; import com.moulberry.flashback.editor.ui.windows.PlayerListWindow; import com.moulberry.flashback.editor.ui.windows.SelectedEntityPopup; import com.moulberry.flashback.state.EditorState; @@ -25,7 +26,6 @@ import net.minecraft.client.gui.screens.ProgressScreen; import net.minecraft.client.gui.screens.ReceivingLevelScreen; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; @@ -55,6 +55,7 @@ public class ReplayUI { private static final CustomImGuiImplGl3 imguiGl3 = new CustomImGuiImplGl3(); private static boolean initialized = false; + private static boolean isFrameFocused = false; private static boolean isFrameHovered = false; public static int frameX = 0; public static int frameY = 0; @@ -64,6 +65,10 @@ public class ReplayUI { public static int viewportSizeY = 1; private static boolean activeLastFrame = false; + private static int focusMainWindowCounter = 0; + + public static boolean hasAnyPopupOpen = false; + public static Matrix4f lastProjectionMatrix = null; public static Quaternionf lastViewQuaternion = null; @@ -126,7 +131,7 @@ public class ReplayUI { Path relativePath = FabricLoader.getInstance().getGameDir().relativize(path); ImGui.getIO().setIniFilename(relativePath.toString()); - ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); + // ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); ImGui.getIO().addConfigFlags(ImGuiConfigFlags.DockingEnable); // ImGui.getIO().addConfigFlags(ImGuiConfigFlags.ViewportsEnable); ImGui.getIO().setConfigMacOSXBehaviors(Minecraft.ON_OSX); @@ -486,6 +491,7 @@ public class ReplayUI { if (!isActiveInternal()) { transitionActiveState(false); imguiGlfw.updateReleaseAllKeys(true); + focusMainWindowCounter = 5; return; } else { imguiGlfw.updateReleaseAllKeys(false); @@ -513,14 +519,16 @@ public class ReplayUI { imguiGlfw.newFrame(); ImGui.newFrame(); - navClose = ImGui.getIO().getNavInputs(ImGuiNavInput.Cancel) != 0; + hasAnyPopupOpen = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup); + + navClose = hasAnyPopupOpen && ImGui.getIO().getNavInputs(ImGuiNavInput.Cancel) != 0.0f; if (wasNavClose != navClose) { wasNavClose = navClose; } else if (wasNavClose) { navClose = false; } - if (ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { + if (hasAnyPopupOpen) { ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); } else { ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); @@ -535,6 +543,7 @@ public class ReplayUI { int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode); imgui.internal.ImGui.dockBuilderGetCentralNode(mainDock).addLocalFlags(imgui.internal.flag.ImGuiDockNodeFlags.NoTabBar); + isFrameFocused = false; isFrameHovered = false; ImGui.setNextWindowDockID(mainDock); ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); @@ -543,6 +552,11 @@ public class ReplayUI { if (ImGui.begin("Main", ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoNavInputs | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoSavedSettings)) { + if (focusMainWindowCounter > 0) { + focusMainWindowCounter -= 1; + ImGui.setWindowFocus(); + } + ImGuiHelper.popStyleVar(); float minX = ImGui.getWindowContentRegionMinX(); @@ -586,6 +600,11 @@ public class ReplayUI { } } + if (ImGui.isWindowFocused()) { + ImGui.getWindowDrawList().addRect(frameX+1, frameY+1, frameX+frameWidth-1, frameY+frameHeight-1, 0xFFC25823); + isFrameFocused = true; + } + if (infoOverlayText != null) { long currentMillis = System.currentTimeMillis(); if (currentMillis < infoOverlayEndMillis - 30000 || currentMillis > infoOverlayEndMillis) { @@ -673,7 +692,9 @@ public class ReplayUI { if (Minecraft.getInstance().screen != null) { ImGui.captureMouseFromApp(false); - } else if (isMovingCamera()) { + } + boolean isMovingCamera = isMovingCamera(); + if (isFrameFocused || isMovingCamera) { LocalPlayer player = Minecraft.getInstance().player; if (player != null) { int wheelY = (int) Math.signum(ImGui.getIO().getMouseWheel()); @@ -685,7 +706,8 @@ public class ReplayUI { player.getAbilities().setFlyingSpeed(flyingSpeed); } } - } else if (ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { + } + if (!isMovingCamera && ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { fireCancelNavInput |= handleBasicInputs(); } } @@ -699,6 +721,7 @@ public class ReplayUI { StartExportWindow.render(); ExportQueueWindow.render(); PlayerListWindow.render(); + MovementWindow.render(); popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup); @@ -723,15 +746,11 @@ public class ReplayUI { transitionActiveState(true); } - public static boolean isMainFrameHovered() { - return isFrameHovered; + public static boolean isMainFrameActive() { + return isFrameFocused; } private static boolean handleBasicInputs() { -// if (ImGui.isMouseClicked(ImGuiMouseButton.Left) && UserAction.LEFT_MOUSE.call(null) == UserAction.ActionResult.USED_STOP) { -// return true; -// } - if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_RIGHT)) { HitResult result = getLookTarget(); if (result instanceof EntityHitResult entityHitResult) { @@ -747,66 +766,11 @@ public class ReplayUI { if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_LEFT)) { int key = -GLFW.GLFW_MOUSE_BUTTON_LEFT-1; if (key != 0) { - imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); + imguiGlfw.setGrabbed(true, key, true, frameX + frameWidth / 2f, frameY + frameHeight / 2f); } return true; } -// if (Keybinds.ADJUST_RADIUS.isPressed(false)) { -// if (ToolManager.isToolActive() && ToolManager.getCurrentTool().initiateAdjustment()) { -// int key = Keybinds.ADJUST_RADIUS.getKey(); -// if (key != 0) { -// imguiGlfw.setGrabbed(false, key, -1, -1); -// } -// -// adjustingTool = true; -// adjustingToolOffsetX = 0; -// adjustingToolOffsetY = 0; -// -// return true; -// } -// } else if (Keybinds.ROTATE_CAMERA.isPressed(false)) { -// movementControls = EditorMovementControls.rotate(); -// return true; -// } else if (Keybinds.PICK_BLOCK.isPressed(false)) { -// RayCaster.RaycastResult result = Tool.raycastBlock(); -// if (result != null) { -// BlockState blockState = Minecraft.getInstance().level.getBlockState(result.blockPos()); -// CustomBlockState customBlockState = ServerCustomBlocks.getCustomStateFor(blockState); -// activeBlockHistory.setActive(Objects.requireNonNullElse(customBlockState, (CustomBlockState) blockState)); -// return true; -// } -// } else if (Keybinds.USE_TOOL.isPressed(false)) { -// if (UserAction.RIGHT_MOUSE.call(null) != UserAction.ActionResult.NOT_HANDLED || ToolManager.isToolActive()) { -// return true; -// } -// } else if (Keybinds.ARCBALL_CAMERA.isPressed(false)) { -// Tool currentTool = ToolManager.isToolActive() ? ToolManager.getCurrentTool() : null; -// if (currentTool instanceof RulerTool || currentTool instanceof ModifyTool || Configuration.keybind.useCenterOfScreenForArcball) { -// movementControls = EditorMovementControls.arcballFromRaycast(); -// if (movementControls != EditorMovementControls.none()) { -// int key = Keybinds.ARCBALL_CAMERA.getKey(); -// if (key != 0) { -// imguiGlfw.setGrabbed(false, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); -// } -// return true; -// } -// } else { -// pendingDepthActions.add(PendingDepthAction.ARCBALL); -// return true; -// } -// } else if (Keybinds.PAN_CAMERA.isPressed(false)) { -// movementControls = EditorMovementControls.pan(); -// return true; -// } - -// if (Keybinds.CROSSHAIR_CAMERA.isPressed(false)) { -// int key = Keybinds.CROSSHAIR_CAMERA.getKey(); -// if (key != 0) { -// imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); -// } -// return true; -// } return false; } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java index bc3db66..8e249d8 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java @@ -15,7 +15,7 @@ public class MainMenuBar { } public static void renderInner() { - if (ImGui.menuItem("Export")) { + if (ImGui.menuItem("Export Video")) { StartExportWindow.open(); } @@ -26,20 +26,31 @@ public class MainMenuBar { } } + ImGui.separator(); + + if (ImGui.menuItem("Player List")) { + toggleWindow("player_list"); + } + if (ImGui.menuItem("Movement")) { + toggleWindow("movement"); + } + + ImGui.separator(); + if (ImGui.menuItem("Hide (F1)")) { Minecraft.getInstance().options.hideGui = true; } + } - if (ImGui.menuItem("Player List")) { - var openedWindows = Flashback.getConfig().openedWindows; - boolean playerListIsOpen = openedWindows.contains("player_list"); - if (playerListIsOpen) { - openedWindows.remove("player_list"); - } else { - openedWindows.add("player_list"); - } - Flashback.getConfig().saveToDefaultFolder(); + private static void toggleWindow(String windowName) { + var openedWindows = Flashback.getConfig().openedWindows; + boolean playerListIsOpen = openedWindows.contains(windowName); + if (playerListIsOpen) { + openedWindows.remove(windowName); + } else { + openedWindows.add(windowName); } + Flashback.getConfig().saveToDefaultFolder(); } } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java new file mode 100644 index 0000000..7612f97 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java @@ -0,0 +1,94 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.mojang.authlib.GameProfile; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.editor.ui.WindowOpenState; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import imgui.ImGui; +import imgui.ImGuiViewport; +import imgui.flag.ImGuiCond; +import imgui.flag.ImGuiWindowFlags; +import imgui.type.ImString; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; + +public class MovementWindow { + + private static WindowOpenState wasOpen = WindowOpenState.UNKNOWN; + + public static void render() { + if (!Flashback.getConfig().openedWindows.contains("movement")) { + wasOpen = WindowOpenState.CLOSED; + return; + } + if (wasOpen == WindowOpenState.CLOSED) { + ImGuiViewport viewport = ImGui.getMainViewport(); + ImGui.setNextWindowPos(viewport.getCenterX(), viewport.getCenterY(), ImGuiCond.Appearing, 0.5f, 0.5f); + } + wasOpen = WindowOpenState.OPEN; + + FlashbackConfig config = Flashback.getConfig(); + + ImGui.setNextWindowSizeConstraints(250, 50, 5000, 5000); + if (ImGui.begin("Movement###Movement", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing)) { + int[] direction = new int[]{config.flightCameraDirection ? 1 : 0}; + + ImGuiHelper.combo("Direction", direction, new String[]{ + "Horizontal", + "Camera" + }); + boolean flightCameraDirection = direction[0] == 1; + if (config.flightCameraDirection != flightCameraDirection) { + config.flightCameraDirection = flightCameraDirection; + config.saveToDefaultFolder(); + } + + float[] momentum = new float[]{config.flightMomentum}; + ImGui.sliderFloat("Momentum", momentum, 0.0f, 1.0f); + if (config.flightMomentum != momentum[0]) { + config.flightMomentum = momentum[0]; + config.saveToDefaultFolder(); + } + + if (ImGui.checkbox("Lock X", config.flightLockX)) { + config.flightLockX = !config.flightLockX; + config.saveToDefaultFolder(); + } + ImGui.sameLine(); + if (ImGui.checkbox("Lock Y", config.flightLockY)) { + config.flightLockY = !config.flightLockY; + config.saveToDefaultFolder(); + } + ImGui.sameLine(); + if (ImGui.checkbox("Lock Z", config.flightLockZ)) { + config.flightLockZ = !config.flightLockZ; + config.saveToDefaultFolder(); + } + + if (ImGui.checkbox("Lock Yaw", config.flightLockYaw)) { + config.flightLockYaw = !config.flightLockYaw; + config.saveToDefaultFolder(); + } + ImGui.sameLine(); + if (ImGui.checkbox("Lock Pitch", config.flightLockPitch)) { + config.flightLockPitch = !config.flightLockPitch; + config.saveToDefaultFolder(); + } + + } + ImGui.end(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/SelectedEntityPopup.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/SelectedEntityPopup.java index 86b3ef3..b82d6f1 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/SelectedEntityPopup.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/SelectedEntityPopup.java @@ -1,7 +1,9 @@ package com.moulberry.flashback.editor.ui.windows; +import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.state.EditorState; import imgui.ImGui; +import imgui.type.ImString; import net.minecraft.client.Minecraft; import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.world.entity.Entity; diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java index a5f5429..afd0b45 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java @@ -4,9 +4,9 @@ import com.mojang.blaze3d.platform.Window; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.combo_options.AspectRatio; import com.moulberry.flashback.combo_options.AudioCodec; +import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.combo_options.VideoCodec; import com.moulberry.flashback.combo_options.VideoContainer; -import com.moulberry.flashback.compat.IrisApiWrapper; import com.moulberry.flashback.exporting.ExportJobQueue; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; @@ -16,12 +16,9 @@ import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.exporting.ExportSettings; import com.moulberry.flashback.playback.ReplayServer; import imgui.ImGui; -import imgui.flag.ImGuiPopupFlags; import imgui.flag.ImGuiWindowFlags; -import imgui.type.ImFloat; import imgui.type.ImString; import net.fabricmc.loader.api.FabricLoader; -import net.irisshaders.iris.api.v0.IrisApi; import net.minecraft.FileUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; @@ -30,6 +27,7 @@ import org.jetbrains.annotations.Nullable; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; +import java.util.List; import java.util.concurrent.CompletableFuture; public class StartExportWindow { @@ -42,7 +40,7 @@ public class StartExportWindow { private static final int[] resolution = new int[]{1920, 1080}; private static final int[] startEndTick = new int[]{0, 100}; - private static final ImFloat framerate = new ImFloat(60); + private static final float[] framerate = new float[]{60}; private static boolean resetRng = false; private static boolean ssaa = false; @@ -58,10 +56,18 @@ public class StartExportWindow { private static boolean recordAudio = false; private static boolean transparentBackground = false; private static AudioCodec audioCodec = AudioCodec.AAC; + private static boolean stereoAudio = false; private static Path defaultExportPath = null; private static final ImString jobName = ImGuiHelper.createResizableImString(""); + private static String installedIncompatibleModsString = null; + private static final List potentialIncompatibleMods = List.of( + "essential", // causes a crash due to casting the DeltaTracker without an instanceof + "g4mespeed", // causes rendering issues due to overriding partial tick time + "feather" // causes miscellaneous crashes and issues that are impossible to debug + ); + static { bitrate.inputData.allowedChars = "0123456789kmb"; } @@ -70,6 +76,17 @@ public class StartExportWindow { EditorState editorState = EditorStateManager.getCurrent(); if (open) { + installedIncompatibleModsString = null; + for (String potentialIncompatibleMod : potentialIncompatibleMods) { + if (FabricLoader.getInstance().isModLoaded(potentialIncompatibleMod)) { + if (installedIncompatibleModsString == null) { + installedIncompatibleModsString = potentialIncompatibleMod; + } else { + installedIncompatibleModsString += ", " + potentialIncompatibleMod; + } + } + } + ImGui.openPopup("###StartExport"); Window window = Minecraft.getInstance().getWindow(); @@ -82,7 +99,7 @@ public class StartExportWindow { lastFramebufferSize[1] = window.framebufferHeight; } - if (editorState != null) { + if (editorState != null && editorState.replayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { AspectRatio aspectRatio = editorState.replayVisuals.changeAspectRatio; if (aspectRatio != null && aspectRatio != lastCustomAspectRatio) { switch (aspectRatio) { @@ -128,19 +145,20 @@ public class StartExportWindow { ImGuiHelper.separatorWithText("Capture Options"); - ImGui.inputInt2("Resolution", resolution); + ImGuiHelper.inputInt("Resolution", resolution); + if (resolution[0] < 16) resolution[0] = 16; if (resolution[1] < 16) resolution[1] = 16; if (resolution[0] % 2 != 0) resolution[0] += 1; if (resolution[1] % 2 != 0) resolution[1] += 1; - if (ImGui.inputInt2("Start/end tick", startEndTick)) { + if (ImGuiHelper.inputInt("Start/end tick", startEndTick)) { ReplayServer replayServer = Flashback.getReplayServer(); if (editorState != null && replayServer != null) { editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks()); } } - ImGui.inputFloat("Framerate", framerate); + ImGuiHelper.inputFloat("Framerate", framerate); if (ImGui.checkbox("Reset RNG", resetRng)) { resetRng = !resetRng; @@ -167,6 +185,10 @@ public class StartExportWindow { } if (recordAudio) { + if (ImGui.checkbox("Stereo (2 channel)", stereoAudio)) { + stereoAudio = !stereoAudio; + } + AudioCodec newAudioCodec = ImGuiHelper.enumCombo("Audio Codec", audioCodec, supportedAudioCodecs); if (newAudioCodec != audioCodec) { audioCodec = newAudioCodec; @@ -182,6 +204,15 @@ public class StartExportWindow { recordAudio = false; } + if (installedIncompatibleModsString != null) { + ImGuiHelper.separatorWithText("Incompatible Mods"); + ImGui.textWrapped("You have some mods installed which are known to cause crashes/rendering issues.\n" + + "If you encounter problems exporting, please try removing the following mods:"); + ImGui.pushTextWrapPos(); + ImGui.textColored(0xFF0000FF, installedIncompatibleModsString); + ImGui.popTextWrapPos(); + } + ImGui.dummy(0, 10); float buttonSize = (ImGui.getContentRegionAvailX() - ImGui.getStyle().getItemSpacingX()) / 2f; @@ -264,10 +295,12 @@ public class StartExportWindow { videoCodec = codecs[0]; } - VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", videoCodec, codecs); - if (newCodec != videoCodec) { - videoCodec = newCodec; - selectedVideoEncoder[0] = 0; + if (codecs.length > 1) { + VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", videoCodec, codecs); + if (newCodec != videoCodec) { + videoCodec = newCodec; + selectedVideoEncoder[0] = 0; + } } String[] encoders = videoCodec.getEncoders(); @@ -275,15 +308,21 @@ public class StartExportWindow { ImGuiHelper.combo("Encoder", selectedVideoEncoder, encoders); } - if (ImGui.checkbox("Use Maximum Bitrate", useMaximumBitrate)) { - useMaximumBitrate = !useMaximumBitrate; - } - if (!useMaximumBitrate) { - ImGui.inputText("Bitrate", bitrate); - if (ImGui.isItemDeactivatedAfterEdit()) { - int numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); - bitrate.set(bitrateToString(numBitrate)); + if (videoCodec != VideoCodec.GIF) { + if (ImGui.checkbox("Use Maximum Bitrate", useMaximumBitrate)) { + useMaximumBitrate = !useMaximumBitrate; } + if (!useMaximumBitrate) { + ImGui.inputText("Bitrate", bitrate); + if (ImGui.isItemDeactivatedAfterEdit()) { + int numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); + bitrate.set(bitrateToString(numBitrate)); + } + } + } else { + ImGui.pushTextWrapPos(); + ImGui.textColored(0xFFFFFFFF, "Warning: GIF output can be extremely large. Please ensure you know the limitations of the GIF format before exporting. You might be better off using WebP which is a similar but better format"); + ImGui.popTextWrapPos(); } } @@ -347,8 +386,9 @@ public class StartExportWindow { return new ExportSettings(name, editorState.copy(), player.position(), player.getYRot(), player.getXRot(), resolution[0], resolution[1], start, end, - Math.max(1, framerate.get()), resetRng, container, videoCodec, encoder, numBitrate, transparent, ssaa, - recordAudio, path); + Math.max(1, framerate[0]), resetRng, container, videoCodec, encoder, numBitrate, transparent, ssaa, + recordAudio, stereoAudio, audioCodec, + path); } return null; diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java index 5076d69..11c1d6d 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java @@ -26,6 +26,8 @@ import com.moulberry.flashback.record.FlashbackMeta; import com.moulberry.flashback.state.KeyframeTrack; import imgui.ImDrawList; import imgui.ImGui; +import imgui.flag.ImGuiButtonFlags; +import imgui.flag.ImGuiHoveredFlags; import imgui.flag.ImGuiMouseButton; import imgui.flag.ImGuiMouseCursor; import imgui.flag.ImGuiPopupFlags; @@ -58,6 +60,9 @@ public class TimelineWindow { private static int grabbedKeyframeTick = 0; private static int grabbedKeyframeTrack = 0; + private static boolean trackDisabledButtonDrag = false; + private static boolean trackDisabledButtonDragValue = false; + @Nullable private static Vector2f dragSelectOrigin = null; @@ -423,7 +428,7 @@ public class TimelineWindow { editingKeyframeTick = -1; } - if (mouseX > x + middleX && mouseX < x + width && mouseY > y + middleY && mouseY < y + height) { + if (mouseX > x + middleX && mouseX < x + width && mouseY > y && mouseY < y + height) { int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel()); double mousePercentage = (mouseX - (x + middleX)) / (width - middleX); @@ -518,6 +523,9 @@ public class TimelineWindow { boolean pressedDelete = ImGui.isKeyPressed(GLFW.GLFW_KEY_DELETE, false) || ImGui.isKeyPressed(GLFW.GLFW_KEY_BACKSPACE, false); + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_SPACE, false)) { + replayServer.replayPaused = !replayServer.replayPaused; + } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT, false)) { pendingStepBackwardsTicks += 1; } else if (pendingStepBackwardsTicks > 0 && !ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT)) { @@ -843,11 +851,18 @@ public class TimelineWindow { } if (leftClicked) { - grabbedKeyframe = true; - grabbedKeyframeMouseX = mouseX; - grabbedKeyframeTick = closest.getKey(); - grabbedKeyframeTrack = trackIndex; - enableKeyframeMovement = false; + if (ImGui.isMouseDoubleClicked(ImGuiMouseButton.Left)) { + MinecraftKeyframeHandler minecraftKeyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance()); + if (minecraftKeyframeHandler.supportedKeyframes().contains(closest.getValue().keyframeType())) { + closest.getValue().apply(minecraftKeyframeHandler); + } + } else { + grabbedKeyframe = true; + grabbedKeyframeMouseX = mouseX; + grabbedKeyframeTick = closest.getKey(); + grabbedKeyframeTrack = trackIndex; + enableKeyframeMovement = false; + } } else if (rightClicked) { ImGui.openPopup("##KeyframePopup"); editingKeyframeTrack = trackIndex; @@ -945,10 +960,10 @@ public class TimelineWindow { editorState.push(new EditorStateHistoryEntry(undo, redo, "Changed interpolation type to " + interpolationType)); } - ImInt intWrapper = new ImInt(editingKeyframeTick); + int[] intWrapper = new int[]{editingKeyframeTick}; ImGui.setNextItemWidth(160); - ImGui.inputInt("Tick", intWrapper, 0); - int newEditingKeyframeTick = intWrapper.get(); + ImGuiHelper.inputInt("Tick", intWrapper); + int newEditingKeyframeTick = intWrapper[0]; if (ImGui.isItemDeactivatedAfterEdit() && newEditingKeyframeTick != editingKeyframeTick) { for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { @@ -996,6 +1011,9 @@ public class TimelineWindow { grabbedZoomBarResizeRight = false; grabbedExportBarResizeLeft = false; grabbedExportBarResizeRight = false; + if (!ImGui.isAnyMouseDown()) { + trackDisabledButtonDrag = false; + } if (dragSelectOrigin != null) { float dragMinX = Math.min(dragSelectOrigin.x, mouseX); @@ -1490,8 +1508,15 @@ public class TimelineWindow { buttonX += buttonSize + spacingX; ImGui.setCursorPosX(buttonX - x); - if (ImGui.button("##ToggleEnabled", buttonSize, buttonSize)) { - keyframeTrack.enabled = !keyframeTrack.enabled; + ImGui.button("##ToggleEnabled", buttonSize, buttonSize); + if (ImGui.isItemHovered(trackDisabledButtonDrag ? ImGuiHoveredFlags.AllowWhenBlockedByActiveItem : 0)) { + if (trackDisabledButtonDrag) { + keyframeTrack.enabled = trackDisabledButtonDragValue; + } else if (ImGui.isMouseClicked(ImGuiMouseButton.Left, false)) { + keyframeTrack.enabled = !keyframeTrack.enabled; + trackDisabledButtonDragValue = keyframeTrack.enabled; + trackDisabledButtonDrag = true; + } } if (keyframeTrack.enabled) { drawList.addCircleFilled(buttonX + buttonSize/2, buttonY + buttonSize/2, buttonSize/3, -1); @@ -1523,7 +1548,7 @@ public class TimelineWindow { redo.add(new EditorStateHistoryAction.RemoveTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); - editorState.push(new EditorStateHistoryEntry(undo, redo, "Delete " + keyframeTrack.keyframeType + " track")); + editorState.push(new EditorStateHistoryEntry(undo, redo, "Delete " + keyframeTrack.keyframeType.name() + " track")); selectedKeyframesList.clear(); } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java index f2eb4c4..d1672be 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java @@ -1,16 +1,28 @@ package com.moulberry.flashback.editor.ui.windows; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; +import com.moulberry.flashback.keyframe.impl.FOVKeyframe; +import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; +import com.moulberry.flashback.keyframe.types.FOVKeyframeType; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.record.FlashbackMeta; import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateHistoryAction; +import com.moulberry.flashback.state.EditorStateHistoryEntry; import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.state.KeyframeTrack; import com.moulberry.flashback.visuals.ReplayVisuals; import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.editor.ui.ImGuiHelper; import imgui.ImGui; +import imgui.flag.ImGuiColorEditFlags; import net.minecraft.client.Minecraft; +import java.util.List; + public class VisualsWindow { private static final float[] floatBuffer = new float[]{0}; @@ -77,6 +89,19 @@ public class VisualsWindow { editorState.markDirty(); } + if (!visuals.renderSky) { + if (ImGui.colorButton("Sky Colour", visuals.skyColour)) { + ImGui.openPopup("##EditSkyColour"); + } + ImGui.sameLine(); + ImGui.text("Sky Colour"); + + if (ImGui.beginPopup("##EditSkyColour")) { + ImGui.colorPicker3("Sky Colour", visuals.skyColour); + ImGui.endPopup(); + } + } + if (ImGui.checkbox("Render Nametags", visuals.renderNametags)) { visuals.renderNametags = !visuals.renderNametags; editorState.markDirty(); @@ -110,6 +135,12 @@ public class VisualsWindow { editorState.markDirty(); } if (visuals.overrideFov) { + ImGui.sameLine(); + if (ImGui.smallButton("+")) { + addKeyframe(editorState, replayServer, new FOVKeyframe(visuals.overrideFovAmount)); + } + ImGuiHelper.tooltip("Add FOV keyframe"); + floatBuffer[0] = visuals.overrideFovAmount; if (ImGui.sliderFloat("FOV", floatBuffer, 1.0f, 110.0f, "%.1f")) { visuals.setFov(floatBuffer[0]); @@ -127,6 +158,12 @@ public class VisualsWindow { editorState.markDirty(); } if (visuals.overrideTimeOfDay >= 0) { + ImGui.sameLine(); + if (ImGui.smallButton("+")) { + addKeyframe(editorState, replayServer, new TimeOfDayKeyframe((int) visuals.overrideTimeOfDay)); + } + ImGuiHelper.tooltip("Add Time keyframe"); + intBuffer[0] = (int) visuals.overrideTimeOfDay; if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) { visuals.overrideTimeOfDay = intBuffer[0]; @@ -140,6 +177,19 @@ public class VisualsWindow { editorState.markDirty(); } if (visuals.overrideCameraShake) { + ImGui.sameLine(); + if (ImGui.smallButton("+")) { + if (visuals.cameraShakeSplitParams) { + addKeyframe(editorState, replayServer, new CameraShakeKeyframe(visuals.cameraShakeXFrequency, visuals.cameraShakeXAmplitude, + visuals.cameraShakeYFrequency, visuals.cameraShakeYAmplitude, true)); + } else { + float frequency = (visuals.cameraShakeXFrequency + visuals.cameraShakeYFrequency)/2.0f; + float amplitude = (visuals.cameraShakeXAmplitude + visuals.cameraShakeYAmplitude)/2.0f; + addKeyframe(editorState, replayServer, new CameraShakeKeyframe(frequency, amplitude, frequency, amplitude, false)); + } + } + ImGuiHelper.tooltip("Add Camera Shake keyframe"); + if (ImGui.checkbox("Split Y/X", visuals.cameraShakeSplitParams)) { visuals.cameraShakeSplitParams = !visuals.cameraShakeSplitParams; editorState.markDirty(); @@ -239,4 +289,37 @@ public class VisualsWindow { } ImGui.end(); } + + private static void addKeyframe(EditorState editorState, ReplayServer replayServer, Keyframe keyframe) { + KeyframeType keyframeType = keyframe.keyframeType(); + + // Try add to existing enabled keyframe track + for (int i = 0; i < editorState.keyframeTracks.size(); i++) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i); + if (keyframeTrack.enabled && keyframeTrack.keyframeType == keyframeType) { + editorState.setKeyframe(i, replayServer.getReplayTick(), keyframe); + return; + } + } + + // Try add to any keyframe track + for (int i = 0; i < editorState.keyframeTracks.size(); i++) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i); + if (keyframeTrack.keyframeType == keyframeType) { + editorState.setKeyframe(i, replayServer.getReplayTick(), keyframe); + return; + } + } + + String description = "Added " + keyframeType.name() + " keyframe"; + int newKeyframeTrackIndex = editorState.keyframeTracks.size(); + editorState.push(new EditorStateHistoryEntry( + List.of(new EditorStateHistoryAction.RemoveTrack(keyframeType, newKeyframeTrackIndex)), + List.of( + new EditorStateHistoryAction.AddTrack(keyframeType, newKeyframeTrackIndex), + new EditorStateHistoryAction.SetKeyframe(keyframeType, newKeyframeTrackIndex, replayServer.getReplayTick(), keyframe) + ), + description + )); + } } diff --git a/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java index dbba61b..0f2e74f 100644 --- a/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java +++ b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java @@ -98,8 +98,16 @@ public class AsyncVideoEncoder implements AutoCloseable { Flashback.LOGGER.info("Encoding video with pixel format {}", PixelFormatHelper.pixelFormatToString(dstPixelFormat)); boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat; - final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder( - filename, width, height, settings.recordAudio() ? 1 : 0); + int audioChannels = 0; + if (settings.recordAudio()) { + if (settings.stereoAudio()) { + audioChannels = 2; + } else { + audioChannels = 1; + } + } + + final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(filename, width, height, audioChannels); recorder.setVideoBitrate(bitrate); recorder.setVideoCodec(settings.codec().codecId()); @@ -110,10 +118,10 @@ public class AsyncVideoEncoder implements AutoCloseable { recorder.setGopSize((int) Math.max(20, Math.min(240, Math.ceil(fps * 2)))); if (settings.recordAudio()) { - recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC); + recorder.setAudioCodec(settings.audioCodec().codecId()); recorder.setSampleFormat(avutil.AV_SAMPLE_FMT_FLTP); - recorder.setSampleRate(44100); - recorder.setAudioBitrate(320000); + recorder.setSampleRate(48000); + recorder.setAudioBitrate(256000); } recorder.start(); diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java index d06bcac..a2d65a0 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -127,6 +127,8 @@ public class ExportJob { TextureTarget infoRenderTarget = null; + int oldGuiScale = Minecraft.getInstance().options.guiScale().get(); + try { Files.createDirectories(exportTempFolder); @@ -145,6 +147,7 @@ public class ExportJob { this.running = false; this.shouldChangeFramebufferSize = false; + Minecraft.getInstance().options.guiScale().set(oldGuiScale); Minecraft.getInstance().resizeDisplay(); try { @@ -180,8 +183,13 @@ public class ExportJob { this.updateRandoms(random, mathRandom); shouldChangeFramebufferSize = true; + // Double gui scale if using SSAA which doubles resolution + if (this.settings.ssaa()) { + Minecraft.getInstance().options.guiScale().set(Minecraft.getInstance().options.guiScale().get() * 2); + } Minecraft.getInstance().resizeDisplay(); + DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate()); int clientTickCount = 0; @@ -279,11 +287,13 @@ public class ExportJob { if (this.settings.recordAudio()) { long device = Minecraft.getInstance().getSoundManager().soundEngine.library.currentDevice; - audioSamples += 44100 / this.settings.framerate(); + audioSamples += 48000 / this.settings.framerate(); int renderSamples = (int) audioSamples; audioSamples -= renderSamples; - audioBuffer = ByteBuffer.allocateDirect(renderSamples * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); + int channels = this.settings.stereoAudio() ? 2 : 1; + + audioBuffer = ByteBuffer.allocateDirect(renderSamples * 4 * channels).order(ByteOrder.nativeOrder()).asFloatBuffer(); SOFTLoopback.alcRenderSamplesSOFT(device, audioBuffer, renderSamples); } diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java index 9c4c35f..c7fe24d 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java @@ -1,5 +1,6 @@ package com.moulberry.flashback.exporting; +import com.moulberry.flashback.combo_options.AudioCodec; import com.moulberry.flashback.combo_options.VideoCodec; import com.moulberry.flashback.combo_options.VideoContainer; import com.moulberry.flashback.state.EditorState; @@ -18,7 +19,7 @@ public record ExportSettings(@Nullable String name, EditorState editorState, // Video VideoContainer container, VideoCodec codec, String encoder, int bitrate, boolean transparent, boolean ssaa, // Audio - boolean recordAudio, + boolean recordAudio, boolean stereoAudio, AudioCodec audioCodec, // Output Path output) { diff --git a/src/main/java/com/moulberry/flashback/io/ReplayReader.java b/src/main/java/com/moulberry/flashback/io/ReplayReader.java index 5222b68..1c0eb03 100644 --- a/src/main/java/com/moulberry/flashback/io/ReplayReader.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayReader.java @@ -14,15 +14,18 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + public class ReplayReader { private final FriendlyByteBuf friendlyByteBuf; private final int replaySnapshotOffset; private final int replayActionsOffset; private RegistryAccess registryAccess; - private Action lastAction = null; + private ResourceLocation lastActionName = null; private final Int2ObjectMap actions = new Int2ObjectOpenHashMap<>(); - private final IntSet ignoredActions = new IntOpenHashSet(); + private final Int2ObjectMap ignoredActions = new Int2ObjectOpenHashMap<>(); public ReplayReader(ByteBuf byteBuf, RegistryAccess registryAccess) { this.friendlyByteBuf = new FriendlyByteBuf(byteBuf); @@ -40,7 +43,7 @@ public class ReplayReader { if (action == null) { if (actionName.getPath().endsWith("optional")) { - this.ignoredActions.add(i); + this.ignoredActions.put(i, actionName); } else { throw new RuntimeException("Missing action: " + actionName); } @@ -50,6 +53,9 @@ public class ReplayReader { } int snapshotSize = this.friendlyByteBuf.readInt(); + if (snapshotSize < 0) { + throw new RuntimeException("Invalid snapshot size: " + snapshotSize + " (0x" + Integer.toHexString(snapshotSize) + ")"); + } this.replaySnapshotOffset = this.friendlyByteBuf.readerIndex(); this.friendlyByteBuf.skipBytes(snapshotSize); this.replayActionsOffset = this.friendlyByteBuf.readerIndex(); @@ -72,14 +78,15 @@ public class ReplayReader { int id = this.friendlyByteBuf.readVarInt(); Action action = this.actions.get(id); if (action == null) { - if (this.ignoredActions.contains(id)) { + if (this.ignoredActions.containsKey(id)) { + this.lastActionName = this.ignoredActions.get(id); int size = this.friendlyByteBuf.readInt(); this.friendlyByteBuf.skipBytes(size); continue; } - throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name()); + throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastActionName); } - this.lastAction = action; + this.lastActionName = action.name(); int size = this.friendlyByteBuf.readInt(); ByteBuf slice = this.friendlyByteBuf.readSlice(size); @@ -87,7 +94,7 @@ public class ReplayReader { action.handle(replayServer, registryFriendlyByteBuf); if (slice.readerIndex() < size) { - throw new RuntimeException("Action " + this.lastAction.name() + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); + throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); } } @@ -105,14 +112,15 @@ public class ReplayReader { int id = this.friendlyByteBuf.readVarInt(); Action action = this.actions.get(id); if (action == null) { - if (this.ignoredActions.contains(id)) { + if (this.ignoredActions.containsKey(id)) { + this.lastActionName = this.ignoredActions.get(id); int size = this.friendlyByteBuf.readInt(); this.friendlyByteBuf.skipBytes(size); return true; } - throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name()); + throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastActionName); } - this.lastAction = action; + this.lastActionName = action.name(); int size = this.friendlyByteBuf.readInt(); ByteBuf slice = this.friendlyByteBuf.readSlice(size); @@ -120,7 +128,7 @@ public class ReplayReader { action.handle(replayServer, registryFriendlyByteBuf); if (slice.readerIndex() < size) { - throw new RuntimeException("Action " + this.lastAction.name() + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); + throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); } return true; diff --git a/src/main/java/com/moulberry/flashback/io/ReplayWriter.java b/src/main/java/com/moulberry/flashback/io/ReplayWriter.java index bb643b3..069a975 100644 --- a/src/main/java/com/moulberry/flashback/io/ReplayWriter.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayWriter.java @@ -50,7 +50,7 @@ public class ReplayWriter { // Actions List actions = ActionRegistry.getActions(); this.dataBuffer.writeVarInt(actions.size()); - for (Action action : ActionRegistry.getActions()) { + for (Action action : actions) { this.dataBuffer.writeResourceLocation(action.name()); this.registeredActions.put(action, this.registeredActions.size()); } @@ -70,7 +70,7 @@ public class ReplayWriter { if (this.state == STATE_EMPTY) { this.state = STATE_WRITING_SNAPSHOT; this.snapshotSizeWriterIndex = this.dataBuffer.writerIndex(); - this.dataBuffer.writeInt(0); + this.dataBuffer.writeInt(0xDEADBEEF); } else { throw new IllegalStateException("Can only start snapshot in STATE_EMPTY"); } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java index 051a7d5..27c5957 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java @@ -2,6 +2,7 @@ package com.moulberry.flashback.keyframe.impl; import com.google.gson.*; import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; @@ -72,7 +73,7 @@ public class CameraKeyframe extends Keyframe { @Override public void renderEditKeyframe(Consumer> update) { float[] center = new float[]{(float) this.position.x, (float) this.position.y, (float) this.position.z}; - if (ImGui.inputFloat3("Position", center)) { + if (ImGuiHelper.inputFloat("Position", center)) { if (center[0] != this.position.x) { update.accept(keyframe -> ((CameraKeyframe)keyframe).position.x = center[0]); } @@ -83,22 +84,22 @@ public class CameraKeyframe extends Keyframe { update.accept(keyframe -> ((CameraKeyframe)keyframe).position.z = center[2]); } } - ImFloat input = new ImFloat(this.yaw); - if (ImGui.inputFloat("Yaw", input)) { - if (input.get() != this.yaw) { - update.accept(keyframe -> ((CameraKeyframe)keyframe).yaw = input.get()); + float[] input = new float[]{this.yaw}; + if (ImGuiHelper.inputFloat("Yaw", input)) { + if (input[0] != this.yaw) { + update.accept(keyframe -> ((CameraKeyframe)keyframe).yaw = input[0]); } } - input.set(this.pitch); - if (ImGui.inputFloat("Pitch", input)) { - if (input.get() != this.pitch) { - update.accept(keyframe -> ((CameraKeyframe)keyframe).pitch = input.get()); + input[0] = this.pitch; + if (ImGuiHelper.inputFloat("Pitch", input)) { + if (input[0] != this.pitch) { + update.accept(keyframe -> ((CameraKeyframe)keyframe).pitch = input[0]); } } - input.set(this.roll); - if (ImGui.inputFloat("Roll", input)) { - if (input.get() != this.roll) { - update.accept(keyframe -> ((CameraKeyframe)keyframe).roll = input.get()); + input[0] = this.roll; + if (ImGuiHelper.inputFloat("Roll", input)) { + if (input[0] != this.roll) { + update.accept(keyframe -> ((CameraKeyframe)keyframe).roll = input[0]); } } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java index 1caaec1..be2bbc3 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java @@ -8,6 +8,7 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; @@ -61,7 +62,7 @@ public class CameraOrbitKeyframe extends Keyframe { @Override public void renderEditKeyframe(Consumer> update) { float[] center = new float[]{(float) this.center.x, (float) this.center.y, (float) this.center.z}; - if (ImGui.inputFloat3("Position", center)) { + if (ImGuiHelper.inputFloat("Position", center)) { if (center[0] != this.center.x) { update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.x = center[0]); } @@ -72,22 +73,22 @@ public class CameraOrbitKeyframe extends Keyframe { update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.z = center[2]); } } - ImFloat input = new ImFloat(this.distance); - if (ImGui.inputFloat("Distance", input)) { - if (input.get() != this.distance) { - update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).distance = input.get()); + float[] input = new float[]{this.distance}; + if (ImGuiHelper.inputFloat("Distance", input)) { + if (input[0] != this.distance) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).distance = input[0]); } } - input.set(this.yaw); - if (ImGui.inputFloat("Yaw", input)) { - if (input.get() != this.yaw) { - update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).yaw = input.get()); + input[0] = this.yaw; + if (ImGuiHelper.inputFloat("Yaw", input)) { + if (input[0] != this.yaw) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).yaw = input[0]); } } - input.set(this.pitch); - if (ImGui.inputFloat("Pitch", input)) { - if (input.get() != this.pitch) { - update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).pitch = input.get()); + input[0] = this.pitch; + if (ImGuiHelper.inputFloat("Pitch", input)) { + if (input[0] != this.pitch) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).pitch = input[0]); } } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java index d8a0648..7aae723 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java @@ -2,6 +2,7 @@ package com.moulberry.flashback.keyframe.impl; import com.google.gson.*; import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; @@ -40,10 +41,10 @@ public class TimeOfDayKeyframe extends Keyframe { @Override public void renderEditKeyframe(Consumer> update) { ImGui.setNextItemWidth(160); - ImInt input = new ImInt(this.time); - if (ImGui.inputInt("Time", input, 0)) { - if (this.time != input.get()) { - update.accept(keyframe -> ((TimeOfDayKeyframe)keyframe).time = input.get()); + int[] input = new int[]{this.time}; + if (ImGuiHelper.inputInt("Time", input)) { + if (this.time != input[0]) { + update.accept(keyframe -> ((TimeOfDayKeyframe)keyframe).time = input[0]); } } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java index cba7b72..c7ca82e 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java @@ -1,5 +1,6 @@ package com.moulberry.flashback.keyframe.types; +import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.impl.CameraKeyframe; @@ -39,9 +40,9 @@ public class CameraOrbitKeyframeType implements KeyframeType createPopup() { float[] cameraOrbitCenter = new float[]{0.0f, 0.0f, 0.0f}; - ImFloat cameraOrbitDistance = new ImFloat(8.0f); - ImFloat cameraOrbitYaw = new ImFloat(0.0f); - ImFloat cameraOrbitPitch = new ImFloat(0.0f); + float[] cameraOrbitDistance = new float[]{8.0f}; + float[] cameraOrbitYaw = new float[]{0.0f}; + float[] cameraOrbitPitch = new float[]{0.0f}; Entity entity = Minecraft.getInstance().cameraEntity; if (entity != null) { @@ -52,14 +53,14 @@ public class CameraOrbitKeyframeType implements KeyframeType { - ImGui.inputFloat3("Position", cameraOrbitCenter); - ImGui.inputFloat("Distance", cameraOrbitDistance); - ImGui.inputFloat("Yaw", cameraOrbitYaw); - ImGui.inputFloat("Pitch", cameraOrbitPitch); + ImGuiHelper.inputFloat("Position", cameraOrbitCenter); + ImGuiHelper.inputFloat("Distance", cameraOrbitDistance); + ImGuiHelper.inputFloat("Yaw", cameraOrbitYaw); + ImGuiHelper.inputFloat("Pitch", cameraOrbitPitch); if (ImGui.button("Add")) { Vector3d center = new Vector3d(cameraOrbitCenter[0], cameraOrbitCenter[1], cameraOrbitCenter[2]); - return new CameraOrbitKeyframe(center, cameraOrbitDistance.get(), cameraOrbitYaw.get(), cameraOrbitPitch.get()); + return new CameraOrbitKeyframe(center, cameraOrbitDistance[0], cameraOrbitYaw[0], cameraOrbitPitch[0]); } ImGui.sameLine(); if (ImGui.button("Cancel")) { diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java index b7762d1..ca67224 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java @@ -1,6 +1,7 @@ package com.moulberry.flashback.keyframe.types; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; @@ -36,18 +37,18 @@ public class TimeOfDayKeyframeType implements KeyframeType { @Override public KeyframeCreatePopup createPopup() { - ImInt timeOfDayKeyframeInput = new ImInt(); + int[] timeOfDayKeyframeInput = new int[1]; EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && editorState.replayVisuals.overrideTimeOfDay >= 0) { - timeOfDayKeyframeInput.set((int) editorState.replayVisuals.overrideTimeOfDay); + timeOfDayKeyframeInput[0] = (int) editorState.replayVisuals.overrideTimeOfDay; } else { - timeOfDayKeyframeInput.set((int)(Minecraft.getInstance().level.getDayTime() % 24000)); + timeOfDayKeyframeInput[0] = (int)(Minecraft.getInstance().level.getDayTime() % 24000); } return () -> { - ImGui.inputInt("Time", timeOfDayKeyframeInput, 0); + ImGuiHelper.inputInt("Time", timeOfDayKeyframeInput); if (ImGui.button("Add")) { - return new TimeOfDayKeyframe(timeOfDayKeyframeInput.get()); + return new TimeOfDayKeyframe(timeOfDayKeyframeInput[0]); } ImGui.sameLine(); if (ImGui.button("Cancel")) { diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java index b806fa1..2de88ab 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java @@ -115,7 +115,8 @@ public abstract class MixinLevelRenderer { if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().transparent()) { RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0F); } else { - RenderSystem.clearColor(0.0f, 1.0f, 0.0f, 0.0F); + float[] skyColour = editorState.replayVisuals.skyColour; + RenderSystem.clearColor(skyColour[0], skyColour[1], skyColour[2], 0.0F); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java b/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java index 281f9ba..43f40e3 100644 --- a/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java +++ b/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java @@ -47,10 +47,11 @@ public class MixinAudioLibrary { public long init_createContext(long deviceHandle, IntBuffer attrList, Operation original) { if (this.usingLoopbackDevice) { try (MemoryStack memoryStack = MemoryStack.stackPush()) { + int channels = Flashback.EXPORT_JOB.getSettings().stereoAudio() ? SOFTLoopback.ALC_STEREO_SOFT : SOFTLoopback.ALC_MONO_SOFT; IntBuffer intBuffer = memoryStack.callocInt(7) .put(SOFTLoopback.ALC_FORMAT_TYPE_SOFT).put(SOFTLoopback.ALC_FLOAT_SOFT) - .put(SOFTLoopback.ALC_FORMAT_CHANNELS_SOFT).put(SOFTLoopback.ALC_MONO_SOFT) - .put(ALC10.ALC_FREQUENCY).put(44100) + .put(SOFTLoopback.ALC_FORMAT_CHANNELS_SOFT).put(channels) + .put(ALC10.ALC_FREQUENCY).put(48000) .put(0).flip(); return ALC10.alcCreateContext(this.currentDevice, intBuffer); } diff --git a/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java b/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java index 4519ef3..605e3b0 100644 --- a/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java +++ b/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java @@ -1,11 +1,14 @@ package com.moulberry.flashback.mixin.audio; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.client.resources.sounds.SoundInstance; import net.minecraft.client.sounds.SoundEngine; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(SoundEngine.class) @@ -26,4 +29,12 @@ public class MixinSoundEngine { } } + @Inject(method = "play", at = @At("HEAD"), cancellable = true) + public void play(SoundInstance soundInstance, CallbackInfo ci) { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null && Flashback.EXPORT_JOB == null && replayServer.replayPaused) { + ci.cancel(); + } + } + } diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/FakeChunkManagerAccessor.java b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/FakeChunkManagerAccessor.java index dfe22a4..ddddbdb 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/FakeChunkManagerAccessor.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/FakeChunkManagerAccessor.java @@ -5,9 +5,11 @@ import de.johni0702.minecraft.bobby.FakeChunkManager; import net.minecraft.client.multiplayer.ClientPacketListener; import org.jetbrains.annotations.Contract; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.gen.Invoker; @IfModLoaded("bobby") +@Pseudo @Mixin(value = FakeChunkManager.class, remap = false) public interface FakeChunkManagerAccessor { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java index 9a7cc0b..57ddb97 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java @@ -8,9 +8,11 @@ import de.johni0702.minecraft.bobby.Bobby; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; @IfModLoaded("bobby") +@Pseudo @Mixin(value = Bobby.class) public class MixinBobby { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java index 94da722..4f2bccb 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java @@ -10,6 +10,7 @@ import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.world.level.chunk.LevelChunk; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @@ -17,6 +18,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.function.Supplier; @IfModLoaded("bobby") +@Pseudo @Mixin(value = FakeChunkManager.class, remap = false) public class MixinBobbyFakeChunkManager { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/iris/MixinIrisSystemTimeUniforms.java b/src/main/java/com/moulberry/flashback/mixin/compat/iris/MixinIrisSystemTimeUniforms.java index bff6193..245736e 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/iris/MixinIrisSystemTimeUniforms.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/iris/MixinIrisSystemTimeUniforms.java @@ -4,11 +4,13 @@ import com.moulberry.flashback.Flashback; import com.moulberry.mixinconstraints.annotations.IfModLoaded; import net.irisshaders.iris.uniforms.SystemTimeUniforms; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @IfModLoaded("iris") +@Pseudo @Mixin(value = SystemTimeUniforms.Timer.class, remap = false) public class MixinIrisSystemTimeUniforms { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/replaymod/MixinReplayModRecording.java b/src/main/java/com/moulberry/flashback/mixin/compat/replaymod/MixinReplayModRecording.java new file mode 100644 index 0000000..3e3c81e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/replaymod/MixinReplayModRecording.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.mixin.compat.replaymod; + +import com.moulberry.flashback.Flashback; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import com.replaymod.recording.ReplayModRecording; +import net.minecraft.network.Connection; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@IfModLoaded("replaymod") +@Pseudo +@Mixin(value = ReplayModRecording.class, remap = false) +public class MixinReplayModRecording { + + @Inject(method = "initiateRecording", at = @At("HEAD"), cancellable = true) + public void initiateRecording(Connection networkManager, CallbackInfo ci) { + if (Flashback.isInReplay()) { + ci.cancel(); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java index 72acceb..b9976ec 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java @@ -9,9 +9,11 @@ import de.maxhenkel.voicechat.voice.client.speaker.ALSpeakerBase; import net.minecraft.client.Camera; import net.minecraft.client.renderer.GameRenderer; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; @IfModLoaded("voicechat") +@Pseudo @Mixin(ALSpeakerBase.class) public class MixinVoiceChatALSpeakerBase { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java index f784154..a168396 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java @@ -5,11 +5,13 @@ import com.moulberry.mixinconstraints.annotations.IfModLoaded; import de.maxhenkel.voicechat.voice.client.ClientVoicechat; import de.maxhenkel.voicechat.voice.client.ClientVoicechatConnection; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @IfModLoaded("voicechat") +@Pseudo @Mixin(value = ClientVoicechat.class, remap = false) public class MixinVoiceChatClientVoicechat { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java index 6ee2080..7c0d23f 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java @@ -6,12 +6,14 @@ import de.maxhenkel.voicechat.voice.client.RenderEvents; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.resources.ResourceLocation; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @IfModLoaded("voicechat") +@Pseudo @Mixin(value = RenderEvents.class, remap = false) public class MixinVoiceChatRenderEvents { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java index 7900466..78d295a 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java @@ -6,11 +6,13 @@ import de.maxhenkel.voicechat.voice.client.SoundManager; import net.minecraft.client.Minecraft; import org.lwjgl.openal.EXTThreadLocalContext; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @IfModLoaded("voicechat") +@Pseudo @Mixin(value = SoundManager.class, remap = false) public class MixinVoiceChatSoundManager { diff --git a/src/main/java/com/moulberry/flashback/mixin/movement/MixinMouseHandler.java b/src/main/java/com/moulberry/flashback/mixin/movement/MixinMouseHandler.java new file mode 100644 index 0000000..26ba5ca --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/movement/MixinMouseHandler.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.mixin.movement; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import net.minecraft.client.MouseHandler; +import net.minecraft.client.player.LocalPlayer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; + +@Mixin(MouseHandler.class) +public class MixinMouseHandler { + + @WrapOperation(method = "turnPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;turn(DD)V")) + public void turnPlayer_turn(LocalPlayer instance, double x, double y, Operation original) { + if (Flashback.isInReplay()) { + FlashbackConfig config = Flashback.getConfig(); + if (config.flightLockYaw) { + x = 0.0f; + } + if (config.flightLockPitch) { + y = 0.0f; + } + } + + original.call(instance, x, y); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java b/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java new file mode 100644 index 0000000..e08f185 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java @@ -0,0 +1,57 @@ +package com.moulberry.flashback.mixin.movement; + +import com.moulberry.flashback.EnhancedFlight; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.Vec3; +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; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(value = Player.class, priority = 1100) +public abstract class MixinPlayerEntity extends LivingEntity { + + protected MixinPlayerEntity() { + super(null, null); + } + + @Shadow public abstract void travel(Vec3 movementInput); + + @Shadow + protected abstract float getFlyingSpeed(); + + @Inject(method="getFlyingSpeed", at=@At("HEAD"), cancellable = true) + public void getFlyingSpeed(CallbackInfoReturnable cir) { + if ((Object)this instanceof LocalPlayer player && Flashback.isInReplay()) { + FlashbackConfig config = Flashback.getConfig(); + + boolean doAirplaneFlight = config.flightCameraDirection || config.flightMomentum < 0.98; + if (doAirplaneFlight && player.getAbilities().flying && !player.isPassenger() && !player.isFallFlying()) { + cir.setReturnValue(EnhancedFlight.getFlightSpeed(player, config)); + } + } + } + + @Inject(method="travel", at=@At(value = "HEAD"), cancellable = true) + public void travel(Vec3 movementInput, CallbackInfo ci) { + if ((Object)this instanceof LocalPlayer player && Flashback.isInReplay()) { + FlashbackConfig config = Flashback.getConfig(); + + boolean doAirplaneFlight = config.flightCameraDirection || config.flightMomentum < 0.98 || + config.flightLockX || config.flightLockY || config.flightLockZ; + if (doAirplaneFlight && player.getAbilities().flying && !player.isPassenger() && !player.isFallFlying()) { + EnhancedFlight.doFlight(player, config, movementInput, this.getFlyingSpeed(), super::travel); + ci.cancel(); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java index f20edcd..366cb39 100644 --- a/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java @@ -44,14 +44,14 @@ public class MixinClientLevel { @Inject(method = "playSeededSound(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/core/Holder;Lnet/minecraft/sounds/SoundSource;FFJ)V", at = @At("RETURN")) public void playSeededSoundEntity(@Nullable Player player, Entity entity, Holder holder, SoundSource soundSource, float volume, float pitch, long seed, CallbackInfo ci) { if (player != null && player == this.minecraft.player && Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { - Flashback.RECORDER.writePacketAsync(new ClientboundSoundEntityPacket(holder, soundSource, entity, volume, pitch, seed), ConnectionProtocol.PLAY); + Flashback.RECORDER.writeEntitySound(holder, soundSource, entity, volume, pitch, seed); } } @Inject(method = "playSeededSound(Lnet/minecraft/world/entity/player/Player;DDDLnet/minecraft/core/Holder;Lnet/minecraft/sounds/SoundSource;FFJ)V", at = @At("RETURN")) public void playSeededSoundNormal(@Nullable Player player, double x, double y, double z, Holder holder, SoundSource soundSource, float volume, float pitch, long seed, CallbackInfo ci) { if (player != null && player == this.minecraft.player && Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { - Flashback.RECORDER.writePacketAsync(new ClientboundSoundPacket(holder, soundSource, x, y, z, volume, pitch, seed), ConnectionProtocol.PLAY); + Flashback.RECORDER.writeSound(holder, soundSource, x, y, z, volume, pitch, seed); } } diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index b620751..84aa2cc 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -1079,10 +1079,6 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleSoundEvent(ClientboundSoundPacket clientboundSoundPacket) { - if (Flashback.EXPORT_JOB == null && this.replayServer.replayPaused) { - return; - } - Holder sound = clientboundSoundPacket.getSound(); double x = clientboundSoundPacket.getX(); double y = clientboundSoundPacket.getY(); @@ -1094,10 +1090,6 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleSoundEntityEvent(ClientboundSoundEntityPacket clientboundSoundEntityPacket) { - if (Flashback.EXPORT_JOB == null && this.replayServer.replayPaused) { - return; - } - Entity entity = this.level().getEntity(clientboundSoundEntityPacket.getId()); if (entity == null) { return; diff --git a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java index 656eb09..1059f30 100644 --- a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java +++ b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java @@ -16,6 +16,11 @@ public class IgnoredPacketSet { } private static final Set> IGNORED = Set.of( + // Ignored because these are added directly by mixin/record/MixinClientLevel + ClientboundLevelEventPacket.class, + ClientboundSoundPacket.class, + ClientboundSoundEntityPacket.class, + // Common ClientboundStoreCookiePacket.class, ClientboundCustomReportDetailsPacket.class, @@ -76,8 +81,7 @@ public class IgnoredPacketSet { ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchFinishedPacket.class, ClientboundDebugSamplePacket.class, - ClientboundPongResponsePacket.class, - ClientboundLevelEventPacket.class + ClientboundPongResponsePacket.class ); } diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java index e098b95..65fbdc5 100644 --- a/src/main/java/com/moulberry/flashback/record/Recorder.java +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -48,6 +48,8 @@ import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.resources.RegistryOps; import net.minecraft.resources.ResourceKey; import net.minecraft.server.RegistryLayer; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; import net.minecraft.tags.TagNetworkSerialization; import net.minecraft.util.Mth; import net.minecraft.world.InteractionHand; @@ -147,11 +149,19 @@ public class Recorder { } } + public boolean readyToWrite() { + return !this.closeForWriting && !this.needsInitialSnapshot && !this.wasPaused; + } + public void addMarker(ReplayMarker marker) { this.metadata.replayMarkers.put(this.writtenTicks, marker); } public void submitCustomTask(Consumer consumer) { + if (!this.readyToWrite()) { + return; + } + this.asyncReplaySaver.submit(consumer); } @@ -632,15 +642,31 @@ public class Recorder { } public void writeLevelEvent(int type, BlockPos blockPos, int data, boolean globalEvent) { - if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) { + if (!this.readyToWrite()) { return; } this.pendingPackets.add(new PacketWithPhase(new ClientboundLevelEventPacket(type, blockPos, data, globalEvent), ConnectionProtocol.PLAY)); } + public void writeSound(Holder holder, SoundSource soundSource, double x, double y, double z, float volume, float pitch, long seed) { + if (!this.readyToWrite()) { + return; + } + + this.pendingPackets.add(new PacketWithPhase(new ClientboundSoundPacket(holder, soundSource, x, y, z, volume, pitch, seed), ConnectionProtocol.PLAY)); + } + + public void writeEntitySound(Holder holder, SoundSource soundSource, Entity entity, float volume, float pitch, long seed) { + if (!this.readyToWrite()) { + return; + } + + this.pendingPackets.add(new PacketWithPhase(new ClientboundSoundEntityPacket(holder, soundSource, entity, volume, pitch, seed), ConnectionProtocol.PLAY)); + } + public void writePacketAsync(Packet packet, ConnectionProtocol phase) { - if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) { + if (!this.readyToWrite()) { return; } diff --git a/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java index 5d5866e..164b88f 100644 --- a/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java @@ -144,6 +144,13 @@ public class SaveReplayScreen extends Screen { if (!this.replayName.isEmpty() && (this.savePath == null || this.generateFileFromReplayName)) { Path replayDir = Flashback.getReplayFolder(); + + if (!Files.exists(replayDir)) { + try { + Files.createDirectories(replayDir); + } catch (IOException ignored) {} + } + String filename; try { diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java index 09a4ff3..1c5be9f 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorState.java +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -53,10 +53,10 @@ public class EditorState { Keyframe old = track.keyframesByTick.get(tick); if (old != null) { undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy())); - description = "Replaced " + track.keyframeType + " keyframe"; + description = "Replaced " + track.keyframeType.name() + " keyframe"; } else { undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick)); - description = "Added " + track.keyframeType + " keyframe"; + description = "Added " + track.keyframeType.name() + " keyframe"; } redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, keyframe.copy())); diff --git a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java index 764a8e3..40498b2 100644 --- a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java +++ b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java @@ -17,6 +17,7 @@ public class ReplayVisuals { public boolean renderPlayers = true; public boolean renderParticles = true; public boolean renderSky = true; + public float[] skyColour = new float[]{0f, 1f, 0f}; public boolean renderNametags = true; public boolean overrideFog = false; diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 82350ec..9bbd6ff 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -40,8 +40,5 @@ "minecraft": "~1.21", "java": ">=21", "fabric-api": "*" - }, - "breaks": { - "essential": "<=1.3.4.1" - } + } } diff --git a/src/main/resources/flashback.mixins.json b/src/main/resources/flashback.mixins.json index 0ae3507..1759ba6 100644 --- a/src/main/resources/flashback.mixins.json +++ b/src/main/resources/flashback.mixins.json @@ -11,6 +11,8 @@ "MixinWindow", "audio.MixinAudioLibrary", "audio.MixinSoundEngine", + "movement.MixinMouseHandler", + "movement.MixinPlayerEntity", "norandom.MixinParticle", "packet_fix.MixinBossHealthOverlay", "playback.MixinArmorStandRenderer", @@ -47,6 +49,7 @@ "compat.bobby.MixinBobby", "compat.bobby.MixinBobbyFakeChunkManager", "compat.iris.MixinIrisSystemTimeUniforms", + "compat.replaymod.MixinReplayModRecording", "compat.voice_chat.MixinVoiceChatALSpeakerBase", "compat.voice_chat.MixinVoiceChatClientVoicechat", "compat.voice_chat.MixinVoiceChatRenderEvents",