From 63535e6b3d6a5401420a8a6c8544b8ba03e90cb3 Mon Sep 17 00:00:00 2001 From: Moulberry Date: Mon, 30 Sep 2024 20:00:24 +0800 Subject: [PATCH] 0.10.0 --- .gitignore | 1 + build.gradle | 4 +- gradle.properties | 2 +- .../com/moulberry/flashback/Flashback.java | 85 ++++- .../moulberry/flashback/FlashbackGson.java | 3 + .../moulberry/flashback/Interpolation.java | 10 +- .../java/com/moulberry/flashback/Utils.java | 22 ++ .../flashback/WindowSizeTracker.java | 49 +++ .../flashback/combo_options/AudioCodec.java | 2 +- .../compat/DistantHorizonsSupport.java | 87 +++++ .../configuration/FlashbackConfig.java | 20 +- .../editor/ui/CustomImGuiImplGlfw.java | 2 + .../flashback/editor/ui/ImGuiHelper.java | 17 + .../flashback/editor/ui/ReplayUI.java | 26 +- .../ui/windows/ExportScreenshotWindow.java | 108 ++++++ .../editor/ui/windows/MainMenuBar.java | 69 +++- .../editor/ui/windows/PreferencesWindow.java | 73 ++++ .../ui/windows/SelectedEntityPopup.java | 77 ++++ .../editor/ui/windows/StartExportWindow.java | 55 +-- .../editor/ui/windows/TimelineWindow.java | 137 +++++--- .../editor/ui/windows/VisualsWindow.java | 5 + .../exporting/AsyncFFmpegVideoWriter.java | 3 +- .../flashback/exporting/ExportJob.java | 19 +- .../exporting/PNGSequenceVideoWriter.java | 21 +- .../flashback/exporting/PerfectFrames.java | 5 +- .../flashback/io/AsyncReplaySaver.java | 28 -- .../flashback/io/ReplayCombiner.java | 329 ++++++++++++++++++ .../moulberry/flashback/io/ReplayWriter.java | 2 +- .../flashback/keyframe/Keyframe.java | 5 +- .../keyframe/impl/CameraKeyframe.java | 93 ++--- .../keyframe/impl/CameraOrbitKeyframe.java | 2 +- .../keyframe/impl/CameraShakeKeyframe.java | 2 +- .../flashback/keyframe/impl/FOVKeyframe.java | 2 +- .../keyframe/impl/TickrateKeyframe.java | 2 +- .../keyframe/impl/TimeOfDayKeyframe.java | 2 +- .../interpolation/InterpolationType.java | 38 +- .../keyframe/types/CameraKeyframeType.java | 11 +- .../mixin/MixinAbstractClientPlayer.java | 45 +++ .../flashback/mixin/MixinLevelRenderer.java | 18 +- .../flashback/mixin/MixinRenderTarget.java | 44 ++- .../compat/MixinSodiumWorldRenderer.java | 5 +- .../{ => axiom}/MixinAxiomEditorUI.java | 2 +- .../axiom/MixinAxiomServerIntegration.java | 23 ++ .../distanthorizons/MixinSharedApi.java | 23 -- .../MixinFabricMinecraftServer.java | 4 +- .../MixinFabricServerPlayNetworking.java | 39 +++ .../iris/MixinIrisSystemTimeUniforms.java | 4 +- .../replaymod/MixinReplayModRecording.java | 2 +- .../mixin/movement/MixinPlayerEntity.java | 16 + .../flashback/mixin/playback/MixinCamera.java | 31 +- .../mixin/playback/MixinGameRenderer.java | 10 + .../mixin/record/MixinClientLevel.java | 13 +- .../mixin/visuals/MixinBossHealthOverlay.java | 2 +- .../mixin/visuals/MixinClientLevel.java | 4 +- .../mixin/visuals/MixinClientLevelData.java | 2 +- .../visuals/MixinEntityRenderDispatcher.java | 4 +- .../mixin/visuals/MixinEntityRenderer.java | 12 +- .../mixin/visuals/MixinFogRenderer.java | 2 +- .../flashback/mixin/visuals/MixinGui.java | 28 +- .../mixin/visuals/MixinLightTexture.java | 28 ++ .../visuals/MixinLivingEntityRenderer.java | 2 +- .../mixin/visuals/MixinLoadingOverlay.java | 2 +- .../mixin/visuals/MixinRenderStateShard.java | 2 +- .../flashback/playback/FakePlayer.java | 3 + .../ReplayConfigurationPacketHandler.java | 25 +- .../playback/ReplayGamePacketHandler.java | 35 +- .../flashback/playback/ReplayServer.java | 52 ++- .../flashback/record/FlashbackChunkMeta.java | 5 + .../flashback/record/FlashbackMeta.java | 21 ++ .../moulberry/flashback/record/Recorder.java | 69 +++- .../flashback/screen/CombineReplayScreen.java | 195 +++++++++++ .../flashback/screen/EditReplayScreen.java | 4 + .../flashback/screen/ReplaySelectionList.java | 94 ++--- .../flashback/spline/CatmullRom.java | 189 +++++----- .../flashback/state/EditorState.java | 5 + .../flashback/visuals/ReplayVisuals.java | 2 + .../flashback/visuals/ShaderManager.java | 42 +-- .../assets/flashback/lang/en_us.json | 1 + src/main/resources/flashback.mixins.json | 9 +- 79 files changed, 2007 insertions(+), 529 deletions(-) create mode 100644 src/main/java/com/moulberry/flashback/WindowSizeTracker.java create mode 100644 src/main/java/com/moulberry/flashback/compat/DistantHorizonsSupport.java create mode 100644 src/main/java/com/moulberry/flashback/editor/ui/windows/ExportScreenshotWindow.java create mode 100644 src/main/java/com/moulberry/flashback/editor/ui/windows/PreferencesWindow.java create mode 100644 src/main/java/com/moulberry/flashback/io/ReplayCombiner.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/MixinAbstractClientPlayer.java rename src/main/java/com/moulberry/flashback/mixin/compat/{ => axiom}/MixinAxiomEditorUI.java (94%) create mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomServerIntegration.java delete mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java rename src/main/java/com/moulberry/flashback/mixin/compat/{ => fabric}/MixinFabricMinecraftServer.java (92%) create mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricServerPlayNetworking.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/visuals/MixinLightTexture.java create mode 100644 src/main/java/com/moulberry/flashback/screen/CombineReplayScreen.java diff --git a/.gitignore b/.gitignore index c476faf..beb3b20 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .gradle/ build/ out/ +deps/ classes/ # eclipse diff --git a/build.gradle b/build.gradle index 4ad0cb9..a105d02 100644 --- a/build.gradle +++ b/build.gradle @@ -64,12 +64,14 @@ dependencies { include(implementation("com.moulberry:mixinconstraints:1.0.1")) + modCompileOnly(rootProject.files('deps/DistantHorizons-2.3.0-a-dev-1.21.1.jar')) + modCompileOnly("maven.modrinth:sodium:RncWhTxD") modCompileOnly("maven.modrinth:iris:kuOV4Ece") modCompileOnly("maven.modrinth:bobby:2cuVyTav") modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I") modCompileOnly("maven.modrinth:replaymod:NtlpUQgI") - modCompileOnly("maven.modrinth:distanthorizons:pEvLEY5E") + // modCompileOnly("maven.modrinth:distanthorizons:pEvLEY5E") modImplementation("maven.modrinth:modmenu:xhN1IvHi") // modCompileOnly("maven.modrinth:axiom:D3uDJmiB") diff --git a/gradle.properties b/gradle.properties index 7b15a47..0cbddf0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ yarn_mappings=1.21+build.9 loader_version=0.15.11 # Mod Properties -mod_version=0.7.0 +mod_version=0.10.0 maven_group=com.moulberry.flashback archives_base_name=flashback diff --git a/src/main/java/com/moulberry/flashback/Flashback.java b/src/main/java/com/moulberry/flashback/Flashback.java index c15c6f6..800851d 100644 --- a/src/main/java/com/moulberry/flashback/Flashback.java +++ b/src/main/java/com/moulberry/flashback/Flashback.java @@ -9,8 +9,10 @@ import com.mojang.realmsclient.RealmsMainScreen; import com.mojang.serialization.Lifecycle; import com.moulberry.flashback.action.*; import com.moulberry.flashback.command.BetterColorArgument; +import com.moulberry.flashback.compat.DistantHorizonsSupport; import com.moulberry.flashback.compat.simple_voice_chat.SimpleVoiceChatPlayback; import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.exporting.AsyncFileDialogs; import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.keyframe.KeyframeRegistry; @@ -45,6 +47,7 @@ import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.ShaderManager; +import com.seibel.distanthorizons.api.DhApi; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; @@ -54,7 +57,6 @@ import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; -import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.ChatFormatting; import net.minecraft.FileUtil; @@ -75,7 +77,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.*; -import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.packs.repository.ServerPacksSource; import net.minecraft.world.Difficulty; @@ -128,6 +129,8 @@ public class Flashback implements ModInitializer, ClientModInitializer { private static boolean delayedOpenConfig = false; private static volatile boolean isInReplay = false; + public static boolean supportsDistantHorizons = false; + private static final List pendingReplaySave = new ArrayList<>(); private static final List pendingReplayRecovery = new ArrayList<>(); @@ -305,7 +308,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { } }); - ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(ShaderManager.INSTANCE); + ShaderManager.INSTANCE.register(); ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { var flashback = ClientCommandManager.literal("flashback"); @@ -358,6 +361,18 @@ public class Flashback implements ModInitializer, ClientModInitializer { editorState.recordCameraMovement(); } } + + // Fix for camera entity sometimes being incorrect when respawning + Entity camera = Minecraft.getInstance().cameraEntity; + LocalPlayer player = Minecraft.getInstance().player; + if (player != null && camera != null && camera != player) { + if (camera.isRemoved()) { + Entity other = player.level().getEntity(camera.getId()); + if (other != null && !other.isRemoved()) { + Minecraft.getInstance().setCameraEntity(other); + } + } + } }); ClientTickEvents.START_CLIENT_TICK.register(minecraft -> { @@ -437,6 +452,16 @@ public class Flashback implements ModInitializer, ClientModInitializer { updateIsInReplay(); }); + + if (FabricLoader.getInstance().isModLoaded("distanthorizons")) { + if (DhApi.getApiMajorVersion() >= 4) { + Flashback.LOGGER.info("DistantHorizons detected. Enabling Flashback+DistantHorizons integration"); + supportsDistantHorizons = true; + DistantHorizonsSupport.register(); + } else { + Flashback.LOGGER.error("DistantHorizons is installed, but API version is too low ({}). Disabling integration.", DhApi.getApiMajorVersion()); + } + } } public static List getReplayIncompatibleMods() { @@ -444,6 +469,9 @@ public class Flashback implements ModInitializer, ClientModInitializer { if (FabricLoader.getInstance().isModLoaded("vmp")) { incompatible.add("VeryManyPlayers (vmp)"); } + if (FabricLoader.getInstance().isModLoaded("c2me")) { + incompatible.add("Concurrent Chunk Management Engine (c2me)"); + } return incompatible; } @@ -466,10 +494,6 @@ public class Flashback implements ModInitializer, ClientModInitializer { return; } - if (colour == null) { - colour = 0xFF5555; - } - ReplayMarker.MarkerPosition position = null; if (savePosition == null || savePosition) { Entity camera = Minecraft.getInstance().getCameraEntity(); @@ -479,6 +503,21 @@ public class Flashback implements ModInitializer, ClientModInitializer { } } + String feedback; + if (colour != null) { + feedback = "Added #" + Integer.toHexString(colour) + " marker"; + } else { + feedback = "Added marker"; + } + + if (position != null) { + feedback += String.format(" at %.2f, %.2f, %.2f", position.position().x, position.position().y, position.position().z); + } + + if (colour == null) { + colour = 0xFF5555; + } + if (description != null) { description = description.trim(); if (description.isEmpty()) { @@ -486,6 +525,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { } } + command.getSource().sendFeedback(Component.literal(feedback)); RECORDER.addMarker(new ReplayMarker(colour, position, description)); } @@ -703,7 +743,38 @@ public class Flashback implements ModInitializer, ClientModInitializer { return null; } + public static void openReplayFromFileBrowser() { + String defaultFolder = Flashback.getReplayFolder().toString(); + AsyncFileDialogs.openFileDialog(defaultFolder, "Zip File", "zip").thenAccept(pathStr -> { + if (pathStr != null) { + Path path = Path.of(pathStr); + Minecraft.getInstance().submit(() -> { + Flashback.openReplayWorld(path); + }); + } + }); + } + public static void openReplayWorld(Path path) { + // Disconnect + Minecraft minecraft = Minecraft.getInstance(); + if (minecraft.level != null) { + minecraft.level.disconnect(); + } + minecraft.disconnect(); + minecraft.setScreen(new TitleScreen()); + + // Add as recent + String pathStr = path.toString(); + FlashbackConfig config = Flashback.getConfig(); + config.recentReplays.remove(pathStr); + config.recentReplays.add(0, pathStr); + if (config.recentReplays.size() > 32) { + config.recentReplays.remove(config.recentReplays.size() - 1); + } + config.saveToDefaultFolder(); + + // Actually load try { UUID replayUuid = UUID.randomUUID(); Path replayTemp = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.SERVER, replayUuid); diff --git a/src/main/java/com/moulberry/flashback/FlashbackGson.java b/src/main/java/com/moulberry/flashback/FlashbackGson.java index 5f64a6d..e78e556 100644 --- a/src/main/java/com/moulberry/flashback/FlashbackGson.java +++ b/src/main/java/com/moulberry/flashback/FlashbackGson.java @@ -2,6 +2,8 @@ package com.moulberry.flashback; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.PropertyMap; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeRegistry; import com.moulberry.flashback.keyframe.KeyframeType; @@ -33,6 +35,7 @@ public class FlashbackGson { .registerTypeAdapter(Quaternionf.class, new QuaternionfTypeAdapater()) .registerTypeAdapter(Vector3d.class, new Vector3dTypeAdapater()) .registerTypeAdapter(Quaterniond.class, new QuaterniondTypeAdapater()) + .registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()) .registerTypeHierarchyAdapter(KeyframeType.class, new KeyframeRegistry.TypeAdapter()) .registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter()) diff --git a/src/main/java/com/moulberry/flashback/Interpolation.java b/src/main/java/com/moulberry/flashback/Interpolation.java index 70c9128..b9b03ec 100644 --- a/src/main/java/com/moulberry/flashback/Interpolation.java +++ b/src/main/java/com/moulberry/flashback/Interpolation.java @@ -1,8 +1,9 @@ package com.moulberry.flashback; import net.minecraft.util.Mth; +import org.joml.Math; import org.joml.Quaterniond; -import org.joml.Quaternionf; +import org.joml.Vector3d; public class Interpolation { @@ -16,11 +17,8 @@ public class Interpolation { public static float linearAngle(float from, float to, float amount) { - return from + Mth.wrapDegrees(to - from) * amount; - } - - public static Quaterniond linear(Quaterniond from, Quaterniond to, float amount) { - return from.slerp(to, amount, new Quaterniond()); + float delta = Mth.wrapDegrees(to - from); + return from + Math.max(-180, Math.min(180, delta * amount)); } } diff --git a/src/main/java/com/moulberry/flashback/Utils.java b/src/main/java/com/moulberry/flashback/Utils.java index 7afd699..ae1184a 100644 --- a/src/main/java/com/moulberry/flashback/Utils.java +++ b/src/main/java/com/moulberry/flashback/Utils.java @@ -1,9 +1,11 @@ package com.moulberry.flashback; +import com.moulberry.flashback.playback.ReplayServer; import it.unimi.dsi.fastutil.objects.Object2FloatFunction; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; +import java.time.LocalDateTime; import java.util.Random; public class Utils { @@ -158,4 +160,24 @@ public class Utils { } } + public static int exportSequenceCount = 1; + public static String resolveFilenameTemplate(String template) { + LocalDateTime dateTime = LocalDateTime.now(); + dateTime = dateTime.withNano(0); + String date = dateTime.toLocalDate().toString(); + String time = dateTime.toLocalTime().toString(); + + String replay = "unknown"; + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null) { + replay = replayServer.getMetadata().name; + } + + return template + .replace("%date%", date) + .replace("%time%", time) + .replace("%replay%", replay) + .replace("%seq%", ""+exportSequenceCount); + } + } diff --git a/src/main/java/com/moulberry/flashback/WindowSizeTracker.java b/src/main/java/com/moulberry/flashback/WindowSizeTracker.java new file mode 100644 index 0000000..afce855 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/WindowSizeTracker.java @@ -0,0 +1,49 @@ +package com.moulberry.flashback; + +import com.mojang.blaze3d.platform.Window; +import org.lwjgl.glfw.GLFW; + +public class WindowSizeTracker { + + /** + * Some mods (e.g. qdaa) like to manipulate the framebuffer width + * This can cause rendering issues since we don't know the real width + * This helper will cache and calculate the real framebuffer width to avoid this issue + */ + + private static int lastFramebufferWidth; + private static int lastFramebufferHeight; + private static int realFramebufferWidth; + private static int realFramebufferHeight; + + public static int getWidth(Window window) { + if (lastFramebufferWidth != window.framebufferWidth) { + recalculate(window); + } + + return realFramebufferWidth; + } + + + public static int getHeight(Window window) { + if (lastFramebufferHeight != window.framebufferHeight) { + recalculate(window); + } + + return realFramebufferHeight; + } + + private static void recalculate(Window window) { + // Calculate real framebuffer width/height + int[] width = new int[1]; + int[] height = new int[1]; + GLFW.glfwGetFramebufferSize(window.getWindow(), width, height); + realFramebufferWidth = width[0] > 0 ? width[0] : 1; + realFramebufferHeight = height[0] > 0 ? height[0] : 1; + + // Update cached values + lastFramebufferWidth = window.framebufferWidth; + lastFramebufferHeight = window.framebufferHeight; + } + +} diff --git a/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java b/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java index 21fcc25..4e9a8e7 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java +++ b/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java @@ -11,7 +11,7 @@ import java.util.List; public enum AudioCodec implements ComboOption { AAC("AAC", avcodec.AV_CODEC_ID_AAC), - FLAC("FLAC", avcodec.AV_CODEC_ID_FLAC), + // FLAC("FLAC", avcodec.AV_CODEC_ID_FLAC), // Removed because it doesn't support fltp sample format MP3("MP3", avcodec.AV_CODEC_ID_MP3), OPUS("Opus", avcodec.AV_CODEC_ID_OPUS), VORBIS("Vorbis", avcodec.AV_CODEC_ID_VORBIS); diff --git a/src/main/java/com/moulberry/flashback/compat/DistantHorizonsSupport.java b/src/main/java/com/moulberry/flashback/compat/DistantHorizonsSupport.java new file mode 100644 index 0000000..c67ecc8 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/compat/DistantHorizonsSupport.java @@ -0,0 +1,87 @@ +package com.moulberry.flashback.compat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayServer; +import com.seibel.distanthorizons.api.DhApi; +import com.seibel.distanthorizons.api.interfaces.override.levelHandling.IDhApiSaveStructure; +import com.seibel.distanthorizons.api.interfaces.world.IDhApiLevelWrapper; +import com.seibel.distanthorizons.api.methods.events.DhApiEventRegister; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiLevelLoadEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiWorldLoadEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiWorldUnloadEvent; +import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiEventParam; +import com.seibel.distanthorizons.core.api.internal.SharedApi; +import com.seibel.distanthorizons.core.level.IDhLevel; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class DistantHorizonsSupport { + + private static boolean boundReplaySaveStructure = false; + + private static class ReplayDhSaveStructure implements IDhApiSaveStructure { + public final Map pathOverrides = new HashMap<>(); + + @Override + public File overrideFilePath(File file, IDhApiLevelWrapper iDhApiLevelWrapper) { + return this.pathOverrides.get(iDhApiLevelWrapper.getDimensionName()); + } + } + private static final ReplayDhSaveStructure REPLAY_SAVE_STRUCTURE = new ReplayDhSaveStructure(); + + public static void register() { + DhApiEventRegister.on(DhApiWorldLoadEvent.class, new DhApiWorldLoadEvent() { + @Override + public void onLevelLoad(DhApiEventParam dhApiEventParam) { + if (Flashback.isInReplay()) { + Flashback.LOGGER.info("Forcing Distant Horizons to read-only because we're inside a replay"); + DhApi.Delayed.worldProxy.setReadOnly(true); + + Flashback.LOGGER.info("Binding IDhApiSaveStructure to REPLAY_SAVE_STRUCTURE"); + + ReplayServer replayServer = Flashback.getReplayServer(); + REPLAY_SAVE_STRUCTURE.pathOverrides.clear(); + REPLAY_SAVE_STRUCTURE.pathOverrides.putAll(replayServer.getMetadata().distantHorizonPaths); + + DhApi.overrides.bind(IDhApiSaveStructure.class, REPLAY_SAVE_STRUCTURE); + boundReplaySaveStructure = true; + } + } + }); + + DhApiEventRegister.on(DhApiWorldUnloadEvent.class, new DhApiWorldUnloadEvent() { + @Override + public void onLevelUnload(DhApiEventParam dhApiEventParam) { + if (boundReplaySaveStructure) { + Flashback.LOGGER.info("Unbinding IDhApiSaveStructure from REPLAY_SAVE_STRUCTURE"); + DhApi.overrides.unbind(IDhApiSaveStructure.class, REPLAY_SAVE_STRUCTURE); + boundReplaySaveStructure = false; + } + } + }); + + DhApiEventRegister.on(DhApiLevelLoadEvent.class, new DhApiLevelLoadEvent() { + @Override + public void onLevelLoad(DhApiEventParam dhApiEventParam) { + if (Flashback.RECORDER != null) { + Flashback.RECORDER.putDistantHorizonsPaths(getDimensionPaths()); + } + } + }); + } + + public static Map getDimensionPaths() { + Map paths = new HashMap<>(); + + for (IDhLevel level : SharedApi.getIDhClientWorld().getAllLoadedLevels()) { + File file = level.getSaveStructure().getSaveFolder(level.getLevelWrapper()); + String dimensionName = level.getLevelWrapper().getDimensionName(); + paths.put(dimensionName, file); + } + + return paths; + } + +} diff --git a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java index e377e20..167ee29 100644 --- a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java +++ b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java @@ -4,6 +4,7 @@ import com.mojang.serialization.Codec; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.SneakyThrow; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.ChatFormatting; import net.minecraft.client.OptionInstance; @@ -74,6 +75,10 @@ public class FlashbackConfig { public boolean flightLockYaw = false; public boolean flightLockPitch = false; + public List recentReplays = new ArrayList<>(); + public String defaultExportFilename = "%date%T%time%"; + public InterpolationType defaultInterpolationType = InterpolationType.SMOOTH; + @SuppressWarnings("unchecked") public OptionInstance[] createOptionInstances() { List> options = new ArrayList<>(); @@ -219,10 +224,17 @@ public class FlashbackConfig { if (Files.exists(primary)) { try { - Files.move(primary, backup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - } catch (IOException e) { - Flashback.LOGGER.error("Failed to backup config", e); - } + // Ensure primary can be loaded before backing it up + // Don't want to back up a bad config now, do we? + load(primary); + + // Try to back up the config + try { + Files.move(primary, backup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + Flashback.LOGGER.error("Failed to backup config", e); + } + } catch (Exception ignored) {} } this.save(primary); 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 f737528..83245a4 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java @@ -367,8 +367,10 @@ public class CustomImGuiImplGlfw { Minecraft.getInstance().options.keyLeft.matches(key, scancode) || Minecraft.getInstance().options.keyDown.matches(key, scancode) || Minecraft.getInstance().options.keyRight.matches(key, scancode) || + Minecraft.getInstance().options.keyJump.matches(key, scancode) || Minecraft.getInstance().options.keyChat.matches(key, scancode) || Minecraft.getInstance().options.keyCommand.matches(key, scancode)) { + ReplayUI.focusMainWindowCounter = 5; passToMinecraft = true; } 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 cb1019d..cb95b2e 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java @@ -364,11 +364,20 @@ public class ImGuiHelper { focusLastIndex = 0; } + if (ImGui.inputInt("", imInt, 0)) { valueChanged = true; value[i] = imInt.get(); } + if (ImGui.isItemHovered()) { + int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel()); + if (scroll != 0) { + valueChanged = true; + value[i] += 1; + } + } + 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)) { @@ -429,11 +438,19 @@ public class ImGuiHelper { focusLastIndex = 0; } + int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel()); if (ImGui.inputFloat("", imFloat, 0)) { valueChanged = true; value[i] = imFloat.get(); } + if (ImGui.isItemHovered()) { + if (scroll != 0) { + valueChanged = true; + value[i] = Math.round(value[i] + scroll); + } + } + 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)) { 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 7586ec6..0e31601 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java @@ -5,8 +5,10 @@ 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.ExportScreenshotWindow; import com.moulberry.flashback.editor.ui.windows.MovementWindow; import com.moulberry.flashback.editor.ui.windows.PlayerListWindow; +import com.moulberry.flashback.editor.ui.windows.PreferencesWindow; import com.moulberry.flashback.editor.ui.windows.SelectedEntityPopup; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; @@ -65,7 +67,7 @@ public class ReplayUI { public static int viewportSizeY = 1; private static boolean activeLastFrame = false; - private static int focusMainWindowCounter = 0; + public static int focusMainWindowCounter = 0; public static boolean hasAnyPopupOpen = false; @@ -535,10 +537,19 @@ public class ReplayUI { ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); } - char controlIcon = Minecraft.ON_OSX ? '\u2318' : '\u2303'; - MainMenuBar.render(); + // The main menu bar can disconnect us, so make sure to check if the UI should still be active here + if (!isActiveInternal()) { + ImGui.render(); + ImGuiHelper.endFrame(); + + transitionActiveState(false); + imguiGlfw.updateReleaseAllKeys(true); + focusMainWindowCounter = 5; + return; + } + // Setup docking ImGui.setNextWindowBgAlpha(0); int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode); @@ -671,15 +682,16 @@ public class ReplayUI { if (selectedEntity != null) { Entity entity = Minecraft.getInstance().level.getEntities().get(selectedEntity); - if (entity == null) { + if (entity == null || editorState == null) { selectedEntity = null; - } else if (entity instanceof Player && editorState != null && !editorState.replayVisuals.renderPlayers) { + } else if (entity instanceof Player && !editorState.replayVisuals.renderPlayers) { selectedEntity = null; - } else if (!(entity instanceof Player) && editorState != null && !editorState.replayVisuals.renderEntities) { + } else if (!(entity instanceof Player) && !editorState.replayVisuals.renderEntities) { selectedEntity = null; } else { if (openSelectedEntityPopup) { ImGui.openPopup("###EntityPopup"); + SelectedEntityPopup.open(entity, editorState); } if (ImGuiHelper.beginPopup("###EntityPopup")) { @@ -728,6 +740,8 @@ public class ReplayUI { VisualsWindow.render(); TimelineWindow.render(); StartExportWindow.render(); + ExportScreenshotWindow.render(); + PreferencesWindow.render(); ExportQueueWindow.render(); PlayerListWindow.render(); MovementWindow.render(); diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportScreenshotWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportScreenshotWindow.java new file mode 100644 index 0000000..53b85d5 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportScreenshotWindow.java @@ -0,0 +1,108 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.Utils; +import com.moulberry.flashback.combo_options.VideoCodec; +import com.moulberry.flashback.combo_options.VideoContainer; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.exporting.AsyncFileDialogs; +import com.moulberry.flashback.exporting.ExportJob; +import com.moulberry.flashback.exporting.ExportSettings; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import imgui.ImGui; +import imgui.flag.ImGuiWindowFlags; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; + +import java.nio.file.Path; + +public class ExportScreenshotWindow { + + private static boolean open = false; + private static boolean close = false; + + private static final int[] resolution = new int[]{1920, 1080}; + + public static void render() { + if (open) { + open = false; + ImGui.openPopup("###ExportScreenshot"); + } + + if (ImGuiHelper.beginPopupModalCloseable("Export screenshot###ExportScreenshot", ImGuiWindowFlags.AlwaysAutoResize)) { + if (close) { + close = false; + ImGui.closeCurrentPopup(); + ImGuiHelper.endPopupModalCloseable(); + return; + } + + ImGuiHelper.inputInt("Resolution", resolution); + resolution[0] = Math.max(1, resolution[0]); + resolution[1] = Math.max(1, resolution[1]); + + EditorState editorState = EditorStateManager.getCurrent(); + + if (ImGui.checkbox("SSAA", StartExportWindow.ssaa)) { + StartExportWindow.ssaa = !StartExportWindow.ssaa; + } + ImGuiHelper.tooltip("Supersampling Anti-Aliasing: Remove jagged edges by rendering the game at double resolution and downscaling"); + + ImGui.sameLine(); + + if (ImGui.checkbox("No GUI", StartExportWindow.noGui)) { + StartExportWindow.noGui = !StartExportWindow.noGui; + } + ImGuiHelper.tooltip("Removes all UI from the screen, rendering only the world"); + + if (editorState != null && !editorState.replayVisuals.renderSky) { + if (ImGui.checkbox("Transparent Sky", StartExportWindow.transparentBackground)) { + StartExportWindow.transparentBackground = !StartExportWindow.transparentBackground; + } + } + + if (editorState != null && ImGui.button("Take Screenshot")) { + String defaultName = StartExportWindow.getDefaultFilename(null, "png"); + String defaultExportPathString = StartExportWindow.defaultExportPath.toString(); + + AsyncFileDialogs.saveFileDialog(defaultExportPathString, defaultName, "PNG", "png").thenAccept(pathStr -> { + if (pathStr != null) { + Path path = Path.of(pathStr); + StartExportWindow.defaultExportPath = path.getParent(); + + LocalPlayer player = Minecraft.getInstance().player; + int tick = Flashback.getReplayServer().getReplayTick(); + + boolean transparent = StartExportWindow.transparentBackground && !editorState.replayVisuals.renderSky; + boolean ssaa = StartExportWindow.ssaa; + boolean noGui = StartExportWindow.noGui; + + EditorState copiedEditorState = editorState.copy(); + copiedEditorState.keyframeTracks.clear(); + + ExportSettings settings = new ExportSettings(null, copiedEditorState, + player.position(), player.getYRot(), player.getXRot(), + resolution[0], resolution[1], tick, tick, + 1, false, VideoContainer.PNG_SEQUENCE, null, null, 0, transparent, ssaa, noGui, + false, false, null, + path); + + close = true; + Utils.exportSequenceCount += 1; + Flashback.EXPORT_JOB = new ExportJob(settings); + } + }); + } + + ImGuiHelper.endPopupModalCloseable(); + } + + close = false; + } + + public static void open() { + open = true; + } + +} 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 8e249d8..77d7fbe 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 @@ -1,9 +1,16 @@ package com.moulberry.flashback.editor.ui.windows; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.exporting.AsyncFileDialogs; import com.moulberry.flashback.exporting.ExportJobQueue; +import com.moulberry.flashback.screen.SelectReplayScreen; import imgui.ImGui; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.TitleScreen; + +import java.nio.file.Files; +import java.nio.file.Path; public class MainMenuBar { @@ -15,15 +22,63 @@ public class MainMenuBar { } public static void renderInner() { - if (ImGui.menuItem("Export Video")) { - StartExportWindow.open(); - } + FlashbackConfig config = Flashback.getConfig(); - if (!ExportJobQueue.queuedJobs.isEmpty()) { - String name = "Export Queue (" + ExportJobQueue.count() + ")"; - if (ImGui.menuItem(name + "###QueuedJobs")) { - ExportQueueWindow.open(); + if (ImGui.beginMenu("File")) { + if (ImGui.menuItem("Export Video")) { + StartExportWindow.open(); } + if (!ExportJobQueue.queuedJobs.isEmpty()) { + String name = "Export Queue (" + ExportJobQueue.count() + ")"; + if (ImGui.menuItem(name + "###QueuedJobs")) { + ExportQueueWindow.open(); + } + } + if (ImGui.menuItem("Export Screenshot")) { + ExportScreenshotWindow.open(); + } + ImGui.separator(); + if (ImGui.menuItem("Open Replay")) { + Flashback.openReplayFromFileBrowser(); + } + if (!config.recentReplays.isEmpty()) { + if (ImGui.beginMenu("Open Recent")) { + Path replayFolder = Flashback.getReplayFolder(); + for (String recentReplay : config.recentReplays) { + Path path = Path.of(recentReplay); + + if (Files.exists(path)) { + String display = path.toString(); + + try { + Path relative = replayFolder.relativize(path); + String relativeStr = relative.toString(); + if (!relativeStr.contains("..")) { + display = relativeStr; + } + } catch (Exception ignored) {} + + if (ImGui.menuItem(display)) { + Flashback.openReplayWorld(path); + break; + } + } + } + ImGui.endMenu(); + } + } + if (ImGui.menuItem("Exit Replay")) { + Minecraft minecraft = Minecraft.getInstance(); + if (minecraft.level != null) { + minecraft.level.disconnect(); + } + minecraft.disconnect(); + minecraft.setScreen(new SelectReplayScreen(new TitleScreen())); + } + ImGui.endMenu(); + } + if (ImGui.menuItem("Preferences")) { + PreferencesWindow.open(); } ImGui.separator(); diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/PreferencesWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/PreferencesWindow.java new file mode 100644 index 0000000..d998d3a --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/PreferencesWindow.java @@ -0,0 +1,73 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.combo_options.VideoContainer; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.exporting.AsyncFileDialogs; +import com.moulberry.flashback.exporting.ExportJob; +import com.moulberry.flashback.exporting.ExportSettings; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import imgui.ImGui; +import imgui.flag.ImGuiWindowFlags; +import imgui.type.ImShort; +import imgui.type.ImString; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; + +import java.nio.file.Path; + +public class PreferencesWindow { + + private static boolean open = false; + private static boolean close = false; + + public static void render() { + if (open) { + open = false; + ImGui.openPopup("###Preferences"); + } + + boolean wasOpen = ImGui.isPopupOpen("###Preferences"); + + if (ImGuiHelper.beginPopupModalCloseable("Preferences###Preferences", ImGuiWindowFlags.AlwaysAutoResize)) { + if (close) { + close = false; + ImGui.closeCurrentPopup(); + ImGuiHelper.endPopupModalCloseable(); + return; + } + + FlashbackConfig config = Flashback.getConfig(); + + // Exporting + ImGuiHelper.separatorWithText("Exporting"); + + ImString imString = ImGuiHelper.createResizableImString(config.defaultExportFilename); + if (ImGui.inputText("Export Filename", imString)) { + config.defaultExportFilename = ImGuiHelper.getString(imString); + } + ImGuiHelper.tooltip("The default filename when exporting\nVariables:\n\t%date%\tyear-month-day\n\t%time%\thh_mm_ss\n\t%replay%\tReplay name\n\t%seq%\tExport count for this session"); + + // Keyframes + ImGuiHelper.separatorWithText("Keyframes"); + + config.defaultInterpolationType = ImGuiHelper.enumCombo("Default Interpolation", config.defaultInterpolationType); + + ImGuiHelper.endPopupModalCloseable(); + } + + if (wasOpen && !ImGui.isPopupOpen("###Preferences")) { + Flashback.getConfig().saveToDefaultFolder(); + } + + close = false; + } + + public static void open() { + open = true; + } + +} 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 b82d6f1..a6fd1a3 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,17 +1,43 @@ package com.moulberry.flashback.editor.ui.windows; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.yggdrasil.ProfileResult; 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.client.multiplayer.PlayerInfo; import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; import java.util.UUID; public class SelectedEntityPopup { + private static ImString changeSkinInput = ImGuiHelper.createResizableImString(""); + static { + changeSkinInput.inputData.allowedChars = "0123456789abcdef-"; + } + private static ImString changeNameInput = ImGuiHelper.createResizableImString(""); + + public static void open(Entity entity, EditorState editorState) { + String nameOverride = editorState.nameOverride.get(entity.getUUID()); + if (nameOverride != null) { + changeNameInput.set(nameOverride); + } else { + changeNameInput.set(""); + } + + GameProfile skinOverride = editorState.skinOverride.get(entity.getUUID()); + if (skinOverride != null) { + changeSkinInput.set(skinOverride.getId().toString()); + } else { + changeSkinInput.set(""); + } + } + public static void render(Entity entity, EditorState editorState) { UUID uuid = entity.getUUID(); ImGui.text("Entity: " + uuid); @@ -45,6 +71,57 @@ public class SelectedEntityPopup { editorState.markDirty(); } + if (!isHiddenDuringExport && entity instanceof Player player) { + boolean hideNametag = editorState.hideNametags.contains(entity.getUUID()); + if (ImGui.checkbox("Render Nametag", !hideNametag)) { + if (hideNametag) { + editorState.hideNametags.remove(entity.getUUID()); + } else { + editorState.hideNametags.add(entity.getUUID()); + } + } + + if (!hideNametag) { + boolean changedName = ImGui.inputTextWithHint("Name##SetNameInput", player.getScoreboardName(), changeNameInput); + + if (changedName) { + String string = ImGuiHelper.getString(changeNameInput); + if (string.isEmpty()) { + editorState.nameOverride.remove(entity.getUUID()); + } else { + editorState.nameOverride.put(entity.getUUID(), string); + } + } + } + + ImGuiHelper.separatorWithText("Change Skin & Cape (UUID)"); + ImGui.setNextItemWidth(320); + ImGui.inputTextWithHint("##SetSkinInput", "e.g. d0e05de7-6067-454d-beae-c6d19d886191", changeSkinInput); + + boolean hasApplySkin = false; + if (!changeSkinInput.isEmpty()) { + String string = ImGuiHelper.getString(changeSkinInput); + try { + UUID changeSkinUuid = UUID.fromString(string); + if (ImGui.button("Apply Skin")) { + ProfileResult profile = Minecraft.getInstance().getMinecraftSessionService().fetchProfile(changeSkinUuid, true); + editorState.skinOverride.put(entity.getUUID(), profile.profile()); + } + hasApplySkin = true; + } catch (Exception ignored) {} + } + + if (editorState.skinOverride.containsKey(entity.getUUID())) { + if (hasApplySkin) { + ImGui.sameLine(); + } + if (ImGui.button("Reset Skin")) { + editorState.skinOverride.remove(entity.getUUID()); + changeSkinInput.set(""); + } + } + } + // ImGui.sameLine(); // ImGui.button("Track 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 412eff5..ee25051 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 @@ -2,6 +2,7 @@ package com.moulberry.flashback.editor.ui.windows; import com.mojang.blaze3d.platform.Window; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.Utils; import com.moulberry.flashback.combo_options.AspectRatio; import com.moulberry.flashback.combo_options.AudioCodec; import com.moulberry.flashback.combo_options.Sizing; @@ -22,6 +23,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.FileUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.file.Files; @@ -43,8 +45,8 @@ public class StartExportWindow { private static final int[] startEndTick = new int[]{0, 100}; private static final float[] framerate = new float[]{60}; private static boolean resetRng = false; - private static boolean ssaa = false; - private static boolean noGui = false; + public static boolean ssaa = false; + public static boolean noGui = false; private static VideoContainer[] supportedContainers = null; private static VideoContainer[] supportedContainersWithTransparency = null; @@ -56,11 +58,11 @@ public class StartExportWindow { private static final ImString bitrate = ImGuiHelper.createResizableImString("20m"); private static boolean recordAudio = false; - private static boolean transparentBackground = false; + public static boolean transparentBackground = false; private static AudioCodec audioCodec = AudioCodec.AAC; private static boolean stereoAudio = false; - private static Path defaultExportPath = null; + public static Path defaultExportPath = null; private static final ImString jobName = ImGuiHelper.createResizableImString(""); private static String installedIncompatibleModsString = null; @@ -229,6 +231,7 @@ public class StartExportWindow { createExportSettings(null).thenAccept(settings -> { if (settings != null) { close = true; + Utils.exportSequenceCount += 1; Flashback.EXPORT_JOB = new ExportJob(settings); } }); @@ -247,6 +250,7 @@ public class StartExportWindow { createExportSettings(ImGuiHelper.getString(jobName)).thenAccept(settings -> { if (settings != null) { close = true; + Utils.exportSequenceCount += 1; ExportJobQueue.queuedJobs.add(settings); } }); @@ -351,24 +355,7 @@ public class StartExportWindow { numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); } - if (defaultExportPath == null || !Files.exists(defaultExportPath)) { - defaultExportPath = FabricLoader.getInstance().getGameDir(); - } - - String defaultName = null; - if (name != null) { - try { - defaultName = FileUtil.findAvailableName(defaultExportPath, name, "." + container.extension()); - } catch (Exception ignored) {} - } - if (defaultName == null) { - try { - defaultName = FileUtil.findAvailableName(defaultExportPath, "output", "." + container.extension()); - } catch (Exception ignored) {} - } - if (defaultName == null) { - defaultName = "output." + container.extension(); - } + String defaultName = getDefaultFilename(name, container.extension()); Function callback = pathStr -> { if (pathStr != null) { @@ -432,6 +419,30 @@ public class StartExportWindow { } + public static @NotNull String getDefaultFilename(@Nullable String name, String extension) { + if (defaultExportPath == null || !Files.exists(defaultExportPath)) { + defaultExportPath = FabricLoader.getInstance().getGameDir(); + } + + String defaultName = null; + if (name != null) { + try { + defaultName = FileUtil.findAvailableName(defaultExportPath, name, "." + extension); + } catch (Exception ignored) {} + } + if (defaultName == null) { + String desiredName = Utils.resolveFilenameTemplate(Flashback.getConfig().defaultExportFilename); + try { + defaultName = FileUtil.findAvailableName(defaultExportPath, desiredName, "." + extension); + } catch (Exception ignored) {} + } + if (defaultName == null) { + String desiredName = Utils.resolveFilenameTemplate(Flashback.getConfig().defaultExportFilename); + defaultName = desiredName + "." + extension; + } + return defaultName; + } + private static int stringToBitrate(String string) { int number = 0; int modifier = 1; 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 559d3b5..463dc26 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 @@ -27,15 +27,12 @@ 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; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; -import imgui.type.ImFloat; -import imgui.type.ImInt; import it.unimi.dsi.fastutil.ints.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; @@ -60,6 +57,9 @@ public class TimelineWindow { private static boolean enableKeyframeMovement = false; private static int grabbedKeyframeTick = 0; private static int grabbedKeyframeTrack = 0; + private static int draggingMouseButton = ImGuiMouseButton.Left; + private static float dragStartMouseX = 0; + private static float dragStartMouseY = 0; private static boolean trackDisabledButtonDrag = false; private static boolean trackDisabledButtonDragValue = false; @@ -130,7 +130,11 @@ public class TimelineWindow { boolean hoveredBody = mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height; ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); - boolean timelineVisible = ImGui.begin("Timeline (" + timestamp + "/" + cursorTicks + ")###Timeline", hoveredBody ? ImGuiWindowFlags.NoMove : ImGuiWindowFlags.None); + int flags = ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoScrollbar; + if (hoveredBody) { + flags |= ImGuiWindowFlags.NoMove; + } + boolean timelineVisible = ImGui.begin("Timeline (" + timestamp + "/" + cursorTicks + ")###Timeline", flags); ImGuiHelper.popStyleVar(); cursorTicks = replayServer.getReplayTick(); @@ -223,23 +227,7 @@ public class TimelineWindow { boolean isShiftDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT); if (isShiftDown) { - int closestTick = -1; - for (KeyframeTrack track : editorState.keyframeTracks) { - Integer floor = track.keyframesByTick.floorKey(cursorTicks); - Integer ceil = track.keyframesByTick.ceilingKey(cursorTicks); - - float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor); - float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil); - - Integer closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE); - if (closest != null) { - if (closestTick == -1) { - closestTick = closest; - } else if (Math.abs(closest - cursorTicks) < Math.abs(closestTick - cursorTicks)) { - closestTick = closest; - } - } - } + int closestTick = findClosestKeyframeForSnap(editorState, cursorTicks); if (closestTick != -1) { cursorTicks = closestTick; } @@ -272,7 +260,7 @@ public class TimelineWindow { drawList.addLine(x + middleX, y + timestampHeight, x + middleX, y + height, -1); // Middle divider (y) - drawList.addLine(0, y + middleY, width, y + middleY, -1); + drawList.addLine(x, y + middleY, x + width, y + middleY, -1); renderKeyframeElements(replayServer, editorState, x, y + middleY, cursorTicks, middleX); @@ -433,58 +421,81 @@ public class TimelineWindow { editingKeyframeTick = -1; } - 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); - - if (scroll > 0) { - double zoomDelta = editorState.zoomMax - editorState.zoomMin; - if (zoomDelta > 0.001) { - editorState.zoomMin += zoomDelta * 0.05 * mousePercentage; - editorState.zoomMax -= zoomDelta * 0.05 * (1 - mousePercentage); - editorState.markDirty(); - } - } else if (scroll < 0) { - double zoomDelta = editorState.zoomMax - editorState.zoomMin; - - editorState.zoomMin = Math.max(0, editorState.zoomMin - zoomDelta * 0.05/0.9 * mousePercentage); - editorState.zoomMax = Math.min(1, editorState.zoomMax + zoomDelta * 0.05/0.9 * (1 - mousePercentage)); - editorState.markDirty(); - } - } - boolean shouldProcessInput = !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup) && !ImGui.getIO().getWantTextInput(); if (shouldProcessInput) { + int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel()); + if (scroll != 0 && mouseX > x + middleX && mouseX < x + width && mouseY > y && mouseY < y + height) { + double mousePercentage = (mouseX - (x + middleX)) / (width - middleX); + + if (scroll > 0) { + double zoomDelta = editorState.zoomMax - editorState.zoomMin; + if (zoomDelta > 0.001) { + editorState.zoomMin += zoomDelta * 0.05 * mousePercentage; + editorState.zoomMax -= zoomDelta * 0.05 * (1 - mousePercentage); + editorState.markDirty(); + } + } else if (scroll < 0) { + double zoomDelta = editorState.zoomMax - editorState.zoomMin; + + editorState.zoomMin = Math.max(0, editorState.zoomMin - zoomDelta * 0.05/0.9 * mousePercentage); + editorState.zoomMax = Math.min(1, editorState.zoomMax + zoomDelta * 0.05/0.9 * (1 - mousePercentage)); + editorState.markDirty(); + } + } + handleKeyPresses(replayServer, cursorTicks, editorState, totalTicks); boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); if (leftClicked || rightClicked) { handleClick(editorState, replayServer, totalTicks); - } else if (ImGui.isMouseDragging(ImGuiMouseButton.Left)) { + if (leftClicked) { + draggingMouseButton = ImGuiMouseButton.Left; + } else { + draggingMouseButton = ImGuiMouseButton.Right; + } + dragStartMouseX = mouseX; + dragStartMouseY = mouseY; + } else if (ImGui.isMouseDragging(draggingMouseButton)) { if (grabbedExportBarResizeLeft) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + int target = timelineXToReplayTick(mouseX - x); + + if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) { + int closestTick = findClosestKeyframeForSnap(editorState, target); + if (closestTick != -1) { + target = closestTick; + } + } + editorState.setExportTicks(target, -1, totalTicks); } if (grabbedExportBarResizeRight) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); int target = timelineXToReplayTick(mouseX - x); + + if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) { + int closestTick = findClosestKeyframeForSnap(editorState, target); + if (closestTick != -1) { + target = closestTick; + } + } + editorState.setExportTicks(-1, target, totalTicks); } if (zoomBarWidth > 1f && grabbedZoomBar) { - float dx = ImGui.getMouseDragDeltaX(); + float dx = mouseX - dragStartMouseX; float factor = dx / zoomBarWidth; if (grabbedZoomBarResizeLeft) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); - editorState.zoomMin = Math.max(0, Math.min(editorState.zoomMax-0.01f, zoomMinBeforeDrag + factor)); + editorState.zoomMin = Math.max(0, Math.min(editorState.zoomMax - 0.01f, zoomMinBeforeDrag + factor)); } else if (grabbedZoomBarResizeRight) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); - editorState.zoomMax = Math.max(editorState.zoomMin+0.01f, Math.min(1, zoomMaxBeforeDrag + factor)); + editorState.zoomMax = Math.max(editorState.zoomMin + 0.01f, Math.min(1, zoomMaxBeforeDrag + factor)); } else { ImGui.setMouseCursor(ImGuiMouseCursor.Hand); @@ -508,6 +519,13 @@ public class TimelineWindow { replayServer.replayPaused = true; } + } else if (zoomBarWidth > 1f && mouseY > y + middleY && mouseY < y + height && mouseX > x + middleX && mouseX < x + width && ImGui.isMouseDown(ImGuiMouseButton.Middle)) { + grabbedZoomBar = true; + draggingMouseButton = ImGuiMouseButton.Middle; + zoomMinBeforeDrag = editorState.zoomMin; + zoomMaxBeforeDrag = editorState.zoomMax; + dragStartMouseX = mouseX; + dragStartMouseY = mouseY; } else if (!ImGui.isAnyMouseDown()) { releaseGrabbed(editorState, replayServer, totalTicks); } @@ -518,6 +536,27 @@ public class TimelineWindow { ImGui.end(); } + private static int findClosestKeyframeForSnap(EditorState editorState, int tick) { + int closestTick = -1; + for (KeyframeTrack track : editorState.keyframeTracks) { + Integer floor = track.keyframesByTick.floorKey(tick); + Integer ceil = track.keyframesByTick.ceilingKey(tick); + + float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor); + float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil); + + Integer closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE); + if (closest != null) { + if (closestTick == -1) { + closestTick = closest; + } else if (Math.abs(closest - tick) < Math.abs(closestTick - tick)) { + closestTick = closest; + } + } + } + return closestTick; + } + private static void handleKeyPresses(ReplayServer replayServer, int cursorTicks, EditorState editorState, int totalTicks) { boolean pressedIn = ImGui.isKeyPressed(GLFW.GLFW_KEY_I, false); boolean pressedOut = ImGui.isKeyPressed(GLFW.GLFW_KEY_O, false); @@ -528,7 +567,7 @@ 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)) { + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_P, false)) { togglePaused(replayServer, editorState); } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT, false)) { @@ -1656,7 +1695,7 @@ public class TimelineWindow { } private static void renderPlaybackHead(int cursorX, float x, int middleX, float width, int cursorTicks, int currentReplayTick, ImDrawList drawList, float y, int middleY, int timestampHeight, float height, int zoomBarHeight) { - if (cursorX > x + middleX -10 && cursorX < x + width +10) { + if (cursorX > middleX - 10 && cursorX < width +10) { int colour = -1; if (cursorTicks < currentReplayTick) { colour = 0x80FFFFFF; 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 61f0f91..9b1761c 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 @@ -201,6 +201,11 @@ public class VisualsWindow { } } + // Night vision + if (ImGui.checkbox("Night Vision", visuals.overrideNightVision)) { + visuals.overrideNightVision = !visuals.overrideNightVision; + } + // Camera shake if (ImGui.checkbox("Camera Shake", visuals.overrideCameraShake)) { visuals.overrideCameraShake = !visuals.overrideCameraShake; diff --git a/src/main/java/com/moulberry/flashback/exporting/AsyncFFmpegVideoWriter.java b/src/main/java/com/moulberry/flashback/exporting/AsyncFFmpegVideoWriter.java index e46b293..990d753 100644 --- a/src/main/java/com/moulberry/flashback/exporting/AsyncFFmpegVideoWriter.java +++ b/src/main/java/com/moulberry/flashback/exporting/AsyncFFmpegVideoWriter.java @@ -3,6 +3,7 @@ package com.moulberry.flashback.exporting; import com.mojang.blaze3d.platform.NativeImage; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.SneakyThrow; +import com.moulberry.flashback.combo_options.AudioCodec; import org.bytedeco.ffmpeg.avutil.AVFrame; import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor; import org.bytedeco.ffmpeg.global.avutil; @@ -91,7 +92,7 @@ public class AsyncFFmpegVideoWriter implements AutoCloseable, VideoWriter { int audioChannels = 0; if (settings.recordAudio()) { - if (settings.stereoAudio()) { + if (settings.audioCodec() == AudioCodec.VORBIS || settings.stereoAudio()) { audioChannels = 2; } else { audioChannels = 1; diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java index 8434b3b..ff3c590 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -27,11 +27,16 @@ import net.minecraft.Util; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.screens.CreditsAndAttributionScreen; +import net.minecraft.client.gui.screens.WinScreen; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.FogRenderer; import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.client.resources.sounds.SoundInstance; import net.minecraft.network.chat.Component; +import net.minecraft.sounds.SoundEvents; import net.minecraft.util.FormattedCharSequence; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; @@ -129,6 +134,7 @@ public class ExportJob { } this.running = true; Minecraft.getInstance().mouseHandler.releaseMouse(); + Minecraft.getInstance().getSoundManager().stop(); UUID uuid = UUID.randomUUID(); @@ -160,9 +166,21 @@ public class ExportJob { this.running = false; this.shouldChangeFramebufferSize = false; + // Reset display size Minecraft.getInstance().options.guiScale().set(oldGuiScale); Minecraft.getInstance().resizeDisplay(); + // Refreeze server & client + replayServer.replayPaused = true; + ClientLevel level = Minecraft.getInstance().level; + if (level != null) { + level.tickRateManager().setFrozen(true); + } + + Minecraft.getInstance().getSoundManager().stop(); + Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.NOTE_BLOCK_CHIME, 1.0f)); + Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.NOTE_BLOCK_BELL, 1.0f)); + try { Files.deleteIfExists(exportTempFile); } catch (IOException ignored) {} @@ -210,7 +228,6 @@ public class ExportJob { } Minecraft.getInstance().resizeDisplay(); - DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate()); int clientTickCount = 0; diff --git a/src/main/java/com/moulberry/flashback/exporting/PNGSequenceVideoWriter.java b/src/main/java/com/moulberry/flashback/exporting/PNGSequenceVideoWriter.java index 77dba94..7a6b8ae 100644 --- a/src/main/java/com/moulberry/flashback/exporting/PNGSequenceVideoWriter.java +++ b/src/main/java/com/moulberry/flashback/exporting/PNGSequenceVideoWriter.java @@ -12,6 +12,8 @@ import org.lwjgl.system.MemoryUtil; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -38,6 +40,9 @@ public class PNGSequenceVideoWriter implements VideoWriter { } private Thread createEncodeThread() { + boolean outputIsDirectory = Files.isDirectory(this.settings.output()); + boolean encodeMultiple = outputIsDirectory || this.settings.startTick() != this.settings.endTick(); + Thread encodeThread = new Thread(() -> { while (true) { NativeImage src; @@ -69,8 +74,20 @@ public class PNGSequenceVideoWriter implements VideoWriter { } this.sequenceNumber += 1; - String filename = String.format("%04d.png", this.sequenceNumber); - src.writeToFile(this.settings.output().resolve(filename)); + + Path output = this.settings.output(); + if (encodeMultiple) { + if (outputIsDirectory) { + String filename = String.format("%04d.png", this.sequenceNumber); + src.writeToFile(output.resolve(filename)); + } else { + String filename = output.getFileName().toString(); + filename += String.format("-%04d.png", this.sequenceNumber); + src.writeToFile(output.getParent().resolve(filename)); + } + } else { + src.writeToFile(this.settings.output()); + } } catch (Throwable t) { this.threadedError.set(t); this.finishEncodeThread.set(true); diff --git a/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java b/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java index a2edd25..deb1fa9 100644 --- a/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java +++ b/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java @@ -1,5 +1,6 @@ package com.moulberry.flashback.exporting; +import com.moulberry.flashback.Flashback; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.PlayerInfo; @@ -54,14 +55,14 @@ public class PerfectFrames { if (level != null) { if (forceFrameReady) { - System.err.println("Waiting for skin loading took too long, ignoring..."); + Flashback.LOGGER.error("Waiting for skin loading took too long, ignoring..."); for (AbstractClientPlayer player : level.players()) { if (player == Minecraft.getInstance().player) { continue; } PlayerInfo playerInfo = player.getPlayerInfo(); if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) { - System.err.println("Took too long to load skin for " + player.getUUID()); + Flashback.LOGGER.error("Took too long to load skin for {}", player.getUUID()); ignoreSkinLoading.add(player.getUUID()); } } diff --git a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java index ec568eb..859155e 100644 --- a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java +++ b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java @@ -194,33 +194,6 @@ public class AsyncReplaySaver { gamePacketCodec.encode(writer.friendlyByteBuf(), packet); writer.finishAction(ActionGamePacket.INSTANCE); } - - if (packet instanceof ClientboundLoginPacket) { - LocalPlayer localPlayer = Minecraft.getInstance().player; - if (localPlayer != null) { - writer.startAction(ActionCreateLocalPlayer.INSTANCE); - RegistryFriendlyByteBuf registryFriendlyByteBuf = writer.friendlyByteBuf(); - registryFriendlyByteBuf.writeUUID(localPlayer.getUUID()); - registryFriendlyByteBuf.writeDouble(localPlayer.getX()); - registryFriendlyByteBuf.writeDouble(localPlayer.getY()); - registryFriendlyByteBuf.writeDouble(localPlayer.getZ()); - registryFriendlyByteBuf.writeFloat(localPlayer.getXRot()); - registryFriendlyByteBuf.writeFloat(localPlayer.getYRot()); - registryFriendlyByteBuf.writeFloat(localPlayer.getYHeadRot()); - registryFriendlyByteBuf.writeVec3(localPlayer.getDeltaMovement()); - - GameProfile currentProfile = localPlayer.getGameProfile(); - GameProfile newProfile = new GameProfile(currentProfile.getId(), currentProfile.getName()); - newProfile.getProperties().putAll(Minecraft.getInstance().getGameProfile().getProperties()); - newProfile.getProperties().putAll(currentProfile.getProperties()); - - ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, newProfile); - - registryFriendlyByteBuf.writeVarInt(Minecraft.getInstance().gameMode.getPlayerMode().getId()); - - writer.finishAction(ActionCreateLocalPlayer.INSTANCE); - } - } } if (lastChunkCacheIndex >= 0) { @@ -246,7 +219,6 @@ public class AsyncReplaySaver { } } - public void writeConfigurationPackets(StreamCodec> configurationPacketCodec, List> packets) { List> packetCopy = new ArrayList<>(packets); diff --git a/src/main/java/com/moulberry/flashback/io/ReplayCombiner.java b/src/main/java/com/moulberry/flashback/io/ReplayCombiner.java new file mode 100644 index 0000000..4176428 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/io/ReplayCombiner.java @@ -0,0 +1,329 @@ +package com.moulberry.flashback.io; + +import com.google.gson.JsonObject; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FlashbackGson; +import com.moulberry.flashback.action.Action; +import com.moulberry.flashback.action.ActionLevelChunkCached; +import com.moulberry.flashback.action.ActionRegistry; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.record.FlashbackChunkMeta; +import com.moulberry.flashback.record.FlashbackMeta; +import com.moulberry.flashback.record.ReplayMarker; +import com.replaymod.replaystudio.lib.viaversion.libs.fastutil.ints.Int2ObjectMap; +import com.replaymod.replaystudio.lib.viaversion.libs.fastutil.ints.Int2ObjectOpenHashMap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.buffer.UnpooledDirectByteBuf; +import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.resources.ResourceLocation; + +import java.io.BufferedOutputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.zip.Deflater; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ReplayCombiner { + + public static void combine(RegistryAccess registryAccess, Path first, Path second, Path output) throws Exception { + StreamCodec> gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); + + try (FileSystem firstFileSystem = FileSystems.newFileSystem(first); + FileSystem secondFileSystem = FileSystems.newFileSystem(second)) { + + List levelChunkPackets = new ArrayList<>(); + Int2IntMap levelChunkMappingsFirst = new Int2IntOpenHashMap(); + Int2IntMap levelChunkMappingsSecond = new Int2IntOpenHashMap(); + + extractChunks(registryAccess, firstFileSystem, gamePacketCodec, levelChunkPackets, levelChunkMappingsFirst); + extractChunks(registryAccess, secondFileSystem, gamePacketCodec, levelChunkPackets, levelChunkMappingsSecond); + + // Read metadata + Path metadataPath = firstFileSystem.getPath("/metadata.json"); + String metadataJson = Files.readString(metadataPath); + FlashbackMeta firstMetadata = FlashbackMeta.fromJson(FlashbackGson.COMPRESSED.fromJson(metadataJson, JsonObject.class)); + if (firstMetadata == null) { + throw new RuntimeException("Unable to load /metadata.json from first replay"); + } + + Path secondMetadataPath = secondFileSystem.getPath("/metadata.json"); + String secondMetadataJson = Files.readString(secondMetadataPath); + FlashbackMeta secondMetadata = FlashbackMeta.fromJson(FlashbackGson.COMPRESSED.fromJson(secondMetadataJson, JsonObject.class)); + if (secondMetadata == null) { + throw new RuntimeException("Unable to load /metadata.json from second replay"); + } + + if (firstMetadata.dataVersion != secondMetadata.dataVersion) { + throw new RuntimeException("Replays were created on different versions of the game, unable to combine"); + } + + firstMetadata.replayIdentifier = UUID.randomUUID(); + for (Map.Entry entry : secondMetadata.replayMarkers.entrySet()) { + firstMetadata.replayMarkers.put(entry.getKey() + firstMetadata.totalTicks, entry.getValue()); + } + firstMetadata.totalTicks = firstMetadata.totalTicks + secondMetadata.totalTicks; + + record ReplayChunk(Path path, Int2IntMap levelChunkMappings) {} + Map newReplayChunks = new HashMap<>(); + + for (String name : firstMetadata.chunks.keySet()) { + newReplayChunks.put(name, new ReplayChunk(firstFileSystem.getPath("/" + name), levelChunkMappingsFirst)); + } + + boolean isFirstChunkOfSecondReplay = true; + for (Map.Entry entry : secondMetadata.chunks.entrySet()) { + String newName = "c" + firstMetadata.chunks.size() + ".flashback"; + if (isFirstChunkOfSecondReplay) { + isFirstChunkOfSecondReplay = false; + entry.getValue().forcePlaySnapshot = true; + } + firstMetadata.chunks.put(newName, entry.getValue()); + newReplayChunks.put(newName, new ReplayChunk(secondFileSystem.getPath("/" + entry.getKey()), levelChunkMappingsSecond)); + } + + // Actually write + FileOutputStream fos = new FileOutputStream(output.toFile()); + BufferedOutputStream bos = new BufferedOutputStream(fos); + ZipOutputStream zipOut = new ZipOutputStream(bos); + zipOut.setLevel(Deflater.BEST_SPEED); + + // Write metadata + ZipEntry zipEntry = new ZipEntry("metadata.json"); + zipOut.putNextEntry(zipEntry); + zipOut.write(FlashbackGson.COMPRESSED.toJson(firstMetadata.toJson()).getBytes(StandardCharsets.UTF_8)); + zipOut.closeEntry(); + + // Write chunked level chunk caches + int lastCacheIndex = -1; + RegistryFriendlyByteBuf chunkCacheOutput = null; + for (int i = 0; i < levelChunkPackets.size(); i++) { + int cacheIndex = i / ReplayServer.CHUNK_CACHE_SIZE; + + if (chunkCacheOutput == null) { + lastCacheIndex = cacheIndex; + chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), registryAccess); + } else if (cacheIndex != lastCacheIndex) { + byte[] bytes = new byte[chunkCacheOutput.writerIndex()]; + chunkCacheOutput.getBytes(0, bytes); + + zipEntry = new ZipEntry("level_chunk_caches/" + lastCacheIndex); + zipOut.putNextEntry(zipEntry); + zipOut.write(bytes); + zipOut.closeEntry(); + + chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), registryAccess); + } + + // Write placeholder value for size + int startWriterIndex = chunkCacheOutput.writerIndex(); + chunkCacheOutput.writeInt(-1); + + // Write chunk packet + gamePacketCodec.encode(chunkCacheOutput, levelChunkPackets.get(i)); + int endWriterIndex = chunkCacheOutput.writerIndex(); + + // Write real size value + int size = endWriterIndex - startWriterIndex - 4; + chunkCacheOutput.writerIndex(startWriterIndex); + chunkCacheOutput.writeInt(size); + chunkCacheOutput.writerIndex(endWriterIndex); + } + + if (chunkCacheOutput != null) { + byte[] bytes = new byte[chunkCacheOutput.writerIndex()]; + chunkCacheOutput.getBytes(0, bytes); + + zipEntry = new ZipEntry("level_chunk_caches/" + lastCacheIndex); + zipOut.putNextEntry(zipEntry); + zipOut.write(bytes); + zipOut.closeEntry(); + } + + // Write icon + zipEntry = new ZipEntry("icon.png"); + zipOut.putNextEntry(zipEntry); + Files.copy(firstFileSystem.getPath("/icon.png"), zipOut); + zipOut.closeEntry(); + + // Write chunks + for (Map.Entry entry : newReplayChunks.entrySet()) { + zipEntry = new ZipEntry(entry.getKey()); + zipOut.putNextEntry(zipEntry); + + Path path = entry.getValue().path(); + byte[] replayChunk = Files.readAllBytes(path); + RegistryFriendlyByteBuf inputBuf = new RegistryFriendlyByteBuf(Unpooled.wrappedBuffer(replayChunk), registryAccess); + FriendlyByteBuf outputBuf = new FriendlyByteBuf(Unpooled.buffer()); + + int magic = inputBuf.readInt(); + if (magic != Flashback.MAGIC) { + throw new RuntimeException("Invalid magic"); + } + outputBuf.writeInt(magic); + + int levelChunkCachedActionId = -1; + int actions = inputBuf.readVarInt(); + outputBuf.writeVarInt(actions); + for (int i = 0; i < actions; i++) { + ResourceLocation actionName = inputBuf.readResourceLocation(); + outputBuf.writeResourceLocation(actionName); + + Action action = ActionRegistry.getAction(actionName); + + if (action instanceof ActionLevelChunkCached) { + levelChunkCachedActionId = i; + } + } + + if (levelChunkCachedActionId == -1) { + Files.copy(entry.getValue().path, zipOut); + } else { + int snapshotSize = inputBuf.readInt(); + if (snapshotSize < 0) { + throw new RuntimeException("Invalid snapshot size: " + snapshotSize + " (0x" + Integer.toHexString(snapshotSize) + ")"); + } + + int snapshotInputEnd = inputBuf.readerIndex() + snapshotSize; + + int snapshotOutputWriterIndex = outputBuf.writerIndex(); + outputBuf.writeInt(0xDEADBEEF); + int snapshotStartWriterIndex = outputBuf.writerIndex(); + int snapshotEndWriterIndex = outputBuf.writerIndex(); + + while (inputBuf.readerIndex() < inputBuf.writerIndex()) { + boolean inSnapshot = inputBuf.readerIndex() < snapshotInputEnd; + + int id = inputBuf.readVarInt(); + int size = inputBuf.readInt(); + if (id == levelChunkCachedActionId) { + int cachedChunkId = inputBuf.readVarInt(); + + if (!entry.getValue().levelChunkMappings.containsKey(cachedChunkId)) { + throw new RuntimeException("Missing cached chunk id " + cachedChunkId); + } + + int newCachedChunkId = entry.getValue().levelChunkMappings.get(cachedChunkId); + + outputBuf.writeVarInt(id); + int sizeWriterIndex = outputBuf.writerIndex(); + outputBuf.writeInt(0); + int cachedIdWriterIndex = outputBuf.writerIndex(); + outputBuf.writeVarInt(newCachedChunkId); + int endWriterIndex = outputBuf.writerIndex(); + + outputBuf.writerIndex(sizeWriterIndex); + outputBuf.writeInt(endWriterIndex - cachedIdWriterIndex); + outputBuf.writerIndex(endWriterIndex); + } else { + outputBuf.writeVarInt(id); + outputBuf.writeInt(size); + outputBuf.writeBytes(inputBuf, size); + } + + if (inSnapshot) { + snapshotEndWriterIndex = outputBuf.writerIndex(); + } + } + + int endWriterIndex = outputBuf.writerIndex(); + outputBuf.writerIndex(snapshotOutputWriterIndex); + outputBuf.writeInt(snapshotEndWriterIndex - snapshotStartWriterIndex); + outputBuf.writerIndex(endWriterIndex); + + byte[] bytes = new byte[outputBuf.writerIndex()]; + outputBuf.getBytes(0, bytes); + zipOut.write(bytes); + } + + zipOut.closeEntry(); + } + + zipOut.close(); + bos.close(); + fos.close(); + } + } + + private static void extractChunks(RegistryAccess registryAccess, FileSystem fileSystem, StreamCodec> gamePacketCodec, + List packets, Int2IntMap levelChunkMappings) throws IOException { + Path levelChunkCachePath = fileSystem.getPath("/level_chunk_cache"); + if (Files.exists(levelChunkCachePath)) { + loadLevelChunkCache(gamePacketCodec, registryAccess, levelChunkCachePath, 0, packets, levelChunkMappings); + } + + int index = 0; + while (true) { + levelChunkCachePath = fileSystem.getPath("/level_chunk_caches/"+index); + if (Files.exists(levelChunkCachePath)) { + loadLevelChunkCache(gamePacketCodec, registryAccess, levelChunkCachePath, index * ReplayServer.CHUNK_CACHE_SIZE, packets, levelChunkMappings); + index += 1; + } else { + break; + } + } + } + + private static void loadLevelChunkCache(StreamCodec> gamePacketCodec, RegistryAccess registryAccess, + Path levelChunkCachePath, int chunkCacheIndex, List packets, Int2IntMap levelChunkMappings) throws IOException { + try (InputStream is = Files.newInputStream(levelChunkCachePath)) { + while (true) { + byte[] sizeBuffer = is.readNBytes(4); + if (sizeBuffer.length < 4) { + break; + } + + int size = (sizeBuffer[0] & 0xff) << 24 | + (sizeBuffer[1] & 0xff) << 16 | + (sizeBuffer[2] & 0xff) << 8 | + sizeBuffer[3] & 0xff; + + byte[] chunk = is.readNBytes(size); + if (chunk.length < size) { + Flashback.LOGGER.error("Ran out of bytes while reading level_chunk_cache, needed {}, had {}", + size, chunk.length); + break; + } + + RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(Unpooled.wrappedBuffer(chunk), registryAccess); + + try { + Packet packet = gamePacketCodec.decode(registryFriendlyByteBuf); + if (packet instanceof ClientboundLevelChunkWithLightPacket levelChunkWithLightPacket) { + levelChunkMappings.put(chunkCacheIndex, packets.size()); + packets.add(levelChunkWithLightPacket); + } else { + throw new IllegalStateException("Level chunk cache contains wrong packet: " + packet); + } + } catch (Exception e) { + Flashback.LOGGER.error("Encountered error while reading level_chunk_cache", e); + } + + chunkCacheIndex += 1; + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/io/ReplayWriter.java b/src/main/java/com/moulberry/flashback/io/ReplayWriter.java index 069a975..f90a5ec 100644 --- a/src/main/java/com/moulberry/flashback/io/ReplayWriter.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayWriter.java @@ -28,7 +28,7 @@ public class ReplayWriter { private static final int STATE_EMPTY = 0; private static final int STATE_WRITING_SNAPSHOT = 1; private static final int STATE_WRITING_DATA = 2; - private int state = STATE_EMPTY; + public int state = STATE_EMPTY; public ReplayWriter(RegistryAccess registryAccess) { this.dataBufferInner = Unpooled.buffer(); diff --git a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java index 7ac0b24..fc0e7f7 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java @@ -1,6 +1,7 @@ package com.moulberry.flashback.keyframe; import com.google.gson.*; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; @@ -17,14 +18,14 @@ import java.util.function.Consumer; public abstract class Keyframe { - private InterpolationType interpolationType = InterpolationType.DEFAULT; + private InterpolationType interpolationType = InterpolationType.getDefault(); public InterpolationType interpolationType() { return interpolationType; } public void interpolationType(InterpolationType interpolationType) { - this.interpolationType = Objects.requireNonNullElse(interpolationType, InterpolationType.DEFAULT); + this.interpolationType = Objects.requireNonNullElse(interpolationType, InterpolationType.getDefault()); } public abstract KeyframeType keyframeType(); 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 27c5957..a75abab 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java @@ -11,15 +11,9 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.spline.CatmullRom; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; -import com.moulberry.flashback.visuals.CameraPath; -import imgui.ImGui; -import imgui.type.ImFloat; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; -import org.joml.Quaterniond; -import org.joml.Quaterniond; import org.joml.Vector3d; -import org.joml.Vector3f; import java.lang.reflect.Type; import java.util.function.Consumer; @@ -45,7 +39,7 @@ public class CameraKeyframe extends Keyframe { } public CameraKeyframe(Vector3d position, float yaw, float pitch, float roll) { - this(position, yaw, pitch, roll, InterpolationType.DEFAULT); + this(position, yaw, pitch, roll, InterpolationType.getDefault()); } public CameraKeyframe(Vector3d position, float yaw, float pitch, float roll, InterpolationType interpolationType) { @@ -56,8 +50,16 @@ public class CameraKeyframe extends Keyframe { this.interpolationType(interpolationType); } - public Quaterniond getQuaternion() { - return new Quaterniond().rotationYXZ((float) -Math.toRadians(this.yaw), (float) Math.toRadians(this.pitch), 0.0); + public Vector3d getNormal() { + double yawRad = Math.toRadians(-this.yaw); + double cosYaw = Math.cos((float)yawRad); + double sinYaw = Math.sin((float)yawRad); + + double pitchRad = Math.toRadians(this.pitch); + double cosPitch = Math.cos((float)pitchRad); + double sinPitch = Math.sin((float)pitchRad); + + return new Vector3d(sinYaw * cosPitch, -sinPitch, cosYaw * cosPitch); } @Override @@ -104,38 +106,11 @@ public class CameraKeyframe extends Keyframe { } } - private void apply(KeyframeHandler keyframeHandler, Vector3d position, Quaterniond quaternion, float roll) { - Vector3d euler = quaternion.getEulerAnglesYXZ(new Vector3d()); - double yaw = Mth.wrapDegrees(Math.toDegrees(euler.y)); - double pitch = Mth.wrapDegrees(Math.toDegrees(euler.x)); - // Handle singularity - double test = quaternion.y * quaternion.z - quaternion.w * quaternion.x; - final double MIN_TEST = 0.49999; - final double MAX_TEST = 0.499999; - if (test > MIN_TEST) { - double fixedYaw = Mth.wrapDegrees(Math.toDegrees(2 * Math.atan2(quaternion.z, quaternion.w))); - if (test >= MAX_TEST) { - yaw = fixedYaw; - } else { - yaw = yaw + Mth.wrapDegrees(fixedYaw - yaw) * (test - MIN_TEST) / (MAX_TEST - MIN_TEST); - } - } else if (test < -MIN_TEST) { - double fixedYaw = Mth.wrapDegrees(Math.toDegrees(-2 * Math.atan2(quaternion.z, quaternion.w))); - if (test <= -MAX_TEST) { - yaw = fixedYaw; - } else { - yaw = yaw + Mth.wrapDegrees(fixedYaw - yaw) * (test - -MIN_TEST) / (-MAX_TEST - -MIN_TEST); - } - } - - // Apply position - keyframeHandler.applyCameraPosition(position, -yaw, pitch, roll); - } @Override public void apply(KeyframeHandler keyframeHandler) { - apply(keyframeHandler, this.position, this.getQuaternion(), this.roll); + keyframeHandler.applyCameraPosition(this.position, this.yaw, this.pitch, this.roll); } @Override @@ -148,11 +123,13 @@ public class CameraKeyframe extends Keyframe { double x = Interpolation.linear(this.position.x, other.position.x, amount); double y = Interpolation.linear(this.position.y, other.position.y, amount); double z = Interpolation.linear(this.position.z, other.position.z, amount); - float roll = Interpolation.linear(this.roll, other.roll, amount); - Quaterniond quaternion = Interpolation.linear(this.getQuaternion(), other.getQuaternion(), amount); - Vector3d position = new Vector3d(x, y, z); - apply(keyframeHandler, position, quaternion, roll); + + float yaw = Interpolation.linearAngle(this.yaw, other.yaw, amount); + float pitch = Interpolation.linearAngle(this.pitch, other.pitch, amount); + float roll = Interpolation.linearAngle(this.roll, other.roll, amount); + + keyframeHandler.applyCameraPosition(position, yaw, pitch, roll); } @Override @@ -171,11 +148,13 @@ public class CameraKeyframe extends Keyframe { double z = position.z; // Calculate rotation - Quaterniond rotation = CatmullRom.rotation(this.getQuaternion(), - ((CameraKeyframe)p1).getQuaternion(), ((CameraKeyframe)p2).getQuaternion(), - ((CameraKeyframe)p3).getQuaternion(), time1, time2, time3, amount); - - float roll = CatmullRom.value(this.roll, + float yaw = CatmullRom.degrees(this.yaw, + ((CameraKeyframe)p1).yaw, ((CameraKeyframe)p2).yaw, + ((CameraKeyframe)p3).yaw, time1, time2, time3, amount); + float pitch = CatmullRom.degrees(this.pitch, + ((CameraKeyframe)p1).pitch, ((CameraKeyframe)p2).pitch, + ((CameraKeyframe)p3).pitch, time1, time2, time3, amount); + float roll = CatmullRom.degrees(this.roll, ((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll, ((CameraKeyframe)p3).roll, time1, time2, time3, amount); @@ -183,27 +162,31 @@ public class CameraKeyframe extends Keyframe { double linearX = Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount); double linearY = Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount); double linearZ = Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount); - float linearRoll = Interpolation.linear(((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll, lerpAmount); - - Quaterniond linearQuaternion = Interpolation.linear(((CameraKeyframe)p1).getQuaternion(), - ((CameraKeyframe)p2).getQuaternion(), lerpAmount); + float linearYaw = Interpolation.linearAngle(((CameraKeyframe)p1).yaw, ((CameraKeyframe)p2).yaw, lerpAmount); + float linearPitch = Interpolation.linearAngle(((CameraKeyframe)p1).pitch, ((CameraKeyframe)p2).pitch, lerpAmount); + float linearRoll = Interpolation.linearAngle(((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll, lerpAmount); if (lerpFromRight) { x = Interpolation.linear(x, linearX, amount); y = Interpolation.linear(y, linearY, amount); z = Interpolation.linear(z, linearZ, amount); - roll = Interpolation.linear(roll, linearRoll, amount); - rotation = Interpolation.linear(rotation, linearQuaternion, amount); + yaw = Interpolation.linearAngle(yaw, linearYaw, amount); + pitch = Interpolation.linearAngle(pitch, linearPitch, amount); + roll = Interpolation.linearAngle(roll, linearRoll, amount); } else { x = Interpolation.linear(linearX, x, amount); y = Interpolation.linear(linearY, y, amount); z = Interpolation.linear(linearZ, z, amount); - roll = Interpolation.linear(linearRoll, roll, amount); - rotation = Interpolation.linear(linearQuaternion, rotation, amount); + yaw = Interpolation.linearAngle(linearYaw, yaw, amount); + pitch = Interpolation.linearAngle(linearPitch, pitch, amount); + roll = Interpolation.linearAngle(linearRoll, roll, amount); } } - apply(keyframeHandler, new Vector3d(x, y, z), rotation, roll); + position.x = x; + position.y = y; + position.z = z; + keyframeHandler.applyCameraPosition(position, yaw, pitch, roll); } public static class TypeAdapter implements JsonSerializer, JsonDeserializer { 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 be2bbc3..dc6c4c5 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java @@ -38,7 +38,7 @@ public class CameraOrbitKeyframe extends Keyframe { public float pitch; public CameraOrbitKeyframe(Vector3d center, float distance, float yaw, float pitch) { - this(center, distance, yaw, pitch, InterpolationType.DEFAULT); + this(center, distance, yaw, pitch, InterpolationType.getDefault()); } public CameraOrbitKeyframe(Vector3d center, float distance, float yaw, float pitch, InterpolationType interpolationType) { diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java index c653d0b..cee20dd 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java @@ -30,7 +30,7 @@ public class CameraShakeKeyframe extends Keyframe { private boolean splitParams; public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, boolean splitParams) { - this(frequencyX, amplitudeX, frequencyY, amplitudeY, splitParams, InterpolationType.DEFAULT); + this(frequencyX, amplitudeX, frequencyY, amplitudeY, splitParams, InterpolationType.getDefault()); } public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, boolean splitParams, InterpolationType interpolationType) { diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java index 942370e..f1d6b1c 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java @@ -19,7 +19,7 @@ public class FOVKeyframe extends Keyframe { public float fov; public FOVKeyframe(float fov) { - this(fov, InterpolationType.DEFAULT); + this(fov, InterpolationType.getDefault()); } public FOVKeyframe(float fov, InterpolationType interpolationType) { diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java index 4edc099..6be59db 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java @@ -18,7 +18,7 @@ public class TickrateKeyframe extends Keyframe { private float tickrate; public TickrateKeyframe(float tickrate) { - this(tickrate, InterpolationType.DEFAULT); + this(tickrate, InterpolationType.getDefault()); } public TickrateKeyframe(float tickrate, InterpolationType interpolationType) { 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 7aae723..d071355 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java @@ -20,7 +20,7 @@ public class TimeOfDayKeyframe extends Keyframe { public int time; public TimeOfDayKeyframe(int time) { - this(time, InterpolationType.DEFAULT); + this(time, InterpolationType.getDefault()); } public TimeOfDayKeyframe(int time, InterpolationType interpolationType) { diff --git a/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java b/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java index b832db8..d9e1430 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java @@ -1,18 +1,28 @@ package com.moulberry.flashback.keyframe.interpolation; -public enum InterpolationType { +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.combo_options.ComboOption; +import com.moulberry.flashback.configuration.FlashbackConfig; - SMOOTH(SidedInterpolationType.SMOOTH, SidedInterpolationType.SMOOTH), - LINEAR(SidedInterpolationType.LINEAR, SidedInterpolationType.LINEAR), - EASE_IN(SidedInterpolationType.EASE, SidedInterpolationType.LINEAR), - EASE_OUT(SidedInterpolationType.LINEAR, SidedInterpolationType.EASE), - EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE), - HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD); +public enum InterpolationType implements ComboOption { - public static InterpolationType DEFAULT = SMOOTH; + SMOOTH(SidedInterpolationType.SMOOTH, SidedInterpolationType.SMOOTH, "Smooth"), + LINEAR(SidedInterpolationType.LINEAR, SidedInterpolationType.LINEAR, "Linear"), + EASE_IN(SidedInterpolationType.EASE, SidedInterpolationType.LINEAR, "Ease In (Linear Out)"), + EASE_OUT(SidedInterpolationType.LINEAR, SidedInterpolationType.EASE, "Ease Out (Linear In)"), + EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE, "Ease In/Out"), + HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD, "Hold"); public static final InterpolationType[] INTERPOLATION_TYPES = values(); + public static InterpolationType getDefault() { + FlashbackConfig config = Flashback.getConfig(); + if (config != null && config.defaultInterpolationType != null) { + return config.defaultInterpolationType; + } + return InterpolationType.SMOOTH; + } + public static String[] NAMES = new String[] { "Smooth", "Linear", @@ -22,12 +32,18 @@ public enum InterpolationType { "Hold" }; - public SidedInterpolationType leftSide; - public SidedInterpolationType rightSide; + public final SidedInterpolationType leftSide; + public final SidedInterpolationType rightSide; + public final String name; - InterpolationType(SidedInterpolationType leftSide, SidedInterpolationType rightSide) { + InterpolationType(SidedInterpolationType leftSide, SidedInterpolationType rightSide, String name) { this.leftSide = leftSide; this.rightSide = rightSide; + this.name = name; } + @Override + public String text() { + return this.name; + } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/CameraKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/CameraKeyframeType.java index b563baa..a743f7d 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/CameraKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/CameraKeyframeType.java @@ -4,6 +4,7 @@ import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.Entity; import org.jetbrains.annotations.Nullable; public class CameraKeyframeType implements KeyframeType { @@ -25,9 +26,13 @@ public class CameraKeyframeType implements KeyframeType { @Override public @Nullable CameraKeyframe createDirect() { - LocalPlayer player = Minecraft.getInstance().player; - if (player != null) { - return new CameraKeyframe(player); + Entity entity = Minecraft.getInstance().cameraEntity; + if (entity != null) { + return new CameraKeyframe(entity); + } + entity = Minecraft.getInstance().player; + if (entity != null) { + return new CameraKeyframe(entity); } return null; } diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinAbstractClientPlayer.java b/src/main/java/com/moulberry/flashback/mixin/MixinAbstractClientPlayer.java new file mode 100644 index 0000000..c3f611d --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/MixinAbstractClientPlayer.java @@ -0,0 +1,45 @@ +package com.moulberry.flashback.mixin; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import com.mojang.authlib.yggdrasil.ProfileResult; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.resources.PlayerSkin; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +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.CallbackInfoReturnable; + +@Mixin(AbstractClientPlayer.class) +public abstract class MixinAbstractClientPlayer extends Player { + + public MixinAbstractClientPlayer(Level level, BlockPos blockPos, float f, GameProfile gameProfile) { + super(level, blockPos, f, gameProfile); + } + + @Unique + private PlayerInfo skinOverridePlayerInfo = null; + + @Inject(method = "getSkin", at = @At("HEAD"), cancellable = true, require = 0) + public void getSkin(CallbackInfoReturnable cir) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + GameProfile skinOverride = editorState.skinOverride.get(this.uuid); + if (skinOverride != null) { + if (skinOverridePlayerInfo == null || skinOverridePlayerInfo.getProfile() != skinOverride) { + skinOverridePlayerInfo = new PlayerInfo(skinOverride, false); + } + cir.setReturnValue(skinOverridePlayerInfo.getSkin()); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java index 71b4818..1171337 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java @@ -73,7 +73,7 @@ public abstract class MixinLevelRenderer { ReplayUI.lastViewQuaternion = camera.rotation(); } - @Inject(method = "renderSectionLayer", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderSectionLayer", at = @At("HEAD"), cancellable = true, require = 0) public void renderSectionLayer(RenderType renderType, double d, double e, double f, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null) { @@ -83,7 +83,7 @@ public abstract class MixinLevelRenderer { } } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", ordinal = 2, shift = At.Shift.AFTER)) + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", ordinal = 2, shift = At.Shift.AFTER), require = 0) public void renderLevel_renderCutoutLayer(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().transparent()) { RenderTarget main = Minecraft.getInstance().mainRenderTarget; @@ -109,7 +109,7 @@ public abstract class MixinLevelRenderer { } } - @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER)) + @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER), require = 0) public void renderLevel_levelFogColor(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null) { @@ -137,13 +137,13 @@ public abstract class MixinLevelRenderer { } } - @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;render(Lnet/minecraft/world/level/block/entity/BlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V")) + @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;render(Lnet/minecraft/world/level/block/entity/BlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"), require = 0) public boolean renderLevel_renderBlockEntity(BlockEntityRenderDispatcher instance, BlockEntity blockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource) { EditorState editorState = EditorStateManager.getCurrent(); return editorState == null || editorState.replayVisuals.renderBlocks; } - @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V")) + @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"), require = 0) public boolean renderLevel_renderEntity(LevelRenderer instance, Entity entity, double d, double e, double f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource) { EditorState editorState = EditorStateManager.getCurrent(); if (entity instanceof Player) { @@ -153,7 +153,7 @@ public abstract class MixinLevelRenderer { } } - @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;")) + @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;"), require = 0) public CloudStatus renderLevel_getCloudsType(Options instance, Operation original) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.renderSky) { @@ -163,19 +163,19 @@ public abstract class MixinLevelRenderer { } } - @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V")) + @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V"), require = 0) public boolean renderLevel_renderParticles(ParticleEngine instance, LightTexture lightTexture, Camera camera, float f) { EditorState editorState = EditorStateManager.getCurrent(); return editorState == null || editorState.replayVisuals.renderParticles; } - @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSky(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FLnet/minecraft/client/Camera;ZLjava/lang/Runnable;)V")) + @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSky(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FLnet/minecraft/client/Camera;ZLjava/lang/Runnable;)V"), require = 0) public boolean renderLevel_renderSky(LevelRenderer instance, Matrix4f matrix4f, Matrix4f matrix4f2, float f, Camera camera, boolean bl, Runnable runnable) { EditorState editorState = EditorStateManager.getCurrent(); return editorState == null || editorState.replayVisuals.renderSky; } - @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V")) + @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V"), require = 0) public void setupRender(LevelRenderer instance, Camera camera, Frustum frustum, boolean capturedFrustum, boolean isSpectator, Operation original) { if (PerfectFrames.isEnabled()) { boolean doCompile = true; diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java index ca49025..7a9addc 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java @@ -8,7 +8,9 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.VertexFormat; +import com.moulberry.flashback.WindowSizeTracker; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; @@ -27,24 +29,42 @@ import java.util.Objects; public abstract class MixinRenderTarget { @Shadow - public int frameBufferId; - - @Shadow - public abstract int getColorTextureId(); + public int colorTextureId; @Inject(method = "blitToScreen(IIZ)V", at = @At("HEAD"), cancellable = true) public void blitToScreenSodium(int width, int height, boolean noBlend, CallbackInfo ci) { if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive()) { var window = Minecraft.getInstance().getWindow(); - int frameBottom = (ReplayUI.viewportSizeY - (ReplayUI.frameY + ReplayUI.frameHeight)) * window.framebufferHeight / ReplayUI.viewportSizeY; - int frameLeft = ReplayUI.frameX * window.framebufferWidth / ReplayUI.viewportSizeX; - int frameWidth = Math.max(1, ReplayUI.frameWidth) * window.framebufferWidth / ReplayUI.viewportSizeX; - int frameHeight = Math.max(1, ReplayUI.frameHeight) * window.framebufferHeight / ReplayUI.viewportSizeY; + float frameLeft = (float) ReplayUI.frameX / ReplayUI.viewportSizeX; + float frameTop = (float) ReplayUI.frameY / ReplayUI.viewportSizeY; + float frameWidth = (float) Math.max(1, ReplayUI.frameWidth) / ReplayUI.viewportSizeX; + float frameHeight = (float) Math.max(1, ReplayUI.frameHeight) / ReplayUI.viewportSizeY; - GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, this.frameBufferId); - GL30.glBlitFramebuffer(0, 0, width, height, frameLeft, frameBottom, frameLeft+frameWidth, frameBottom+frameHeight, - GL11.GL_COLOR_BUFFER_BIT, GL11.GL_LINEAR); - GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, 0); + int realWidth = WindowSizeTracker.getWidth(window); + int realHeight = WindowSizeTracker.getHeight(window); + + RenderSystem.assertOnRenderThread(); + GlStateManager._colorMask(true, true, true, false); + GlStateManager._disableDepthTest(); + GlStateManager._depthMask(false); + GlStateManager._viewport((int)(realWidth * frameLeft), (int)(realHeight * (1 - (frameTop+frameHeight))), + Math.max(1, (int)(realWidth * frameWidth)), Math.max(1, (int)(realHeight * frameHeight))); + if (noBlend) { + GlStateManager._disableBlend(); + } + Minecraft minecraft = Minecraft.getInstance(); + ShaderInstance shaderInstance = Objects.requireNonNull(minecraft.gameRenderer.blitShader, "Blit shader not loaded"); + shaderInstance.setSampler("DiffuseSampler", this.colorTextureId); + shaderInstance.apply(); + BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN); + bufferBuilder.addVertex(0.0f, 0.0f, 0.0f); + bufferBuilder.addVertex(1.0f, 0.0f, 0.0f); + bufferBuilder.addVertex(1.0f, 1.0f, 0.0f); + bufferBuilder.addVertex(0.0f, 1.0f, 0.0f); + BufferUploader.draw(bufferBuilder.buildOrThrow()); + shaderInstance.clear(); + GlStateManager._depthMask(true); + GlStateManager._colorMask(true, true, true, true); ci.cancel(); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java b/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java index 026666f..bbbcb94 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java @@ -21,9 +21,8 @@ import java.util.SortedSet; @Mixin(targets = {"net.caffeinemc.mods.sodium.client.render.SodiumWorldRenderer", "me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer"}) public class MixinSodiumWorldRenderer { - @Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;Lnet/minecraft/client/Camera;F)V", - at = @At("HEAD"), cancellable = true) - public void renderBlockEntities(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, Camera camera, float tickDelta, CallbackInfo ci) { + @Inject(method = "renderBlockEntities", at = @At("HEAD"), cancellable = true, require = 0, remap = false) + public void renderBlockEntities(CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.renderBlocks) { ci.cancel(); diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/MixinAxiomEditorUI.java b/src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomEditorUI.java similarity index 94% rename from src/main/java/com/moulberry/flashback/mixin/compat/MixinAxiomEditorUI.java rename to src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomEditorUI.java index a3b80c2..d231d99 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/MixinAxiomEditorUI.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomEditorUI.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.compat; +package com.moulberry.flashback.mixin.compat.axiom; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.editor.ui.ReplayUI; diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomServerIntegration.java b/src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomServerIntegration.java new file mode 100644 index 0000000..fa77bbd --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/axiom/MixinAxiomServerIntegration.java @@ -0,0 +1,23 @@ +package com.moulberry.flashback.mixin.compat.axiom; + +import com.moulberry.flashback.Flashback; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +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("axiom") +@Pseudo +@Mixin(targets = "com.moulberry.axiom.integration.ServerIntegration", remap = false) +public class MixinAxiomServerIntegration { + + @Inject(method = "changeGameMode", at = @At("HEAD"), cancellable = true, require = 0) + private static void changeGameMode(CallbackInfo ci) { + if (Flashback.isInReplay()) { + ci.cancel(); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java b/src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java deleted file mode 100644 index 975f309..0000000 --- a/src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.moulberry.flashback.mixin.compat.distanthorizons; - -import com.moulberry.mixinconstraints.annotations.IfModLoaded; -import com.seibel.distanthorizons.core.api.internal.SharedApi; -import org.spongepowered.asm.mixin.Mixin; - -@IfModLoaded("distanthorizons") -@Mixin(value = SharedApi.class, remap = false) -public abstract class MixinSharedApi { - - /* - * Override any changes to the DhWorld, changing it to our proxy world - */ - -// @Inject(method = "setDhWorld", at = @At("HEAD"), cancellable = true) -// private static void setDhWorld(AbstractDhWorld newWorld, CallbackInfo ci) { -// if (Flashback.isInReplay() && newWorld != null && !(newWorld instanceof ProxyDhWorld)) { -// SharedApi.setDhWorld(new ProxyDhWorld()); -// ci.cancel(); -// } -// } - -} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/MixinFabricMinecraftServer.java b/src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricMinecraftServer.java similarity index 92% rename from src/main/java/com/moulberry/flashback/mixin/compat/MixinFabricMinecraftServer.java rename to src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricMinecraftServer.java index 4967c58..d5749e3 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/MixinFabricMinecraftServer.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricMinecraftServer.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.compat; +package com.moulberry.flashback.mixin.compat.fabric; import com.bawnorton.mixinsquared.TargetHandler; import com.moulberry.flashback.playback.ReplayServer; @@ -21,7 +21,7 @@ public class MixinFabricMinecraftServer { mixin = "net.fabricmc.fabric.mixin.biome.modification.MinecraftServerMixin", name = "finalizeWorldGen" ) - @Inject(method = "@MixinSquared:Handler", at = @At("HEAD"), cancellable = true) + @Inject(method = "@MixinSquared:Handler", at = @At("HEAD"), cancellable = true, require = 0) private void preventWorldGenChanges(CallbackInfo ci) { if ((Object) this instanceof ReplayServer) { ci.cancel(); diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricServerPlayNetworking.java b/src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricServerPlayNetworking.java new file mode 100644 index 0000000..2f2238f --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/fabric/MixinFabricServerPlayNetworking.java @@ -0,0 +1,39 @@ +package com.moulberry.flashback.mixin.compat.fabric; + +import com.moulberry.flashback.playback.FakePlayer; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(value = ServerPlayNetworking.class, remap = false) +public class MixinFabricServerPlayNetworking { + + @Inject(method = "canSend(Lnet/minecraft/server/network/ServerGamePacketListenerImpl;Lnet/minecraft/network/protocol/common/custom/CustomPacketPayload$Type;)Z", at = @At("HEAD"), cancellable = true, require = 0) + private static void canSend1(ServerGamePacketListenerImpl handler, CustomPacketPayload.Type type, CallbackInfoReturnable cir) { + if (handler.player instanceof FakePlayer) { + cir.setReturnValue(true); + } + } + + @Inject(method = "canSend(Lnet/minecraft/server/network/ServerGamePacketListenerImpl;Lnet/minecraft/resources/ResourceLocation;)Z", at = @At("HEAD"), cancellable = true, require = 0) + private static void canSend2(ServerGamePacketListenerImpl handler, ResourceLocation channelName, CallbackInfoReturnable cir) { + if (handler.player instanceof FakePlayer) { + cir.setReturnValue(true); + } + } + + @Inject(method = "send", at = @At("HEAD"), cancellable = true, require = 0) + private static void send(ServerPlayer player, CustomPacketPayload payload, CallbackInfo ci) { + if (player instanceof FakePlayer) { + ci.cancel(); + } + } + +} 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 245736e..01bea88 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 @@ -14,7 +14,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(value = SystemTimeUniforms.Timer.class, remap = false) public class MixinIrisSystemTimeUniforms { - @Inject(method = "getFrameTimeCounter", at = @At("HEAD"), cancellable = true) + @Inject(method = "getFrameTimeCounter", at = @At("HEAD"), require = 0, cancellable = true) public void getFrameTimeCounter(CallbackInfoReturnable cir) { if (Flashback.isExporting()) { double currentTick = Flashback.EXPORT_JOB.getCurrentTickDouble(); @@ -22,7 +22,7 @@ public class MixinIrisSystemTimeUniforms { } } - @Inject(method = "getLastFrameTime", at = @At("HEAD"), cancellable = true) + @Inject(method = "getLastFrameTime", at = @At("HEAD"), require = 0, cancellable = true) public void getLastFrameTime(CallbackInfoReturnable cir) { if (Flashback.isExporting()) { cir.setReturnValue((float)(1 / Flashback.EXPORT_JOB.getSettings().framerate())); 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 index 3e3c81e..04a3ecc 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/replaymod/MixinReplayModRecording.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/replaymod/MixinReplayModRecording.java @@ -15,7 +15,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = ReplayModRecording.class, remap = false) public class MixinReplayModRecording { - @Inject(method = "initiateRecording", at = @At("HEAD"), cancellable = true) + @Inject(method = "initiateRecording", at = @At("HEAD"), require = 0, cancellable = true) public void initiateRecording(Connection networkManager, CallbackInfo ci) { if (Flashback.isInReplay()) { ci.cancel(); diff --git a/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java b/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java index e08f185..835a175 100644 --- a/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/movement/MixinPlayerEntity.java @@ -5,7 +5,10 @@ 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.multiplayer.PlayerInfo; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.player.RemotePlayer; +import net.minecraft.network.chat.Component; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.phys.Vec3; @@ -54,4 +57,17 @@ public abstract class MixinPlayerEntity extends LivingEntity { } } + @Inject(method = "getName", at = @At("HEAD"), cancellable = true) + public void getName(CallbackInfoReturnable cir) { + if ((Object)this instanceof RemotePlayer) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + String nameOverride = editorState.nameOverride.get(this.uuid); + if (nameOverride != null) { + cir.setReturnValue(Component.literal(nameOverride)); + } + } + } + } + } diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java index 0745d2c..2a6e186 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java @@ -7,14 +7,17 @@ import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import net.minecraft.client.Camera; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; import org.joml.Vector2f; import org.joml.Vector3d; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Camera.class) -public class MixinCamera { +public abstract class MixinCamera { @Shadow private float eyeHeightOld; @@ -22,28 +25,22 @@ public class MixinCamera { @Shadow public float eyeHeight; - @WrapOperation(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setRotation(FF)V", ordinal = 0)) - public void setRotation(Camera instance, float yaw, float pitch, Operation original, - @Local(argsOnly = true) Entity entity, @Local(argsOnly = true) float partialTick) { + @Shadow + protected abstract void setRotation(float f, float g); + + @Shadow + protected abstract void setPosition(double d, double e, double f); + + @Inject(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setPosition(DDD)V", ordinal = 0, shift = At.Shift.AFTER)) + public void afterSetPosition(BlockGetter blockGetter, Entity entity, boolean bl, boolean bl2, float partialTick, CallbackInfo ci) { Vector2f rotation = AccurateEntityPositionHandler.getAccurateRotation(entity, partialTick); if (rotation != null) { - pitch = rotation.x; - yaw = rotation.y; + this.setRotation(rotation.y, rotation.x); } - original.call(instance, yaw, pitch); - } - - - @WrapOperation(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setPosition(DDD)V", ordinal = 0)) - public void setPosition(Camera instance, double x, double y, double z, Operation original, - @Local(argsOnly = true) Entity entity, @Local(argsOnly = true) float partialTick) { Vector3d position = AccurateEntityPositionHandler.getAccuratePosition(entity, partialTick); if (position != null) { - x = position.x; - y = position.y + Mth.lerp(partialTick, this.eyeHeightOld, this.eyeHeight); - z = position.z; + this.setPosition(position.x, position.y + Mth.lerp(partialTick, this.eyeHeightOld, this.eyeHeight), position.z); } - original.call(instance, x, y, z); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java index 238405b..5a20ee0 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java @@ -12,6 +12,7 @@ import com.moulberry.flashback.ext.ItemInHandRendererExt; import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.CameraRotation; +import com.moulberry.flashback.visuals.ReplayVisuals; import com.moulberry.flashback.visuals.ShaderManager; import net.minecraft.client.Camera; import net.minecraft.client.DeltaTracker; @@ -26,6 +27,7 @@ import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.PostChain; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.GameType; import org.jetbrains.annotations.Nullable; @@ -105,6 +107,14 @@ public abstract class MixinGameRenderer { original.call(instance, blockGetter, entity, bl, bl2, f); } + @Inject(method = "getNightVisionScale", at = @At("HEAD"), cancellable = true) + private static void getNightVisionScale(LivingEntity livingEntity, float f, CallbackInfoReturnable cir) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideNightVision) { + cir.setReturnValue(1.0f); + } + } + @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;rotation()Lorg/joml/Quaternionf;")) public Quaternionf renderLevel(Camera instance, Operation original) { return CameraRotation.modifyViewQuaternion(original.call(instance)); 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 8bbca51..e04ce27 100644 --- a/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java @@ -4,6 +4,7 @@ import com.moulberry.flashback.Flashback; import com.moulberry.flashback.record.Recorder; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.prediction.BlockStatePredictionHandler; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.network.ConnectionProtocol; @@ -31,11 +32,17 @@ public class MixinClientLevel { @Final private Minecraft minecraft; + @Shadow + @Final + private BlockStatePredictionHandler blockStatePredictionHandler; + @Inject(method = "setBlock", at = @At("HEAD")) public void setBlock(BlockPos blockPos, BlockState blockState, int i, int j, CallbackInfoReturnable cir) { - Recorder recorder = Flashback.RECORDER; - if (recorder != null && !recorder.isPaused()) { - recorder.writePacketAsync(new ClientboundBlockUpdatePacket(blockPos.immutable(), blockState), ConnectionProtocol.PLAY); + if (this.blockStatePredictionHandler.isPredicting()) { + Recorder recorder = Flashback.RECORDER; + if (recorder != null && !recorder.isPaused()) { + recorder.writePacketAsync(new ClientboundBlockUpdatePacket(blockPos.immutable(), blockState), ConnectionProtocol.PLAY); + } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java index 3902e9d..f55657a 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java @@ -12,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(BossHealthOverlay.class) public class MixinBossHealthOverlay { - @Inject(method = "render", at = @At("HEAD"), cancellable = true) + @Inject(method = "render", at = @At("HEAD"), cancellable = true, require = 0) public void render(GuiGraphics guiGraphics, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.showBossBar) { diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java index b9f5f76..4831fec 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java @@ -17,7 +17,7 @@ public class MixinClientLevel { * This code here ensures that the interpolation of yRotO -> yRot will always be the shortest path */ - @Inject(method = "tickNonPassenger", at = @At("RETURN")) + @Inject(method = "tickNonPassenger", at = @At("RETURN"), require = 0) public void tickNonPassengerEnd(Entity entity, CallbackInfo ci) { if (Flashback.isInReplay()) { entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot(); @@ -25,7 +25,7 @@ public class MixinClientLevel { } } - @Inject(method = "tickPassenger", at = @At("RETURN")) + @Inject(method = "tickPassenger", at = @At("RETURN"), require = 0) public void tickPassengerEnd(Entity vehicle, Entity entity, CallbackInfo ci) { if (Flashback.isInReplay()) { entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot(); diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java index b14461e..5e2a251 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java @@ -12,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(ClientLevel.ClientLevelData.class) public class MixinClientLevelData { - @Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true) + @Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true, require = 0) public void getDayTime(CallbackInfoReturnable cir) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && editorState.replayVisuals.overrideTimeOfDay >= 0) { diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java index 6ba1a22..25e21c5 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java @@ -36,7 +36,7 @@ public abstract class MixinEntityRenderDispatcher { } // Add a yellow outline to selected entity - @Inject(method = "render", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", shift = At.Shift.BEFORE)) + @Inject(method = "render", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", shift = At.Shift.BEFORE), require = 0) public void renderAfter(Entity entity, double d, double e, double f, float g, float h, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, CallbackInfo ci) { if (Flashback.isInReplay()) { if (ReplayUI.isEntitySelected(entity.getUUID())) { @@ -51,7 +51,7 @@ public abstract class MixinEntityRenderDispatcher { } // Prevent rendering shadows when blocks are turned off - @WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;renderShadow(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/entity/Entity;FFLnet/minecraft/world/level/LevelReader;F)V")) + @WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;renderShadow(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/entity/Entity;FFLnet/minecraft/world/level/LevelReader;F)V"), require = 0) public boolean renderShadow(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, float f, float g, LevelReader levelReader, float h) { EditorState editorState = EditorStateManager.getCurrent(); return editorState == null || editorState.replayVisuals.renderBlocks; diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderer.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderer.java index f32669a..14d2b48 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderer.java @@ -15,11 +15,17 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(EntityRenderer.class) public class MixinEntityRenderer { - @Inject(method = "renderNameTag", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderNameTag", at = @At("HEAD"), cancellable = true, require = 0) public void renderNameTag(Entity entity, Component component, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, float f, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); - if (editorState != null && !editorState.replayVisuals.renderNametags) { - ci.cancel(); + if (editorState != null) { + if (!editorState.replayVisuals.renderNametags) { + ci.cancel(); + } else if (editorState.hideNametags.contains(entity.getUUID())) { + ci.cancel(); + } else if (editorState.hideDuringExport.contains(entity.getUUID())) { + ci.cancel(); + } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java index 48365b9..58d4e81 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java @@ -14,7 +14,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(FogRenderer.class) public class MixinFogRenderer { - @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) + @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true, require = 0) private static void setupFog(Camera camera, FogRenderer.FogMode fogMode, float f, boolean bl, float g, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && editorState.replayVisuals.overrideFog) { diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java index 1e495f0..8885daf 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java @@ -54,7 +54,7 @@ public abstract class MixinGui { } } - @Inject(method = "renderChat", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderChat", at = @At("HEAD"), cancellable = true, require = 0) public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.showChat) { @@ -62,7 +62,7 @@ public abstract class MixinGui { } } - @Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true, require = 0) public void renderTitle(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.showTitleText) { @@ -70,7 +70,7 @@ public abstract class MixinGui { } } - @Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true, require = 0) public void renderScoreboardSidebar(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.showScoreboard) { @@ -78,7 +78,7 @@ public abstract class MixinGui { } } - @Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true, require = 0) public void renderOverlayMessage(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.showActionBar) { @@ -86,7 +86,7 @@ public abstract class MixinGui { } } - @Inject(method = "renderHotbarAndDecorations", at = @At("HEAD"), cancellable = true) + @Inject(method = "renderHotbarAndDecorations", at = @At("HEAD"), cancellable = true, require = 0) public void renderHotbarAndDecorations(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && !editorState.replayVisuals.showHotbar) { @@ -94,7 +94,7 @@ public abstract class MixinGui { } } - @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;")) + @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;"), require = 0) public GameType renderHotbarAndDecorations_getPlayerMode(MultiPlayerGameMode instance, Operation original) { if (Flashback.isInReplay()) { return this.cameraGameType; @@ -102,7 +102,7 @@ public abstract class MixinGui { return original.call(instance); } - @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;canHurtPlayer()Z")) + @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;canHurtPlayer()Z"), require = 0) public boolean renderHotbarAndDecorations_canHurtPlayer(MultiPlayerGameMode instance, Operation original) { if (Flashback.isInReplay()) { return this.cameraGameType.isSurvival(); @@ -110,14 +110,14 @@ public abstract class MixinGui { return original.call(instance); } - @Inject(method = "isExperienceBarVisible", at = @At("HEAD"), cancellable = true) + @Inject(method = "isExperienceBarVisible", at = @At("HEAD"), cancellable = true, require = 0) public void isExperienceBarVisible(CallbackInfoReturnable cir) { if (Flashback.isInReplay()) { cir.setReturnValue(this.cameraGameType.isSurvival()); } } - @WrapOperation(method = "renderExperienceBar", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getXpNeededForNextLevel()I")) + @WrapOperation(method = "renderExperienceBar", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getXpNeededForNextLevel()I"), require = 0) public int renderExperienceBar_getXpNeededForNextLevel(LocalPlayer instance, Operation original) { if (Flashback.isInReplay()) { Player player = this.getCameraPlayer(); @@ -128,7 +128,7 @@ public abstract class MixinGui { return original.call(instance); } - @WrapOperation(method = "renderExperienceBar", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceProgress:F")) + @WrapOperation(method = "renderExperienceBar", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceProgress:F"), require = 0) public float renderExperienceBar_experienceProgress(LocalPlayer instance, Operation original) { if (Flashback.isInReplay()) { Player player = this.getCameraPlayer(); @@ -139,7 +139,7 @@ public abstract class MixinGui { return original.call(instance); } - @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getAttackStrengthScale(F)F")) + @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getAttackStrengthScale(F)F"), require = 0) public float renderCrosshair_getAttackStrengthScale(LocalPlayer instance, float partialTick, Operation original) { if (Flashback.isInReplay()) { Player player = this.getCameraPlayer(); @@ -150,7 +150,7 @@ public abstract class MixinGui { return original.call(instance, partialTick); } - @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getCurrentItemAttackStrengthDelay()F")) + @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getCurrentItemAttackStrengthDelay()F"), require = 0) public float renderCrosshair_getCurrentItemAttackStrengthDelay(LocalPlayer instance, Operation original) { if (Flashback.isInReplay()) { Player player = this.getCameraPlayer(); @@ -161,7 +161,7 @@ public abstract class MixinGui { return original.call(instance); } - @WrapOperation(method = "renderExperienceLevel", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceLevel:I")) + @WrapOperation(method = "renderExperienceLevel", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceLevel:I"), require = 0) public int renderExperienceLevel_experienceLevel(LocalPlayer instance, Operation original) { if (Flashback.isInReplay()) { Player player = this.getCameraPlayer(); @@ -181,7 +181,7 @@ public abstract class MixinGui { } } - @Inject(method = "canRenderCrosshairForSpectator", at = @At("HEAD"), cancellable = true) + @Inject(method = "canRenderCrosshairForSpectator", at = @At("HEAD"), cancellable = true, require = 0) public void canRenderCrosshairForSpectator(HitResult hitResult, CallbackInfoReturnable cir) { if (Flashback.isInReplay()) { if (!Flashback.isExporting() && ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) { diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLightTexture.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLightTexture.java new file mode 100644 index 0000000..1377720 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLightTexture.java @@ -0,0 +1,28 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.core.Holder; +import net.minecraft.world.effect.MobEffects; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(LightTexture.class) +public class MixinLightTexture { + + @WrapOperation(method = "updateLightTexture", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;hasEffect(Lnet/minecraft/core/Holder;)Z"), require = 0) + public boolean updateLightTexture_hasEffect(LocalPlayer instance, Holder holder, Operation original) { + if (holder == MobEffects.NIGHT_VISION) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideNightVision) { + return true; + } + } + return original.call(instance, holder); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLivingEntityRenderer.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLivingEntityRenderer.java index 02e65ea..9d7f640 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLivingEntityRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLivingEntityRenderer.java @@ -12,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(LivingEntityRenderer.class) public class MixinLivingEntityRenderer { - @Inject(method = "isBodyVisible", at = @At("HEAD"), cancellable = true) + @Inject(method = "isBodyVisible", at = @At("HEAD"), cancellable = true, require = 0) public void isBodyVisible(LivingEntity livingEntity, CallbackInfoReturnable cir) { EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && editorState.hideDuringExport.contains(livingEntity.getUUID())) { diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java index a3f964b..e671bb5 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java @@ -19,7 +19,7 @@ public class MixinLoadingOverlay { @Shadow @Final private Minecraft minecraft; // Make overlay disappear instantly if inside replay - @Inject(method = "render", at = @At("RETURN")) + @Inject(method = "render", at = @At("RETURN"), require = 0) public void render(GuiGraphics guiGraphics, int i, int j, float f, CallbackInfo ci) { if (this.fadeOutStart != -1 && Flashback.isInReplay()) { this.minecraft.setOverlay(null); diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinRenderStateShard.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinRenderStateShard.java index 2563fb7..69481f0 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinRenderStateShard.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinRenderStateShard.java @@ -10,7 +10,7 @@ import org.spongepowered.asm.mixin.injection.At; @Mixin(RenderStateShard.class) public class MixinRenderStateShard { - @WrapOperation(method = "setupGlintTexturing", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J")) + @WrapOperation(method = "setupGlintTexturing", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J"), require = 0) private static long setupGlintTexturing(Operation original) { if (Flashback.isExporting()) { double currentTick = Flashback.EXPORT_JOB.getCurrentTickDouble(); diff --git a/src/main/java/com/moulberry/flashback/playback/FakePlayer.java b/src/main/java/com/moulberry/flashback/playback/FakePlayer.java index a5ee615..6a55cef 100644 --- a/src/main/java/com/moulberry/flashback/playback/FakePlayer.java +++ b/src/main/java/com/moulberry/flashback/playback/FakePlayer.java @@ -40,4 +40,7 @@ public class FakePlayer extends ServerPlayer { public void awardStat(Stat stat, int i) { } + @Override + public void resetStat(Stat stat) { + } } diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java index 3526209..14e1e4d 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java @@ -3,6 +3,7 @@ package com.moulberry.flashback.playback; import com.google.common.collect.ImmutableMap; import com.moulberry.flashback.exception.UnsupportedPacketException; import com.moulberry.flashback.registry.RegistryHelper; +import net.fabricmc.fabric.api.event.registry.DynamicRegistries; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; @@ -77,14 +78,6 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack boolean sendTags = false; - if (this.pendingTags != null && !this.pendingTags.isEmpty()) { - this.pendingTags.forEach((resourceKey, networkPayload) -> { - networkPayload.applyToRegistry(this.replayServer.registryAccess().registryOrThrow(resourceKey)); - }); - sendTags = true; - this.pendingTags = null; - } - List configurationTasks = new ArrayList<>(); FeatureFlagSet currentFeatureFlags = this.replayServer.worldData.enabledFeatures(); List currentKnownPacks = this.replayServer.getResourceManager().listPacks().flatMap(packResources -> packResources.location().knownPackInfo().stream()).toList(); @@ -130,7 +123,7 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack if (!RegistryHelper.equals(this.replayServer.registryAccess(), synchronizedRegistries, RegistryDataLoader.SYNCHRONIZED_REGISTRIES)) { Set> neededRegistries = new HashSet<>(); - for (RegistryDataLoader.RegistryData worldgenRegistry : RegistryDataLoader.WORLDGEN_REGISTRIES) { + for (RegistryDataLoader.RegistryData worldgenRegistry : DynamicRegistries.getDynamicRegistries()) { neededRegistries.add(worldgenRegistry.key()); } @@ -162,12 +155,17 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack } } - if (synchronizeRegistries) { - configurationTasks.add(new SynchronizeRegistriesTask(currentKnownPacks, this.replayServer.registries)); - sendTags = false; + if (this.pendingTags != null && !this.pendingTags.isEmpty()) { + this.pendingTags.forEach((resourceKey, networkPayload) -> { + networkPayload.applyToRegistry(this.replayServer.registryAccess().registryOrThrow(resourceKey)); + }); + sendTags = true; + this.pendingTags = null; } - if (sendTags) { + if (synchronizeRegistries) { + configurationTasks.add(new SynchronizeRegistriesTask(currentKnownPacks, this.replayServer.registries)); + } else if (sendTags) { this.replayServer.getPlayerList().broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.replayServer.registries))); } @@ -201,6 +199,7 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack false, 0, List.of(), false, null); serverLevel.noSave = true; this.replayServer.levels.put(Level.OVERWORLD, serverLevel); + this.replayServer.getPlayerList().addWorldborderListener(serverLevel); } private static Collection knownPacksToIds(PackRepository packRepository, Collection knownPacks) { diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index ecf7564..4f20931 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -24,6 +24,7 @@ import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; import net.minecraft.network.DisconnectionDetails; +import net.minecraft.network.PacketSendListener; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.codec.ByteBufCodecs; @@ -149,11 +150,14 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } ((ServerLevelExt) level).flashback$setCanSpawnEntities(true); - level.addFreshEntity(pendingEntity); + try { + level.addFreshEntity(pendingEntity); + ChunkPos chunkPos = new ChunkPos(pendingEntity.blockPosition()); + level.getChunkSource().addRegionTicket(ReplayServer.ENTITY_LOAD_TICKET, chunkPos, 3, chunkPos); + } catch (Exception e) { + Flashback.LOGGER.error("Unable to spawn entity", e); + } ((ServerLevelExt) level).flashback$setCanSpawnEntities(false); - - ChunkPos chunkPos = new ChunkPos(pendingEntity.blockPosition()); - level.getChunkSource().addRegionTicket(ReplayServer.ENTITY_LOAD_TICKET, chunkPos, 3, chunkPos); } this.pendingEntities.clear(); } @@ -198,7 +202,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { gameProfile.getProperties().removeAll("IsReplayViewer"); CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false); - ServerPlayer serverPlayer = new FakePlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()){ + ServerPlayer serverPlayer = new FakePlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()) { @Override public boolean isSpectator() { return false; @@ -230,12 +234,25 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } } - Connection connection = new Connection(PacketFlow.SERVERBOUND); + Connection connection = new Connection(PacketFlow.SERVERBOUND) { + @Override + public void send(Packet packet, @Nullable PacketSendListener packetSendListener, boolean bl) {} + }; EmbeddedChannel embeddedChannel = new EmbeddedChannel(connection); serverPlayer.recreateFromPacket(addEntityPacket); - this.replayServer.getPlayerList().placeNewPlayer(connection, serverPlayer, commonListenerCookie); + try { + this.replayServer.getPlayerList().placeNewPlayer(connection, serverPlayer, commonListenerCookie); + } catch (Exception e) { + Flashback.LOGGER.error("Failed to spawn player", e); + return null; + } serverPlayer.setGameMode(gameType); + if (serverPlayer.isRemoved()) { + Flashback.LOGGER.error("ServerPlayer {} was removed while spawning. Incompatible mod?", serverPlayer.getUUID()); + return null; + } + return serverPlayer; } @@ -705,6 +722,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { false, commonPlayerSpawnInfo.seed(), List.of(), false, null); serverLevel.noSave = true; this.replayServer.levels.put(dimension, serverLevel); + this.replayServer.getPlayerList().addWorldborderListener(serverLevel); if (oldLevel != null) { this.replayServer.closeLevel(oldLevel); @@ -894,6 +912,9 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { 0, Vec3.ZERO, oldServerPlayer.getYHeadRot()); ServerPlayer newServerPlayer = this.spawnPlayer(addEntityPacket, oldServerPlayer.getGameProfile(), oldServerPlayer.gameMode.getGameModeForPlayer()); + if (newServerPlayer == null) { + return; + } if (clientboundRespawnPacket.shouldKeep((byte)2)) { newServerPlayer.setShiftKeyDown(oldServerPlayer.isShiftKeyDown()); diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java index c5a7b7b..c35aaa4 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java @@ -34,6 +34,7 @@ import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; @@ -349,6 +350,9 @@ public class ReplayServer extends IntegratedServer { // Send tab list customization serverPlayer.connection.send(new ClientboundTabListPacket(tabListHeader, tabListFooter)); + + // Send world border + serverPlayer.connection.send(new ClientboundInitializeBorderPacket(serverLevel.getWorldBorder())); } @Override @@ -372,7 +376,8 @@ public class ReplayServer extends IntegratedServer { } }); - this.loadLevel(); + super.initServer(); + this.overworld().noSave = true; return true; @@ -764,12 +769,17 @@ public class ReplayServer extends IntegratedServer { } } + // Pause replay if game is paused (by opening the ESC pause menu for example) + if (!this.replayPaused && this.isPaused()) { + this.replayPaused = true; + } + // Update current tick boolean normalPlayback = false; if (this.jumpToTick >= 0) { this.targetTick = this.jumpToTick; this.jumpToTick = -1; - } else if (!this.isPaused() && !this.replayPaused && this.targetTick < this.totalTicks) { + } else if (!this.replayPaused && this.targetTick < this.totalTicks) { // Normal playback this.targetTick += 1; normalPlayback = true; @@ -825,6 +835,7 @@ public class ReplayServer extends IntegratedServer { if (camera == null || camera == replayViewer || camera.isRemoved()) { Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid); if (targetEntity != null && !targetEntity.isRemoved()) { + replayViewer.setCamera(null); replayViewer.setCamera(targetEntity); } } @@ -1076,13 +1087,7 @@ public class ReplayServer extends IntegratedServer { if (shouldJump) { this.processedSnapshot = true; - // Clear bossbars and particles - for (ReplayPlayer replayViewer : this.replayViewers) { - for (UUID uuid : this.bossEvents.keySet()) { - replayViewer.connection.send(ClientboundBossEventPacket.createRemovePacket(uuid)); - } - } - this.bossEvents.clear(); + this.clearDataForPlayingSnapshot(); Map.Entry entry = this.playableChunksByStart.floorEntry(this.targetTick); ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); @@ -1099,6 +1104,12 @@ public class ReplayServer extends IntegratedServer { this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); if (this.currentTick == entry.getKey()) { this.currentReplayReader.resetToStart(); + + if (!this.processedSnapshot && entry.getValue().chunkMeta.forcePlaySnapshot) { + this.processedSnapshot = true; + this.clearDataForPlayingSnapshot(); + this.currentReplayReader.handleSnapshot(this); + } } while (this.currentTick < this.targetTick) { @@ -1121,6 +1132,12 @@ public class ReplayServer extends IntegratedServer { this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); this.currentReplayReader.resetToStart(); + + if (entry.getValue().chunkMeta.forcePlaySnapshot) { + this.processedSnapshot = true; + this.clearDataForPlayingSnapshot(); + this.currentReplayReader.handleSnapshot(this); + } } if (entry.getKey() + entry.getValue().chunkMeta.duration < this.currentTick) { @@ -1135,6 +1152,15 @@ public class ReplayServer extends IntegratedServer { this.currentReplayReader = null; } + private void clearDataForPlayingSnapshot() { + for (ReplayPlayer replayViewer : this.replayViewers) { + for (UUID uuid : this.bossEvents.keySet()) { + replayViewer.connection.send(ClientboundBossEventPacket.createRemovePacket(uuid)); + } + } + this.bossEvents.clear(); + } + private void tryFollowLocalPlayer() { if (this.spawnLevel == null) { return; @@ -1219,10 +1245,10 @@ public class ReplayServer extends IntegratedServer { Files.walkFileTree(temp, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if (!Files.isDirectory(file)) { - Files.deleteIfExists(file); - } - return FileVisitResult.CONTINUE; + if (!Files.isDirectory(file)) { + Files.deleteIfExists(file); + } + return FileVisitResult.CONTINUE; } }); } catch (IOException e) { diff --git a/src/main/java/com/moulberry/flashback/record/FlashbackChunkMeta.java b/src/main/java/com/moulberry/flashback/record/FlashbackChunkMeta.java index f829559..020a177 100644 --- a/src/main/java/com/moulberry/flashback/record/FlashbackChunkMeta.java +++ b/src/main/java/com/moulberry/flashback/record/FlashbackChunkMeta.java @@ -5,10 +5,12 @@ import org.jetbrains.annotations.Nullable; public class FlashbackChunkMeta { public int duration = 0; + public boolean forcePlaySnapshot = false; public JsonObject toJson() { JsonObject chunkMeta = new JsonObject(); chunkMeta.addProperty("duration", this.duration); + chunkMeta.addProperty("forcePlaySnapshot", this.forcePlaySnapshot); return chunkMeta; } @@ -20,6 +22,9 @@ public class FlashbackChunkMeta { return null; } flashbackChunkMeta.duration = chunkMeta.get("duration").getAsInt(); + if (chunkMeta.has("forcePlaySnapshot")) { + flashbackChunkMeta.forcePlaySnapshot = chunkMeta.get("forcePlaySnapshot").getAsBoolean(); + } return flashbackChunkMeta; } diff --git a/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java index c0a9817..ab40f3f 100644 --- a/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java +++ b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java @@ -6,7 +6,9 @@ import com.google.gson.JsonObject; import com.moulberry.flashback.FlashbackGson; import org.jetbrains.annotations.Nullable; +import java.io.File; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -27,6 +29,8 @@ public class FlashbackMeta { public int totalTicks = -1; public LinkedHashMap chunks = new LinkedHashMap<>(); + public Map distantHorizonPaths = new HashMap<>(); + public JsonObject toJson() { JsonObject meta = new JsonObject(); meta.addProperty("uuid", this.replayIdentifier.toString()); @@ -57,6 +61,15 @@ public class FlashbackMeta { meta.add("markers", jsonMarkers); } + // Distant horizons + if (!this.distantHorizonPaths.isEmpty()) { + JsonObject distantHorizonPaths = new JsonObject(); + for (Map.Entry entry : this.distantHorizonPaths.entrySet()) { + distantHorizonPaths.addProperty(entry.getKey(), entry.getValue().getPath()); + } + meta.add("distantHorizonPaths", distantHorizonPaths); + } + JsonObject chunksJson = new JsonObject(); for (Map.Entry entry : this.chunks.entrySet()) { chunksJson.add(entry.getKey(), entry.getValue().toJson()); @@ -110,6 +123,14 @@ public class FlashbackMeta { } } + // Distant horizons + if (meta.has("distantHorizonPaths")) { + JsonObject distantHorizonPaths = meta.getAsJsonObject("distantHorizonPaths"); + for (Map.Entry entry : distantHorizonPaths.entrySet()) { + flashbackMeta.distantHorizonPaths.put(entry.getKey(), new File(entry.getValue().getAsString())); + } + } + // Chunks if (!meta.has("chunks")) { return null; diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java index 250ea40..155baa4 100644 --- a/src/main/java/com/moulberry/flashback/record/Recorder.java +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -2,11 +2,13 @@ package com.moulberry.flashback.record; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.mojang.authlib.GameProfile; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.datafixers.util.Pair; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.PacketHelper; import com.moulberry.flashback.action.*; +import com.moulberry.flashback.compat.DistantHorizonsSupport; import com.moulberry.flashback.io.AsyncReplaySaver; import com.moulberry.flashback.io.ReplayWriter; import com.moulberry.flashback.mixin.compat.bobby.FakeChunkManagerAccessor; @@ -29,12 +31,12 @@ import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.resources.server.ServerPackManager; import net.minecraft.core.*; -import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; import net.minecraft.network.ConnectionProtocol; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; @@ -58,7 +60,6 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.Leashable; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.food.FoodData; @@ -76,6 +77,7 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.*; import org.jetbrains.annotations.Nullable; +import java.io.File; import java.nio.file.Path; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; @@ -150,12 +152,20 @@ public class Recorder { this.metadata.bobbyWorldName = bobbyWorldName; } catch (Throwable t) {} } + + if (Flashback.supportsDistantHorizons) { + this.metadata.distantHorizonPaths.putAll(DistantHorizonsSupport.getDimensionPaths()); + } } public boolean readyToWrite() { return !this.closeForWriting && !this.needsInitialSnapshot && !this.wasPaused; } + public void putDistantHorizonsPaths(Map paths) { + this.metadata.distantHorizonPaths.putAll(paths); + } + public void addMarker(ReplayMarker marker) { this.metadata.replayMarkers.put(this.writtenTicks, marker); } @@ -231,6 +241,7 @@ public class Recorder { int localPlayerUpdatesPerSecond = Flashback.getConfig().localPlayerUpdatesPerSecond; boolean trackAccurateFirstPersonPosition = localPlayerUpdatesPerSecond > 20; + boolean wroteNewTick = false; if (minecraft.level != null && (minecraft.getOverlay() == null || !minecraft.getOverlay().isPauseScreen()) && !minecraft.isPaused() && !this.isPaused && isLevelLoaded) { @@ -241,6 +252,7 @@ public class Recorder { this.writeAccurateFirstPersonPosition(localPlayerUpdatesPerSecond); } + wroteNewTick = true; this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); this.writtenTicksInChunk += 1; this.writtenTicks += 1; @@ -274,7 +286,7 @@ public class Recorder { if (writeChunk) { // Add an extra tick to avoid edge-cases with 0-length replay chunks - if (this.writtenTicksInChunk == 0) { + if (this.writtenTicksInChunk == 0 || !wroteNewTick) { this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); this.writtenTicksInChunk += 1; this.writtenTicks += 1; @@ -631,6 +643,13 @@ public class Recorder { gamePackets.add(((Packet) packet.packet)); + if (packet.packet instanceof ClientboundLoginPacket) { + this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets); + gamePackets.clear(); + + this.writeCreateLocalPlayer(); + } + if (this.isConfiguring) { endedConfiguration = true; this.isConfiguring = false; @@ -664,6 +683,44 @@ public class Recorder { return endedConfiguration; } + private void writeCreateLocalPlayer() { + LocalPlayer localPlayer = Minecraft.getInstance().player; + if (localPlayer != null) { + UUID uuid = localPlayer.getUUID(); + double x = localPlayer.getX(); + double y = localPlayer.getY(); + double z = localPlayer.getZ(); + float xRot = localPlayer.getXRot(); + float yRot = localPlayer.getYRot(); + float yHeadRot = localPlayer.getYHeadRot(); + Vec3 deltaMovement = localPlayer.getDeltaMovement(); + + GameProfile currentProfile = localPlayer.getGameProfile(); + GameProfile newProfile = new GameProfile(currentProfile.getId(), currentProfile.getName()); + newProfile.getProperties().putAll(Minecraft.getInstance().getGameProfile().getProperties()); + newProfile.getProperties().putAll(currentProfile.getProperties()); + int gameModeId = Minecraft.getInstance().gameMode.getPlayerMode().getId(); + + this.asyncReplaySaver.submit(writer -> { + writer.startAction(ActionCreateLocalPlayer.INSTANCE); + + RegistryFriendlyByteBuf registryFriendlyByteBuf = writer.friendlyByteBuf(); + registryFriendlyByteBuf.writeUUID(uuid); + registryFriendlyByteBuf.writeDouble(x); + registryFriendlyByteBuf.writeDouble(y); + registryFriendlyByteBuf.writeDouble(z); + registryFriendlyByteBuf.writeFloat(xRot); + registryFriendlyByteBuf.writeFloat(yRot); + registryFriendlyByteBuf.writeFloat(yHeadRot); + registryFriendlyByteBuf.writeVec3(deltaMovement); + ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, newProfile); + registryFriendlyByteBuf.writeVarInt(gameModeId); + + writer.finishAction(ActionCreateLocalPlayer.INSTANCE); + }); + } + } + public void writeLevelEvent(int type, BlockPos blockPos, int data, boolean globalEvent) { if (!this.readyToWrite()) { return; @@ -798,6 +855,11 @@ public class Recorder { localPlayer.isReducedDebugInfo(), localPlayer.shouldShowDeathScreen(), localPlayer.getDoLimitedCrafting(), commonPlayerSpawnInfo, false); gamePackets.add(loginPacket); + // Write local player + this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets); + gamePackets.clear(); + this.writeCreateLocalPlayer(); + // Create player info update packet var infoUpdatePacket = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LISTED, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), List.of()); @@ -910,7 +972,6 @@ public class Recorder { for (int i = 0; i < chunks.length(); i++) { LevelChunk chunk = chunks.get(i); if (chunk != null) { - System.out.println("chunk " + chunk.getPos() + " is light correct: " + chunk.isLightCorrect()); var task = pool.submit(() -> new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), new BitSet(), new BitSet())); levelChunkPacketTasks.add(new PositionedTask(chunk.getPos(), task)); } diff --git a/src/main/java/com/moulberry/flashback/screen/CombineReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/CombineReplayScreen.java new file mode 100644 index 0000000..7881d57 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/CombineReplayScreen.java @@ -0,0 +1,195 @@ +package com.moulberry.flashback.screen; + +import com.mojang.serialization.Lifecycle; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FlashbackGson; +import com.moulberry.flashback.exporting.AsyncFileDialogs; +import com.moulberry.flashback.io.ReplayCombiner; +import com.moulberry.flashback.playback.EmptyLevelSource; +import com.moulberry.flashback.record.FlashbackMeta; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.StringWidget; +import net.minecraft.client.gui.layouts.FrameLayout; +import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.screens.AlertScreen; +import net.minecraft.client.gui.screens.ConfirmScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.commands.Commands; +import net.minecraft.core.Holder; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.server.WorldLoader; +import net.minecraft.server.WorldStem; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.world.Difficulty; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.WorldDimensions; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.PrimaryLevelData; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +public class CombineReplayScreen extends Screen { + + @Nullable + private final Screen lastScreen; + + private String newReplayName = "Combined Replay"; + private Path firstReplay; + private Path secondReplay; + private Path output; + + private Button firstReplayButton; + private Button secondReplayButton; + private Button outputButton; + + protected CombineReplayScreen(@Nullable Screen lastScreen, @Nullable Path firstReplay, @Nullable Path secondReplay, @Nullable Path output) { + super(Component.literal("Combine Replay")); + this.lastScreen = lastScreen; + this.firstReplay = firstReplay; + this.secondReplay = secondReplay; + this.output = output; + } + + @Override + protected void init() { + super.init(); + + GridLayout gridLayout = new GridLayout(); + gridLayout.defaultCellSetting().padding(4, 4, 4, 0); + GridLayout.RowHelper rowHelper = gridLayout.createRowHelper(2); + + rowHelper.addChild(new StringWidget(204, 20, Component.literal("Combine Replay"), this.font), 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("New Replay Name"), this.font).alignLeft(), 2); + + EditBox replayNameEditBox = new EditBox(this.font, 0, 0, 204, 20, Component.literal(this.newReplayName)); + replayNameEditBox.setValue(this.newReplayName); + replayNameEditBox.setResponder(string -> this.newReplayName = string); + rowHelper.addChild(replayNameEditBox, 2); + + Path replayFolder = Flashback.getReplayFolder(); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Source #1"), this.font).alignLeft(), 2); + + String firstReplayPath = this.firstReplay == null ? "" : this.firstReplay.toString(); + this.firstReplayButton = Button.builder(Component.literal(firstReplayPath), button -> { + CompletableFuture future = AsyncFileDialogs.openFileDialog(replayFolder.toString(), + "Replay Archive", "zip"); + future.thenAccept(pathStr -> { + if (pathStr != null) { + this.firstReplay = Path.of(pathStr); + this.firstReplayButton.setMessage(Component.literal(this.firstReplay.toString())); + } + }); + }).width(204).build(); + rowHelper.addChild(this.firstReplayButton, 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Source #2"), this.font).alignLeft(), 2); + + String secondReplayPath = this.secondReplay == null ? "" : this.secondReplay.toString(); + this.secondReplayButton = Button.builder(Component.literal(secondReplayPath), button -> { + CompletableFuture future = AsyncFileDialogs.openFileDialog(replayFolder.toString(), + "Replay Archive", "zip"); + future.thenAccept(pathStr -> { + if (pathStr != null) { + this.secondReplay = Path.of(pathStr); + this.secondReplayButton.setMessage(Component.literal(this.secondReplay.toString())); + } + }); + }).width(204).build(); + rowHelper.addChild(this.secondReplayButton, 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Output"), this.font).alignLeft(), 2); + + String outputPath = this.output == null ? "" : this.output.toString(); + this.outputButton = Button.builder(Component.literal(outputPath), button -> { + CompletableFuture future = AsyncFileDialogs.saveFileDialog(replayFolder.toString(), "combined.zip", + "Replay Archive", "zip"); + future.thenAccept(pathStr -> { + if (pathStr != null) { + this.output = Path.of(pathStr); + this.outputButton.setMessage(Component.literal(this.output.toString())); + } + }); + }).width(204).build(); + rowHelper.addChild(this.outputButton, 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2); + + rowHelper.addChild(Button.builder(Component.literal("Combine Replays"), button -> { + try { + PackRepository packRepository = ServerPacksSource.createVanillaTrustedRepository(); + packRepository.reload(); + + WorldDataConfiguration worldDataConfiguration = new WorldDataConfiguration(new DataPackConfig(List.of(), List.of()), FeatureFlags.DEFAULT_FLAGS); + LevelSettings levelSettings = new LevelSettings("Replay", GameType.SPECTATOR, false, Difficulty.NORMAL, true, new GameRules(), worldDataConfiguration); + WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, worldDataConfiguration, false, true); + WorldLoader.InitConfig initConfig = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, 4); + + WorldStem worldStem = Util.blockUntilDone(executor -> WorldLoader.load(initConfig, dataLoadContext -> { + Registry registry = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze(); + + Holder.Reference plains = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.BIOME).getHolder(Biomes.PLAINS).get(); + Holder.Reference overworld = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.DIMENSION_TYPE).getHolder(BuiltinDimensionTypes.OVERWORLD).get(); + + WorldDimensions worldDimensions = new WorldDimensions(Map.of(LevelStem.OVERWORLD, new LevelStem(overworld, new EmptyLevelSource(plains)))); + WorldDimensions.Complete complete = worldDimensions.bake(registry); + + return new WorldLoader.DataLoadOutput<>(new PrimaryLevelData(levelSettings, new WorldOptions(0L, false, false), + complete.specialWorldProperty(), complete.lifecycle()), complete.dimensionsRegistryAccess()); + }, WorldStem::new, Util.backgroundExecutor(), executor)).get(); + + ReplayCombiner.combine(worldStem.registries().compositeAccess(), this.firstReplay, this.secondReplay, this.output); + Minecraft.getInstance().setScreen(new TitleScreen()); + + worldStem.close(); + } catch (Exception e) { + Flashback.LOGGER.error("Error combining replays", e); + Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.lastScreen), + Component.literal("Unable to combine replays"), Component.literal(e.getMessage()))); + } + + }).width(98).build(), 1); + rowHelper.addChild(Button.builder(Component.literal("Cancel"), button -> { + Minecraft.getInstance().setScreen(this.lastScreen); + }).width(98).build(), 1); + + gridLayout.arrangeElements(); + FrameLayout.alignInRectangle(gridLayout, 0, 0, this.width, this.height, 0.5f, 0.5f); + gridLayout.visitWidgets(this::addRenderableWidget); + } + + @Override + public void onClose() { + this.minecraft.setScreen(this.lastScreen); + } +} diff --git a/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java index 14e00c8..b388365 100644 --- a/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java @@ -63,6 +63,10 @@ public class EditReplayScreen extends Screen { rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2); + rowHelper.addChild(Button.builder(Component.literal("Combine With Other Replay"), button -> { + this.minecraft.setScreen(new CombineReplayScreen(this, this.replayPath, null, null)); + }).width(204).build(), 2); + this.saveChangesButton = rowHelper.addChild(Button.builder(Component.literal("Save Changes"), button -> { this.applyChanges(); }).width(98).build()); diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java index b864c38..a73ab05 100644 --- a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java +++ b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java @@ -19,6 +19,7 @@ import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.ObjectSelectionList; +import net.minecraft.client.gui.components.WidgetSprites; import net.minecraft.client.gui.components.toasts.SystemToast; import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.client.gui.navigation.CommonInputs; @@ -62,6 +63,7 @@ public class ReplaySelectionList extends ObjectSelectionList currentlyDisplayedReplays; private String filter; private final LoadingHeader loadingHeader; + private final LoadFromDeviceHeader loadFromDeviceHeader; private Map lastOpenTimes = null; @@ -69,6 +71,7 @@ public class ReplaySelectionList extends ObjectSelectionList list) { this.clearEntries(); + this.addEntry(this.loadFromDeviceHeader); string = string.toLowerCase(Locale.ROOT); for (ReplaySummary ReplaySummary : list) { if (!this.filterAccepts(string, ReplaySummary)) continue; @@ -253,6 +257,7 @@ public class ReplaySelectionList extends ObjectSelectionList this.minecraft.setScreen(this.screen))); -// return; -// } -// try { -// editWorldScreen = EditWorldScreen.create(this.minecraft, levelStorageAccess, bl -> { -// levelStorageAccess.safeClose(); -// if (bl) { -// ReplaySelectionList.this.reloadWorldList(); -// } -// this.minecraft.setScreen(this.screen); -// }); -// } catch (IOException | NbtException | ReportedNbtException exception) { -// levelStorageAccess.safeClose(); -// SystemToast.onWorldAccessFailure(this.minecraft, string); -// LOGGER.error("Failed to load world data {}", (Object)string, (Object)exception); -// ReplaySelectionList.this.reloadWorldList(); -// return; -// } -// this.minecraft.setScreen(editWorldScreen); } private void loadIcon() { diff --git a/src/main/java/com/moulberry/flashback/spline/CatmullRom.java b/src/main/java/com/moulberry/flashback/spline/CatmullRom.java index 6bfaae8..c1c34e9 100644 --- a/src/main/java/com/moulberry/flashback/spline/CatmullRom.java +++ b/src/main/java/com/moulberry/flashback/spline/CatmullRom.java @@ -1,9 +1,8 @@ package com.moulberry.flashback.spline; import com.moulberry.flashback.Interpolation; -import org.joml.Quaterniond; +import net.minecraft.util.Mth; import org.joml.Vector3d; -import org.joml.Vector3f; public class CatmullRom { @@ -97,100 +96,6 @@ public class CatmullRom { } } - private static double rotationCentripetalTj(Quaterniond p1, Quaterniond p2) { - Quaterniond delta = p1.invert(new Quaterniond()).mul(p2); - - double lengthSq = delta.x*delta.x + delta.y*delta.y + delta.z*delta.z; - double length = Math.sqrt(lengthSq); - - double angleBetween = Math.abs(2 * Math.atan2(length, delta.w)); - angleBetween = Math.max(0, Math.min(Math.PI, angleBetween)); - return Math.pow(angleBetween, 0.5f); - } - - public static Quaterniond rotation(Quaterniond p0, Quaterniond p1, Quaterniond p2, Quaterniond p3, float time1, float time2, float time3, float amount) { - double tj1 = rotationCentripetalTj(p0, p1); - double tj2 = rotationCentripetalTj(p1, p2); - double tj3 = rotationCentripetalTj(p2, p3); - double averageTj = (tj1 + tj2 + tj3) / 3f; - - if (averageTj == 0.0) { - return new Quaterniond(p1); - } - - double averageTime = time3 / 3f; - double relation = averageTime / averageTj; - - double deltaTime1 = 0.0f; - if (time1 > 0.0f) { - double factor1 = (tj1 * relation) / time1; - factor1 = Math.max(0.4f, Math.min(2.5f, factor1)); - deltaTime1 = (tj1 * relation) / factor1; - } - - double deltaTime2 = 0.0f; - if (time2 - time1 > 0.0f) { - double factor2 = (tj2 * relation) / (time2 - time1); - factor2 = Math.max(0.4f, Math.min(2.5f, factor2)); - deltaTime2 = (tj2 * relation) / factor2; - } - - double deltaTime3 = 0.0f; - if (time3 - time2 > 0.0f) { - double factor3 = (tj3 * relation) / (time3 - time2); - factor3 = Math.max(0.4f, Math.min(2.5f, factor3)); - deltaTime3 = (tj3 * relation) / factor3; - } - - double t0 = 0; - double t1 = t0 + deltaTime1; - double t2 = t1 + deltaTime2; - double t3 = t2 + deltaTime3; - - double t = t1 + (t2 - t1) * amount; - - Quaterniond a1; - if (t0 == t1) { - a1 = p0.nlerp(p1, 0.5f, new Quaterniond()).normalize(); - } else { - a1 = p0.nlerp(p1, (t - t0)/(t1 - t0), new Quaterniond()).normalize(); - } - - Quaterniond a2; - if (t1 == t2) { - a2 = p1.nlerp(p2, 0.5f, new Quaterniond()).normalize(); - } else { - a2 = p1.nlerp(p2, (t - t1)/(t2 - t1), new Quaterniond()).normalize(); - } - - Quaterniond a3; - if (t2 == t3) { - a3 = p2.nlerp(p3, 0.5f, new Quaterniond()).normalize(); - } else { - a3 = p2.nlerp(p3, (t - t2)/(t3 - t2), new Quaterniond()).normalize(); - } - - Quaterniond b1; - if (t0 == t2) { - b1 = a1.nlerp(a2, 0.5f, new Quaterniond()).normalize(); - } else { - b1 = a1.nlerp(a2, (t - t0)/(t2 - t0), new Quaterniond()).normalize(); - } - - Quaterniond b2; - if (t1 == t3) { - b2 = a2.nlerp(a3, 0.5f, new Quaterniond()).normalize(); - } else { - b2 = a2.nlerp(a3, (t - t1)/(t3 - t1), new Quaterniond()).normalize(); - } - - if (t1 == t2) { - return b1.nlerp(b2, 0.5f, new Quaterniond()).normalize(); - } else { - return b1.nlerp(b2, (t - t1)/(t2 - t1), new Quaterniond()).normalize(); - } - } - private static float valueCentripetalTj(float p1, float p2) { return (float) Math.sqrt(Math.abs(p1 - p2)); } @@ -278,4 +183,96 @@ public class CatmullRom { } } + private static float degreesCentripetalTj(float p1, float p2) { + return (float) Math.sqrt(Math.abs(Mth.wrapDegrees(p1 - p2))); + } + + public static float degrees(float p0, float p1, float p2, float p3, float time1, float time2, float time3, float amount) { + p0 = Mth.wrapDegrees(p0); + p1 = Mth.wrapDegrees(p1); + p2 = Mth.wrapDegrees(p2); + p3 = Mth.wrapDegrees(p3); + + float tj1 = degreesCentripetalTj(p0, p1); + float tj2 = degreesCentripetalTj(p1, p2); + float tj3 = degreesCentripetalTj(p2, p3); + float averageTj = (tj1 + tj2 + tj3) / 3f; + + if (averageTj == 0.0) { + return p1; + } + + float averageTime = time3 / 3f; + float relation = averageTime / averageTj; + + float deltaTime1 = 0.0f; + if (time1 > 0.0f) { + float factor1 = (tj1 * relation) / time1; + factor1 = Math.max(0.4f, Math.min(2.5f, factor1)); + deltaTime1 = (tj1 * relation) / factor1; + } + + float deltaTime2 = 0.0f; + if (time2 - time1 > 0.0f) { + float factor2 = (tj2 * relation) / (time2 - time1); + factor2 = Math.max(0.4f, Math.min(2.5f, factor2)); + deltaTime2 = (tj2 * relation) / factor2; + } + + float deltaTime3 = 0.0f; + if (time3 - time2 > 0.0f) { + float factor3 = (tj3 * relation) / (time3 - time2); + factor3 = Math.max(0.4f, Math.min(2.5f, factor3)); + deltaTime3 = (tj3 * relation) / factor3; + } + + float t0 = 0; + float t1 = t0 + deltaTime1; + float t2 = t1 + deltaTime2; + float t3 = t2 + deltaTime3; + + float t = t1 + (t2 - t1) * amount; + + float a1; + if (t0 == t1) { + a1 = Interpolation.linearAngle(p0, p1, 0.5f); + } else { + a1 = Interpolation.linearAngle(p0, p1, (t - t0)/(t1 - t0)); + } + + float a2; + if (t1 == t2) { + a2 = Interpolation.linearAngle(p1, p2, 0.5f); + } else { + a2 = Interpolation.linearAngle(p1, p2, (t - t1)/(t2 - t1)); + } + + float a3; + if (t2 == t3) { + a3 = Interpolation.linearAngle(p2, p3, 0.5f); + } else { + a3 = Interpolation.linearAngle(p2, p3, (t - t2)/(t3 - t2)); + } + + float b1; + if (t0 == t2) { + b1 = Interpolation.linearAngle(a1, a2, 0.5f); + } else { + b1 = Interpolation.linearAngle(a1, a2, (t - t0)/(t2 - t0)); + } + + float b2; + if (t1 == t3) { + b2 = Interpolation.linearAngle(a2, a3, 0.5f); + } else { + b2 = Interpolation.linearAngle(a2, a3, (t - t1)/(t3 - t1)); + } + + if (t1 == t2) { + return Interpolation.linearAngle(b1, b2, 0.5f); + } else { + return Interpolation.linearAngle(b1, b2, (t - t1)/(t2 - t1)); + } + } + } diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java index 65951c3..a6283b0 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorState.java +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -1,5 +1,6 @@ package com.moulberry.flashback.state; +import com.mojang.authlib.GameProfile; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.editor.ui.ReplayUI; @@ -16,6 +17,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.PlayerInfo; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; @@ -44,6 +46,9 @@ public class EditorState { public UUID audioSourceEntity = null; public Set hideDuringExport = new HashSet<>(); + public Set hideNametags = new HashSet<>(); + public Map skinOverride = new HashMap<>(); + public Map nameOverride = new HashMap<>(); public transient int recordingCameraMovementTrack = -1; public transient int recordingCameraMovementMinTick = -1; diff --git a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java index 9b9095f..f55cf2a 100644 --- a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java +++ b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java @@ -43,6 +43,8 @@ public class ReplayVisuals { public long overrideTimeOfDay = -1; + public boolean overrideNightVision = false; + public boolean ruleOfThirdsGuide = false; public boolean centerGuide = false; public boolean cameraPath = true; diff --git a/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java b/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java index 8932a08..7681f94 100644 --- a/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java +++ b/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java @@ -2,6 +2,7 @@ package com.moulberry.flashback.visuals; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.moulberry.flashback.Flashback; +import net.fabricmc.fabric.api.client.rendering.v1.CoreShaderRegistrationCallback; import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; import net.fabricmc.fabric.impl.client.rendering.FabricShaderProgram; import net.minecraft.client.Minecraft; @@ -11,43 +12,22 @@ import net.minecraft.server.packs.resources.ResourceManager; import java.io.IOException; -public class ShaderManager implements SimpleSynchronousResourceReloadListener { +public class ShaderManager { public static final ShaderManager INSTANCE = new ShaderManager(); public static ShaderInstance blitScreenRoundAlpha; public static ShaderInstance blitScreenFlip; - @Override - public ResourceLocation getFabricId() { - return ResourceLocation.parse("flashback:shaders"); - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - Flashback.LOGGER.info("Reloading shaders..."); - - if (blitScreenRoundAlpha != null) { - blitScreenRoundAlpha.close(); - blitScreenRoundAlpha = null; - } - if (blitScreenFlip != null) { - blitScreenFlip.close(); - blitScreenFlip = null; - } - - try { - blitScreenRoundAlpha = new FabricShaderProgram(Minecraft.getInstance().getResourceManager(), - ResourceLocation.parse("flashback:blit_screen_round_alpha"), DefaultVertexFormat.BLIT_SCREEN); - } catch (IOException e) { - Flashback.LOGGER.error("Failed to load flashback:blit_screen_round_alpha shader", e); - } - try { - blitScreenFlip = new FabricShaderProgram(Minecraft.getInstance().getResourceManager(), - ResourceLocation.parse("flashback:blit_screen_flip"), DefaultVertexFormat.BLIT_SCREEN); - } catch (IOException e) { - Flashback.LOGGER.error("Failed to load flashback:blit_screen_flip shader", e); - } + public void register() { + CoreShaderRegistrationCallback.EVENT.register(context -> { + context.register(ResourceLocation.parse("flashback:blit_screen_round_alpha"), DefaultVertexFormat.BLIT_SCREEN, shaderInstance -> { + blitScreenRoundAlpha = shaderInstance; + }); + context.register(ResourceLocation.parse("flashback:blit_screen_flip"), DefaultVertexFormat.BLIT_SCREEN, shaderInstance -> { + blitScreenFlip = shaderInstance; + }); + }); } } diff --git a/src/main/resources/assets/flashback/lang/en_us.json b/src/main/resources/assets/flashback/lang/en_us.json index 9182e72..d9f013c 100644 --- a/src/main/resources/assets/flashback/lang/en_us.json +++ b/src/main/resources/assets/flashback/lang/en_us.json @@ -2,6 +2,7 @@ "flashback.select_replay": "Select Replay", "flashback.select_replay.open": "Open Replay", "flashback.select_replay.loading_replays": "Loading Replays", + "flashback.select_replay.load_replay_from_file": "Load replay from file...", "flashback.select_replay.replay": "Replay", "flashback.select_replay.data_read": "Reading replay data...", "flashback.select_replay.delete_question": "Are you sure you want to delete this replay?", diff --git a/src/main/resources/flashback.mixins.json b/src/main/resources/flashback.mixins.json index 21e9d75..88f72ce 100644 --- a/src/main/resources/flashback.mixins.json +++ b/src/main/resources/flashback.mixins.json @@ -3,6 +3,7 @@ "package": "com.moulberry.flashback.mixin", "compatibilityLevel": "JAVA_21", "client": [ + "MixinAbstractClientPlayer", "MixinDebugScreenOverlay", "MixinLevelRenderer", "MixinMinecraft", @@ -35,6 +36,7 @@ "visuals.MixinFogRenderer", "visuals.MixinGui", "visuals.MixinLevelRenderer", + "visuals.MixinLightTexture", "visuals.MixinLivingEntityRenderer", "visuals.MixinLoadingOverlay", "visuals.MixinMouseHandler", @@ -46,13 +48,14 @@ }, "mixins": [ "MixinThreadedLevelLightEngine", - "compat.MixinAxiomEditorUI", - "compat.MixinFabricMinecraftServer", + "compat.axiom.MixinAxiomEditorUI", "compat.MixinSodiumWorldRenderer", + "compat.axiom.MixinAxiomServerIntegration", "compat.bobby.FakeChunkManagerAccessor", "compat.bobby.MixinBobby", "compat.bobby.MixinBobbyFakeChunkManager", - "compat.distanthorizons.MixinSharedApi", + "compat.fabric.MixinFabricMinecraftServer", + "compat.fabric.MixinFabricServerPlayNetworking", "compat.iris.MixinIrisSystemTimeUniforms", "compat.replaymod.MixinReplayModRecording", "compat.voice_chat.MixinVoiceChatALSpeakerBase",