diff --git a/build.gradle b/build.gradle index d8c86c6..7242488 100644 --- a/build.gradle +++ b/build.gradle @@ -71,9 +71,7 @@ dependencies { 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:modmenu:xhN1IvHi") - // modCompileOnly("maven.modrinth:axiom:D3uDJmiB") + modImplementation("maven.modrinth:modmenu:xhN1IvHi") shadow(implementation("org.bytedeco:javacv-platform:1.5.10") { exclude group: "org.bytedeco", module: "artoolkitplus" diff --git a/gradle.properties b/gradle.properties index 0d73286..67b347b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ yarn_mappings=1.21.3+build.2 loader_version=0.16.9 # Mod Properties -mod_version=0.12.0 +mod_version=0.13.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 78b0252..8092ee5 100644 --- a/src/main/java/com/moulberry/flashback/Flashback.java +++ b/src/main/java/com/moulberry/flashback/Flashback.java @@ -20,10 +20,12 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType; import com.moulberry.flashback.keyframe.types.CameraShakeKeyframeType; import com.moulberry.flashback.keyframe.types.FOVKeyframeType; +import com.moulberry.flashback.keyframe.types.FreezeKeyframeType; import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; import com.moulberry.flashback.keyframe.types.TimeOfDayKeyframeType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; +import com.moulberry.flashback.packet.FlashbackClearEntities; import com.moulberry.flashback.packet.FlashbackClearParticles; import com.moulberry.flashback.packet.FinishedServerTick; import com.moulberry.flashback.packet.FlashbackForceClientTick; @@ -106,6 +108,9 @@ import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; @@ -116,6 +121,7 @@ import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; public class Flashback implements ModInitializer, ClientModInitializer { public static final Logger LOGGER = LoggerFactory.getLogger("flashback"); @@ -166,6 +172,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { PayloadTypeRegistry.playS2C().register(FlashbackForceClientTick.TYPE, StreamCodec.unit(FlashbackForceClientTick.INSTANCE)); PayloadTypeRegistry.playS2C().register(FlashbackClearParticles.TYPE, StreamCodec.unit(FlashbackClearParticles.INSTANCE)); + PayloadTypeRegistry.playS2C().register(FlashbackClearEntities.TYPE, StreamCodec.unit(FlashbackClearEntities.INSTANCE)); PayloadTypeRegistry.playS2C().register(FlashbackInstantlyLerp.TYPE, StreamCodec.unit(FlashbackInstantlyLerp.INSTANCE)); PayloadTypeRegistry.playS2C().register(FlashbackRemoteSelectHotbarSlot.TYPE, FlashbackRemoteSelectHotbarSlot.STREAM_CODEC); PayloadTypeRegistry.playS2C().register(FlashbackRemoteExperience.TYPE, FlashbackRemoteExperience.STREAM_CODEC); @@ -231,6 +238,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { KeyframeRegistry.register(SpeedKeyframeType.INSTANCE); KeyframeRegistry.register(TimelapseKeyframeType.INSTANCE); KeyframeRegistry.register(TimeOfDayKeyframeType.INSTANCE); + KeyframeRegistry.register(FreezeKeyframeType.INSTANCE); ClientPlayNetworking.registerGlobalReceiver(FlashbackForceClientTick.TYPE, (payload, context) -> { if (Flashback.isInReplay()) { @@ -244,6 +252,16 @@ public class Flashback implements ModInitializer, ClientModInitializer { } }); + ClientPlayNetworking.registerGlobalReceiver(FlashbackClearEntities.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) { + if (entity != null && !(entity instanceof Player)) { + entity.discard(); + } + } + } + }); + ClientPlayNetworking.registerGlobalReceiver(FlashbackInstantlyLerp.TYPE, (payload, context) -> { if (Flashback.isInReplay()) { for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) { @@ -356,13 +374,6 @@ public class Flashback implements ModInitializer, ClientModInitializer { AccurateEntityPositionHandler.tick(); - if (Flashback.isInReplay() && !Flashback.isExporting()) { - EditorState editorState = EditorStateManager.getCurrent(); - if (editorState != null) { - editorState.recordCameraMovement(); - } - } - // Fix for camera entity sometimes being incorrect when respawning Entity camera = Minecraft.getInstance().cameraEntity; LocalPlayer player = Minecraft.getInstance().player; @@ -374,6 +385,8 @@ public class Flashback implements ModInitializer, ClientModInitializer { } } } + + Flashback.getConfig().tickDelayedSave(); }); ClientTickEvents.START_CLIENT_TICK.register(minecraft -> { @@ -532,7 +545,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { private void deleteUnusedReplayStates() { Path flashbackDir = Flashback.getDataDirectory(); - Path replayDir = flashbackDir.resolve("replays"); + Path replayDir = Flashback.getReplayFolder(); Path replayStatesDir = flashbackDir.resolve("editor_states"); if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) { @@ -543,6 +556,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { } CompletableFuture.runAsync(() -> { + long currentTime = System.currentTimeMillis(); Map replayStates = new HashMap<>(); // Find existing replay states @@ -558,6 +572,15 @@ public class Flashback implements ModInitializer, ClientModInitializer { withoutExtension = filename.substring(0, filename.length() - 9); } + BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class); + BasicFileAttributes basicFileAttributes = attributeView.readAttributes(); + + long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis()); + long timeDifference = Math.abs(currentTime - lastModified); + if (timeDifference < Duration.ofDays(30).toMillis()) { + continue; + } + if (withoutExtension != null) { UUID uuid; try { @@ -571,6 +594,10 @@ public class Flashback implements ModInitializer, ClientModInitializer { } } catch (IOException ignored) {} + if (replayStates.isEmpty()) { + return; + } + // Find which uuids are still valid because they have replays Set replayUuids = new HashSet<>(); try (DirectoryStream directoryStream = Files.newDirectoryStream(replayDir)) { @@ -773,7 +800,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { if (config.recentReplays.size() > 32) { config.recentReplays.remove(config.recentReplays.size() - 1); } - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); // Actually load try { diff --git a/src/main/java/com/moulberry/flashback/FlashbackGson.java b/src/main/java/com/moulberry/flashback/FlashbackGson.java index e78e556..18e59d1 100644 --- a/src/main/java/com/moulberry/flashback/FlashbackGson.java +++ b/src/main/java/com/moulberry/flashback/FlashbackGson.java @@ -2,7 +2,6 @@ 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; @@ -11,6 +10,7 @@ import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; import com.moulberry.flashback.keyframe.impl.FOVKeyframe; +import com.moulberry.flashback.keyframe.impl.FreezeKeyframe; import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; @@ -18,7 +18,7 @@ import com.moulberry.flashback.serialization.QuaterniondTypeAdapater; import com.moulberry.flashback.serialization.QuaternionfTypeAdapater; import com.moulberry.flashback.serialization.Vector3dTypeAdapater; import com.moulberry.flashback.serialization.Vector3fTypeAdapater; -import com.moulberry.flashback.state.EditorStateHistoryAction; +import com.moulberry.flashback.state.EditorSceneHistoryAction; import org.joml.Quaterniond; import org.joml.Quaternionf; import org.joml.Vector3d; @@ -45,13 +45,14 @@ public class FlashbackGson { .registerTypeAdapter(TickrateKeyframe.class, new TickrateKeyframe.TypeAdapter()) .registerTypeAdapter(TimelapseKeyframe.class, new TimelapseKeyframe.TypeAdapter()) .registerTypeAdapter(TimeOfDayKeyframe.class, new TimeOfDayKeyframe.TypeAdapter()) + .registerTypeAdapter(FreezeKeyframe.class, new FreezeKeyframe.TypeAdapter()) .registerTypeAdapter(Keyframe.class, new Keyframe.TypeAdapter()) - .registerTypeAdapter(EditorStateHistoryAction.SetKeyframe.class, new EditorStateHistoryAction.SetKeyframe.TypeAdapter()) - .registerTypeAdapter(EditorStateHistoryAction.RemoveKeyframe.class, new EditorStateHistoryAction.RemoveKeyframe.TypeAdapter()) - .registerTypeAdapter(EditorStateHistoryAction.AddTrack.class, new EditorStateHistoryAction.AddTrack.TypeAdapter()) - .registerTypeAdapter(EditorStateHistoryAction.RemoveTrack.class, new EditorStateHistoryAction.RemoveTrack.TypeAdapter()) - .registerTypeAdapter(EditorStateHistoryAction.class, new EditorStateHistoryAction.TypeAdapter()); + .registerTypeAdapter(EditorSceneHistoryAction.SetKeyframe.class, new EditorSceneHistoryAction.SetKeyframe.TypeAdapter()) + .registerTypeAdapter(EditorSceneHistoryAction.RemoveKeyframe.class, new EditorSceneHistoryAction.RemoveKeyframe.TypeAdapter()) + .registerTypeAdapter(EditorSceneHistoryAction.AddTrack.class, new EditorSceneHistoryAction.AddTrack.TypeAdapter()) + .registerTypeAdapter(EditorSceneHistoryAction.RemoveTrack.class, new EditorSceneHistoryAction.RemoveTrack.TypeAdapter()) + .registerTypeAdapter(EditorSceneHistoryAction.class, new EditorSceneHistoryAction.TypeAdapter()); } } diff --git a/src/main/java/com/moulberry/flashback/FreezeSlowdownFormula.java b/src/main/java/com/moulberry/flashback/FreezeSlowdownFormula.java new file mode 100644 index 0000000..a1cb533 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/FreezeSlowdownFormula.java @@ -0,0 +1,65 @@ +package com.moulberry.flashback; + +public class FreezeSlowdownFormula { + + public static double calculateFreezeClientTickDerivative(double serverTicks, int frozenDelay, double freezePowerBase) { + double freezePowerSq = freezePowerBase * freezePowerBase; + double freezePower4 = freezePowerSq * freezePowerSq; + return -4 * Math.log(freezePowerBase) * Math.pow(freezePowerBase, 4 * serverTicks / frozenDelay) / (frozenDelay - frozenDelay*freezePower4); + } + + public static double calculateFreezeClientTick(double serverTicks, int frozenDelay, double freezePowerBase) { + return (1 - Math.pow(freezePowerBase, 4 * serverTicks/frozenDelay)) / (1 - Math.pow(freezePowerBase, 4)); + } + + private static final double[] freezePowers = new double[11]; + + public static double getFreezePowerBase(int freezeTicks, double targetDerivative) { + if (freezeTicks < 0) { + freezeTicks = 0; + } + if (freezeTicks > 10) { + freezeTicks = 10; + } + + double freezePowerBase = freezePowers[freezeTicks]; + if (freezePowerBase == 0) { + freezePowerBase = calculateFreezePower(freezeTicks, targetDerivative); + freezePowers[freezeTicks] = freezePowerBase; + } + return freezePowerBase; + } + + private static double calculateFreezePower(int freezeTicks, double targetDerivative) { + double freezePowerBaseMin = 0.05; + double freezePowerBaseMax = 0.95; + + if (computeDerivativeAtZero(freezeTicks, freezePowerBaseMin) < targetDerivative) { + return freezePowerBaseMin; + } + + if (computeDerivativeAtZero(freezeTicks, freezePowerBaseMax) > targetDerivative) { + return freezePowerBaseMax; + } + + double freezePowerBaseMid = (freezePowerBaseMin + freezePowerBaseMax) / 2.0; + + for (int i = 0; i < 100; i++) { + if (computeDerivativeAtZero(freezeTicks, freezePowerBaseMid) > targetDerivative) { + freezePowerBaseMin = freezePowerBaseMid; + } else { + freezePowerBaseMax = freezePowerBaseMid; + } + freezePowerBaseMid = (freezePowerBaseMin + freezePowerBaseMax) / 2.0; + } + + return freezePowerBaseMid; + } + + private static double computeDerivativeAtZero(int freezeTicks, double freezePower) { + double freezePowerSq = freezePower * freezePower; + double freezePower4 = freezePowerSq * freezePowerSq; + return -4 * Math.log(freezePower) / (freezeTicks - freezeTicks*freezePower4); + } + +} diff --git a/src/main/java/com/moulberry/flashback/PacketHelper.java b/src/main/java/com/moulberry/flashback/PacketHelper.java index 85d063a..b6d1163 100644 --- a/src/main/java/com/moulberry/flashback/PacketHelper.java +++ b/src/main/java/com/moulberry/flashback/PacketHelper.java @@ -3,6 +3,7 @@ package com.moulberry.flashback; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; import net.minecraft.network.protocol.game.VecDeltaCodec; import net.minecraft.server.level.ServerEntity; import net.minecraft.util.Mth; @@ -10,12 +11,15 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.ExperienceOrb; import net.minecraft.world.entity.Marker; import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.PositionMoveRotation; +import net.minecraft.world.entity.Relative; import net.minecraft.world.entity.boss.EnderDragonPart; import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.decoration.Painting; import net.minecraft.world.entity.item.FallingBlockEntity; import net.minecraft.world.entity.monster.warden.Warden; import net.minecraft.world.level.block.Block; +import net.minecraft.world.phys.Vec3; import java.util.ArrayList; @@ -25,6 +29,15 @@ public class PacketHelper { return entity == null || entity.isRemoved() || entity instanceof EnderDragonPart || entity.getType().clientTrackingRange() <= 0; } + public static ClientboundTeleportEntityPacket createTeleportForUnknown(int id, double x, double y, double z, byte yRot, byte xRot, boolean onGround) { + return new ClientboundTeleportEntityPacket( + id, + new PositionMoveRotation(new Vec3(x, y, z), Vec3.ZERO, yRot, xRot), + Relative.DELTA, + onGround + ); + } + public static Packet createAddEntity(Entity entity) { ServerEntity serverEntity = null; diff --git a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java index 167ee29..c18e114 100644 --- a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java +++ b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java @@ -5,6 +5,7 @@ import com.moulberry.flashback.Flashback; import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.screen.select_replay.ReplaySorting; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.ChatFormatting; import net.minecraft.client.OptionInstance; @@ -79,6 +80,11 @@ public class FlashbackConfig { public String defaultExportFilename = "%date%T%time%"; public InterpolationType defaultInterpolationType = InterpolationType.SMOOTH; + public ReplaySorting replaySorting = ReplaySorting.CREATED_DATE; + public boolean sortDescending = true; + + private transient int saveDelay = 0; + @SuppressWarnings("unchecked") public OptionInstance[] createOptionInstances() { List> options = new ArrayList<>(); @@ -213,12 +219,28 @@ public class FlashbackConfig { return new FlashbackConfig(); } + public void delayedSaveToDefaultFolder() { + if (this.saveDelay <= 0) { + this.saveDelay = 200; + } + } + + public void tickDelayedSave() { + if (this.saveDelay > 0) { + this.saveDelay -= 1; + if (this.saveDelay == 0) { + this.saveToDefaultFolder(); + } + } + } + public void saveToDefaultFolder() { Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback"); this.saveToFolder(configFolder); + this.saveDelay = 0; } - public void saveToFolder(Path configFolder) { + public synchronized void saveToFolder(Path configFolder) { Path primary = configFolder.resolve("flashback.json"); Path backup = configFolder.resolve(".flashback.json.backup"); diff --git a/src/main/java/com/moulberry/flashback/editor/SavedTrack.java b/src/main/java/com/moulberry/flashback/editor/SavedTrack.java index 02f9d6e..4bcaa46 100644 --- a/src/main/java/com/moulberry/flashback/editor/SavedTrack.java +++ b/src/main/java/com/moulberry/flashback/editor/SavedTrack.java @@ -2,9 +2,10 @@ package com.moulberry.flashback.editor; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.state.EditorScene; +import com.moulberry.flashback.state.EditorSceneHistoryAction; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateHistoryAction; -import com.moulberry.flashback.state.EditorStateHistoryEntry; +import com.moulberry.flashback.state.EditorSceneHistoryEntry; import com.moulberry.flashback.state.KeyframeTrack; import org.jetbrains.annotations.Nullable; @@ -15,37 +16,37 @@ import java.util.TreeMap; public record SavedTrack(KeyframeType type, int track, boolean copiedFromDisabled, TreeMap keyframes) { - public int applyToEditorState(EditorState editorState, int cursorTicks, int totalTicks) { + public int applyToScene(EditorScene editorScene, int cursorTicks, int totalTicks) { if (this.keyframes == null || this.keyframes.isEmpty()) { return 0; } // Try to apply directly to copied track - if (this.track >= 0 && this.track < editorState.keyframeTracks.size()) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.track); + if (this.track >= 0 && this.track < editorScene.keyframeTracks.size()) { + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(this.track); if ((keyframeTrack.enabled || this.copiedFromDisabled) && keyframeTrack.keyframeType == this.type) { - return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks); + return this.applyTo(editorScene, this.type, keyframeTrack, this.track, cursorTicks, totalTicks); } } // Try to find first eligible enabled track - for (KeyframeTrack keyframeTrack : editorState.keyframeTracks) { + for (KeyframeTrack keyframeTrack : editorScene.keyframeTracks) { if (keyframeTrack.enabled && keyframeTrack.keyframeType == this.type) { - return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks); + return this.applyTo(editorScene, this.type, keyframeTrack, this.track, cursorTicks, totalTicks); } } // Create new track - return this.applyTo(editorState, this.type, null, this.track, cursorTicks, totalTicks); + return this.applyTo(editorScene, this.type, null, this.track, cursorTicks, totalTicks); } - private int applyTo(EditorState editorState, KeyframeType type, @Nullable KeyframeTrack existing, int trackIndex, int cursorTicks, int totalTicks) { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + private int applyTo(EditorScene editorScene, KeyframeType type, @Nullable KeyframeTrack existing, int trackIndex, int cursorTicks, int totalTicks) { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); if (existing == null) { - undo.add(new EditorStateHistoryAction.RemoveTrack(type, trackIndex)); - redo.add(new EditorStateHistoryAction.AddTrack(type, trackIndex)); + undo.add(new EditorSceneHistoryAction.RemoveTrack(type, trackIndex)); + redo.add(new EditorSceneHistoryAction.AddTrack(type, trackIndex)); } int count = 0; @@ -56,18 +57,18 @@ public record SavedTrack(KeyframeType type, int track, boolean copiedFromDisa Keyframe old = existing.keyframesByTick.get(newTick); if (old != null) { - undo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, old.copy())); + undo.add(new EditorSceneHistoryAction.SetKeyframe(type, trackIndex, newTick, old.copy())); } else { - undo.add(new EditorStateHistoryAction.RemoveKeyframe(type, trackIndex, newTick)); + undo.add(new EditorSceneHistoryAction.RemoveKeyframe(type, trackIndex, newTick)); } } - redo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, entry.getValue().copy())); + redo.add(new EditorSceneHistoryAction.SetKeyframe(type, trackIndex, newTick, entry.getValue().copy())); count += 1; } } - editorState.push(new EditorStateHistoryEntry(undo, redo, "Pasted " + count + " keyframe(s)")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Pasted " + count + " keyframe(s)")); return count; } diff --git a/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java b/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java index 573b504..e6846f5 100644 --- a/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java +++ b/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java @@ -1,17 +1,18 @@ package com.moulberry.flashback.editor; import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.state.EditorScene; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.KeyframeTrack; import it.unimi.dsi.fastutil.ints.IntSet; public record SelectedKeyframes(KeyframeType type, int trackIndex, IntSet keyframeTicks) { - public boolean checkValid(EditorState state) { - if (this.trackIndex < 0 || this.trackIndex >= state.keyframeTracks.size()) { + public boolean checkValid(EditorScene scene) { + if (this.trackIndex < 0 || this.trackIndex >= scene.keyframeTracks.size()) { return false; } - KeyframeTrack keyframeTrack = state.keyframeTracks.get(this.trackIndex); + KeyframeTrack keyframeTrack = scene.keyframeTracks.get(this.trackIndex); if (keyframeTrack.keyframeType != this.type) { return false; } 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 cb95b2e..4c459c5 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java @@ -8,6 +8,7 @@ import imgui.flag.ImGuiComboFlags; import imgui.flag.ImGuiHoveredFlags; import imgui.flag.ImGuiInputTextFlags; import imgui.flag.ImGuiNavInput; +import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import imgui.type.ImFloat; 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 0e31601..6eee1f9 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java @@ -10,6 +10,7 @@ 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.editor.ui.windows.WindowType; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.combo_options.Sizing; @@ -96,7 +97,6 @@ public class ReplayUI { private static String infoOverlayText = null; private static long infoOverlayEndMillis = 0; - public static boolean recordCameraMovement = false; private static UUID selectedEntity = null; private static boolean openSelectedEntityPopup = false; @@ -216,10 +216,16 @@ public class ReplayUI { fontConfig.setOversampleV(2); fontConfig.setName("Inter (Medium), 16px"); + fontConfig.setGlyphOffset(0, 0); font = fonts.addFontFromMemoryTTF(loadFont("inter-medium.ttf"), size, fontConfig, glyphRanges); // Merge in Japanese/Korean/Chinese/etc. characters if needed fontConfig.setMergeMode(true); + + fontConfig.setGlyphOffset(0, (int)(5 * getUiScale())); + io.getFonts().addFontFromMemoryTTF(loadFont("materialiconsround-regular.otf"), (int)(20 * getUiScale()), fontConfig, buildMaterialIconRanges()); + fontConfig.setGlyphOffset(0, 0); + if (languageCode.startsWith("he")) { short[] hebrewRanges = new short[]{(short)'\u0590', (short)'\u05FF', (short)'\uFB1D', (short)'\uFB4F', 0}; io.getFonts().addFontFromMemoryTTF(loadFont("heebo-medium.ttf"), size, fontConfig, hebrewRanges); @@ -241,6 +247,27 @@ public class ReplayUI { fonts.clearTexData(); } + private static short[] buildMaterialIconRanges() { + ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder(); + builder.addChar('\ue04b'); + builder.addChar('\ue577'); + builder.addChar('\uefeb'); + builder.addChar('\ue3af'); + builder.addChar('\ue9e4'); + builder.addChar('\ue422'); + builder.addChar('\ue518'); + builder.addChar('\ue945'); + builder.addChar('\ue8f4'); + builder.addChar('\ue8f5'); + builder.addChar('\ue148'); + builder.addChar('\ue5d2'); + builder.addChar('\ue872'); + builder.addChar('\ue3c9'); + builder.addChar('\ue40a'); + builder.addChar('\ue92b'); + return builder.buildRanges(); + } + private static byte[] loadFont(String name) { try { var resource = Minecraft.getInstance().getResourceManager().getResource(Flashback.createResourceLocation(name)); @@ -629,9 +656,6 @@ public class ReplayUI { showText = infoOverlayText; showTextBorderColour = 0xFF00FFFF; } - } else if (recordCameraMovement) { - showText = "Recording Movement as Keyframes..."; - showTextBorderColour = 0xFF0000FF; } if (showText != null) { @@ -743,8 +767,8 @@ public class ReplayUI { ExportScreenshotWindow.render(); PreferencesWindow.render(); ExportQueueWindow.render(); - PlayerListWindow.render(); - MovementWindow.render(); + + WindowType.renderAll(); popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup); 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 index 53b85d5..3df01ff 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportScreenshotWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportScreenshotWindow.java @@ -8,6 +8,7 @@ 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.EditorScene; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import imgui.ImGui; @@ -79,7 +80,9 @@ public class ExportScreenshotWindow { boolean noGui = StartExportWindow.noGui; EditorState copiedEditorState = editorState.copy(); - copiedEditorState.keyframeTracks.clear(); + for (EditorScene scene : copiedEditorState.scenes) { + scene.keyframeTracks.clear(); + } ExportSettings settings = new ExportSettings(null, copiedEditorState, player.position(), player.getYRot(), player.getXRot(), diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/ImGuiWindowRenderer.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/ImGuiWindowRenderer.java new file mode 100644 index 0000000..36ce17f --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/ImGuiWindowRenderer.java @@ -0,0 +1,10 @@ +package com.moulberry.flashback.editor.ui.windows; + +import imgui.type.ImBoolean; + +@FunctionalInterface +public interface ImGuiWindowRenderer { + + void render(ImBoolean open, boolean newlyOpened); + +} 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 77d7fbe..9b43350 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 @@ -2,9 +2,8 @@ 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 com.moulberry.flashback.screen.select_replay.SelectReplayScreen; import imgui.ImGui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.TitleScreen; @@ -73,7 +72,7 @@ public class MainMenuBar { minecraft.level.disconnect(); } minecraft.disconnect(); - minecraft.setScreen(new SelectReplayScreen(new TitleScreen())); + minecraft.setScreen(new SelectReplayScreen(new TitleScreen(), Flashback.getReplayFolder())); } ImGui.endMenu(); } @@ -105,7 +104,7 @@ public class MainMenuBar { } else { openedWindows.add(windowName); } - Flashback.getConfig().saveToDefaultFolder(); + Flashback.getConfig().delayedSaveToDefaultFolder(); } } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java index 358a386..cde29dc 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java @@ -12,6 +12,7 @@ import imgui.ImGui; import imgui.ImGuiViewport; import imgui.flag.ImGuiCond; import imgui.flag.ImGuiWindowFlags; +import imgui.type.ImBoolean; import imgui.type.ImString; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; @@ -27,30 +28,23 @@ import java.util.Locale; public class MovementWindow { - private static WindowOpenState wasOpen = WindowOpenState.UNKNOWN; private static boolean wasDocked = false; - public static void render() { - if (!Flashback.getConfig().openedWindows.contains("movement")) { - wasOpen = WindowOpenState.CLOSED; - return; - } - if (wasOpen == WindowOpenState.CLOSED) { + public static void render(ImBoolean open, boolean newlyOpened) { + if (newlyOpened) { ImGuiViewport viewport = ImGui.getMainViewport(); ImGui.setNextWindowPos(viewport.getCenterX(), viewport.getCenterY(), ImGuiCond.Appearing, 0.5f, 0.5f); } - wasOpen = WindowOpenState.OPEN; - - FlashbackConfig config = Flashback.getConfig(); ImGui.setNextWindowSizeConstraints(250, 50, 5000, 5000); int flags = ImGuiWindowFlags.NoFocusOnAppearing; if (!wasDocked) { flags |= ImGuiWindowFlags.AlwaysAutoResize; } - if (ImGui.begin("Movement###Movement", flags)) { + if (ImGui.begin("Movement###Movement", open, flags)) { wasDocked = ImGui.isWindowDocked(); + FlashbackConfig config = Flashback.getConfig(); int[] direction = new int[]{config.flightCameraDirection ? 1 : 0}; ImGuiHelper.combo("Direction", direction, new String[]{ @@ -60,46 +54,40 @@ public class MovementWindow { boolean flightCameraDirection = direction[0] == 1; if (config.flightCameraDirection != flightCameraDirection) { config.flightCameraDirection = flightCameraDirection; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } float[] momentum = new float[]{config.flightMomentum}; ImGui.sliderFloat("Momentum", momentum, 0.0f, 1.0f); if (config.flightMomentum != momentum[0]) { config.flightMomentum = momentum[0]; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } if (ImGui.checkbox("Lock X", config.flightLockX)) { config.flightLockX = !config.flightLockX; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } ImGui.sameLine(); if (ImGui.checkbox("Lock Y", config.flightLockY)) { config.flightLockY = !config.flightLockY; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } ImGui.sameLine(); if (ImGui.checkbox("Lock Z", config.flightLockZ)) { config.flightLockZ = !config.flightLockZ; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } if (ImGui.checkbox("Lock Yaw", config.flightLockYaw)) { config.flightLockYaw = !config.flightLockYaw; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } ImGui.sameLine(); if (ImGui.checkbox("Lock Pitch", config.flightLockPitch)) { config.flightLockPitch = !config.flightLockPitch; - config.saveToDefaultFolder(); + config.delayedSaveToDefaultFolder(); } - - // todo: record movement: can we make this smoother? -// if (ImGui.checkbox("Record Movement as Keyframes", ReplayUI.recordCameraMovement)) { -// ReplayUI.recordCameraMovement = !ReplayUI.recordCameraMovement; -// } - } ImGui.end(); } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/PlayerListWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/PlayerListWindow.java index d75fb69..1c53da7 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/PlayerListWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/PlayerListWindow.java @@ -10,6 +10,7 @@ import imgui.ImGui; import imgui.ImGuiViewport; import imgui.flag.ImGuiCond; import imgui.flag.ImGuiWindowFlags; +import imgui.type.ImBoolean; import imgui.type.ImString; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; @@ -25,8 +26,6 @@ import java.util.Locale; public class PlayerListWindow { - private static WindowOpenState wasOpen = WindowOpenState.UNKNOWN; - private static String lastSearch = null; private static long lastUpdate = 0; private static ImString search = ImGuiHelper.createResizableImString(""); @@ -90,20 +89,14 @@ public class PlayerListWindow { } } - public static void render() { - // todo: refactor this if we want to add a lot more windows - if (!Flashback.getConfig().openedWindows.contains("player_list")) { - wasOpen = WindowOpenState.CLOSED; - return; - } - if (wasOpen == WindowOpenState.CLOSED) { + public static void render(ImBoolean open, boolean newlyOpened) { + if (newlyOpened) { ImGuiViewport viewport = ImGui.getMainViewport(); ImGui.setNextWindowPos(viewport.getCenterX(), viewport.getCenterY(), ImGuiCond.Appearing, 0.5f, 0.5f); } - wasOpen = WindowOpenState.OPEN; ImGui.setNextWindowSizeConstraints(250, 50, 5000, 5000); - if (ImGui.begin("Player List###PlayerList", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing)) { + if (ImGui.begin("Player List###PlayerList", open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing)) { ImGui.setNextItemWidth(ImGui.getContentRegionAvailX() - ImGuiHelper.calcTextWidth("Search") - 32); if (ImGui.inputText("Search", search)) { lastSearch = null; 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 8f2b3ab..40c65ad 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 @@ -9,6 +9,7 @@ import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.combo_options.VideoCodec; import com.moulberry.flashback.combo_options.VideoContainer; import com.moulberry.flashback.exporting.ExportJobQueue; +import com.moulberry.flashback.state.EditorScene; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.ImGuiHelper; @@ -158,7 +159,8 @@ public class StartExportWindow { if (ImGuiHelper.inputInt("Start/end tick", startEndTick)) { ReplayServer replayServer = Flashback.getReplayServer(); if (editorState != null && replayServer != null) { - editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks()); + editorState.currentScene().setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks()); + editorState.markDirty(); } } ImGuiHelper.inputFloat("Framerate", framerate); @@ -487,14 +489,15 @@ public class StartExportWindow { open = true; EditorState editorState = EditorStateManager.getCurrent(); + EditorScene editorScene = editorState == null ? null : editorState.currentScene(); - if (editorState != null && editorState.exportStartTicks >= 0) { - startEndTick[0] = editorState.exportStartTicks; + if (editorScene != null && editorScene.exportStartTicks >= 0) { + startEndTick[0] = editorScene.exportStartTicks; } else { startEndTick[0] = 0; } - if (editorState != null && editorState.exportEndTicks >= 0) { - startEndTick[1] = editorState.exportEndTicks; + if (editorScene != null && editorScene.exportEndTicks >= 0) { + startEndTick[1] = editorScene.exportEndTicks; } else { ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer == null) { diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java index 463dc26..29baac2 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 @@ -10,12 +10,12 @@ import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.KeyframeRegistry; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; -import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; import com.moulberry.flashback.record.ReplayMarker; -import com.moulberry.flashback.state.EditorStateHistoryAction; +import com.moulberry.flashback.state.EditorScene; +import com.moulberry.flashback.state.EditorSceneHistoryAction; +import com.moulberry.flashback.state.EditorSceneHistoryEntry; import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; -import com.moulberry.flashback.state.EditorStateHistoryEntry; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.keyframe.Keyframe; @@ -27,12 +27,17 @@ import com.moulberry.flashback.record.FlashbackMeta; import com.moulberry.flashback.state.KeyframeTrack; import imgui.ImDrawList; import imgui.ImGui; +import imgui.ImVec4; +import imgui.flag.ImGuiCol; +import imgui.flag.ImGuiComboFlags; import imgui.flag.ImGuiHoveredFlags; +import imgui.flag.ImGuiInputTextFlags; import imgui.flag.ImGuiMouseButton; import imgui.flag.ImGuiMouseCursor; import imgui.flag.ImGuiPopupFlags; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; +import imgui.type.ImString; import it.unimi.dsi.fastutil.ints.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; @@ -44,6 +49,8 @@ import java.util.*; public class TimelineWindow { + private static EditorState editorState; + private static EditorScene editorScene; private static double zoomMinBeforeDrag = 0.0f; private static double zoomMaxBeforeDrag = 1.0f; private static boolean grabbedZoomBar = false; @@ -58,6 +65,7 @@ public class TimelineWindow { private static int grabbedKeyframeTick = 0; private static int grabbedKeyframeTrack = 0; private static int draggingMouseButton = ImGuiMouseButton.Left; + private static int repositioningKeyframeTrack = 0; private static float dragStartMouseX = 0; private static float dragStartMouseY = 0; @@ -69,6 +77,7 @@ public class TimelineWindow { private static KeyframeType.KeyframeCreatePopup createKeyframeWithPopup = null; private static int createKeyframeWithPopupTick = 0; + private static ImString sceneNameString = null; private static float mouseX; private static float mouseY; @@ -84,6 +93,9 @@ public class TimelineWindow { private static int pendingStepBackwardsTicks = 0; private static int cursorTicks; + private static long lastRenderNanos = 0; + private static long renderDeltaNanos = 0; + private static boolean hoveredControls; private static boolean hoveredSkipBackwards; private static boolean hoveredSlowDown; @@ -141,7 +153,8 @@ public class TimelineWindow { if (timelineVisible) { FlashbackMeta metadata = replayServer.getMetadata(); - EditorState editorState = EditorStateManager.get(metadata.replayIdentifier); + editorState = EditorStateManager.get(metadata.replayIdentifier); + editorScene = editorState.currentScene(); ImDrawList drawList = ImGui.getWindowDrawList(); @@ -160,7 +173,7 @@ public class TimelineWindow { return; } - selectedKeyframesList.removeIf(k -> !k.checkValid(editorState)); + selectedKeyframesList.removeIf(k -> !k.checkValid(editorScene)); if (editingKeyframeTrack >= 0 && editingKeyframeTick >= 0) { for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { @@ -174,6 +187,10 @@ public class TimelineWindow { } } + long currentTime = System.nanoTime(); + renderDeltaNanos = Math.max(0, Math.min(1_000_000_000, currentTime - lastRenderNanos)); + lastRenderNanos = currentTime; + mouseX = ImGui.getMousePosX(); mouseY = ImGui.getMousePosY(); @@ -222,12 +239,12 @@ public class TimelineWindow { cursorTicks = Math.max(0, cursorTicks - pendingStepBackwardsTicks); } - if (grabbedPlayback && !editorState.keyframeTracks.isEmpty()) { + if (grabbedPlayback && !editorScene.keyframeTracks.isEmpty()) { boolean isCtrlDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_CONTROL); boolean isShiftDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT); if (isShiftDown) { - int closestTick = findClosestKeyframeForSnap(editorState, cursorTicks); + int closestTick = findClosestKeyframeForSnap(cursorTicks); if (closestTick != -1) { cursorTicks = closestTick; } @@ -262,14 +279,14 @@ public class TimelineWindow { // Middle divider (y) drawList.addLine(x, y + middleY, x + width, y + middleY, -1); - renderKeyframeElements(replayServer, editorState, x, y + middleY, cursorTicks, middleX); + renderKeyframeElements(x, y + middleY, cursorTicks, middleX); drawList.pushClipRect(x + middleX, y, x + width, y + height); - renderExportBar(editorState, drawList); + renderExportBar(drawList); drawList.pushClipRect(x + middleX, y + middleY, x + width, y + height); - renderKeyframes(editorState, x, y + middleY, mouseX, minTicks, availableTicks, totalTicks); + renderKeyframes(x, y + middleY, mouseX, minTicks, availableTicks, totalTicks); drawList.popClipRect(); renderSeparators(minorsPerMajor, x, middleX, minorSeparatorWidth, errorOffset, width, drawList, y, timestampHeight, middleY, minTicks, ticksPerMinor, showSubSeconds, majorSeparatorHeight, minorSeparatorHeight); @@ -414,7 +431,7 @@ public class TimelineWindow { } if (ImGui.beginPopup("##KeyframePopup")) { - renderKeyframeOptionsPopup(editorState); + renderKeyframeOptionsPopup(); ImGui.endPopup(); } else { editingKeyframeTrack = -1; @@ -443,12 +460,12 @@ public class TimelineWindow { } } - handleKeyPresses(replayServer, cursorTicks, editorState, totalTicks); + handleKeyPresses(replayServer, cursorTicks, totalTicks); boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); if (leftClicked || rightClicked) { - handleClick(editorState, replayServer, totalTicks); + handleClick(replayServer, totalTicks); if (leftClicked) { draggingMouseButton = ImGuiMouseButton.Left; } else { @@ -457,6 +474,38 @@ public class TimelineWindow { dragStartMouseX = mouseX; dragStartMouseY = mouseY; } else if (ImGui.isMouseDragging(draggingMouseButton)) { + if (repositioningKeyframeTrack >= 0 && repositioningKeyframeTrack < editorScene.keyframeTracks.size()) { + float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); + + float mouseDeltaY = mouseY - dragStartMouseY; + if (mouseDeltaY > lineHeight/2) { + if (repositioningKeyframeTrack < editorScene.keyframeTracks.size()-1) { + selectedKeyframesList.clear(); + editingKeyframeTrack = -1; + editingKeyframeTick = -1; + + dragStartMouseY += lineHeight; + + var track = editorScene.keyframeTracks.remove(repositioningKeyframeTrack); + editorScene.keyframeTracks.get(repositioningKeyframeTrack).animatedOffsetInUi += lineHeight; + repositioningKeyframeTrack += 1; + editorScene.keyframeTracks.add(repositioningKeyframeTrack, track); + } + } else if (mouseDeltaY < -lineHeight/2) { + if (repositioningKeyframeTrack > 0) { + selectedKeyframesList.clear(); + editingKeyframeTrack = -1; + editingKeyframeTick = -1; + + dragStartMouseY -= lineHeight; + + var track = editorScene.keyframeTracks.remove(repositioningKeyframeTrack); + repositioningKeyframeTrack -= 1; + editorScene.keyframeTracks.get(repositioningKeyframeTrack).animatedOffsetInUi -= lineHeight; + editorScene.keyframeTracks.add(repositioningKeyframeTrack, track); + } + } + } if (grabbedExportBarResizeLeft) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); @@ -464,13 +513,14 @@ public class TimelineWindow { 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); + int closestTick = findClosestKeyframeForSnap(target); if (closestTick != -1) { target = closestTick; } } - editorState.setExportTicks(target, -1, totalTicks); + editorScene.setExportTicks(target, -1, totalTicks); + editorState.markDirty(); } if (grabbedExportBarResizeRight) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); @@ -478,13 +528,14 @@ public class TimelineWindow { 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); + int closestTick = findClosestKeyframeForSnap(target); if (closestTick != -1) { target = closestTick; } } - editorState.setExportTicks(-1, target, totalTicks); + editorScene.setExportTicks(-1, target, totalTicks); + editorState.markDirty(); } if (zoomBarWidth > 1f && grabbedZoomBar) { float dx = mouseX - dragStartMouseX; @@ -527,18 +578,18 @@ public class TimelineWindow { dragStartMouseX = mouseX; dragStartMouseY = mouseY; } else if (!ImGui.isAnyMouseDown()) { - releaseGrabbed(editorState, replayServer, totalTicks); + releaseGrabbed(replayServer, totalTicks); } } else { - releaseGrabbed(editorState, replayServer, totalTicks); + releaseGrabbed(replayServer, totalTicks); } } ImGui.end(); } - private static int findClosestKeyframeForSnap(EditorState editorState, int tick) { + private static int findClosestKeyframeForSnap(int tick) { int closestTick = -1; - for (KeyframeTrack track : editorState.keyframeTracks) { + for (KeyframeTrack track : editorScene.keyframeTracks) { Integer floor = track.keyframesByTick.floorKey(tick); Integer ceil = track.keyframesByTick.ceilingKey(tick); @@ -557,7 +608,7 @@ public class TimelineWindow { return closestTick; } - private static void handleKeyPresses(ReplayServer replayServer, int cursorTicks, EditorState editorState, int totalTicks) { + private static void handleKeyPresses(ReplayServer replayServer, int cursorTicks, int totalTicks) { boolean pressedIn = ImGui.isKeyPressed(GLFW.GLFW_KEY_I, false); boolean pressedOut = ImGui.isKeyPressed(GLFW.GLFW_KEY_O, false); @@ -568,7 +619,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_P, false)) { - togglePaused(replayServer, editorState); + togglePaused(replayServer); } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT, false)) { pendingStepBackwardsTicks += 1; @@ -583,10 +634,10 @@ public class TimelineWindow { } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_UP, false)) { int nextKeyframeTick; - if (editorState.exportStartTicks >= 0 && editorState.exportStartTicks > cursorTicks) { - nextKeyframeTick = editorState.exportStartTicks; - } else if (editorState.exportEndTicks >= 0 && editorState.exportEndTicks > cursorTicks) { - nextKeyframeTick = editorState.exportEndTicks; + if (editorScene.exportStartTicks >= 0 && editorScene.exportStartTicks > cursorTicks) { + nextKeyframeTick = editorScene.exportStartTicks; + } else if (editorScene.exportEndTicks >= 0 && editorScene.exportEndTicks > cursorTicks) { + nextKeyframeTick = editorScene.exportEndTicks; } else { nextKeyframeTick = totalTicks; } @@ -597,7 +648,7 @@ public class TimelineWindow { nextKeyframeTick = nextMarker; } - for (KeyframeTrack track : editorState.keyframeTracks) { + for (KeyframeTrack track : editorScene.keyframeTracks) { Integer ceilingKey = track.keyframesByTick.ceilingKey(cursorTicks+1); if (ceilingKey != null && ceilingKey < nextKeyframeTick) { nextKeyframeTick = ceilingKey; @@ -608,10 +659,10 @@ public class TimelineWindow { } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_DOWN, false)) { int previousKeyframeTick; - if (editorState.exportEndTicks >= 0 && editorState.exportEndTicks < cursorTicks) { - previousKeyframeTick = editorState.exportEndTicks; - } else if (editorState.exportStartTicks >= 0 && editorState.exportStartTicks < cursorTicks) { - previousKeyframeTick = editorState.exportStartTicks; + if (editorScene.exportEndTicks >= 0 && editorScene.exportEndTicks < cursorTicks) { + previousKeyframeTick = editorScene.exportEndTicks; + } else if (editorScene.exportStartTicks >= 0 && editorScene.exportStartTicks < cursorTicks) { + previousKeyframeTick = editorScene.exportStartTicks; } else { previousKeyframeTick = 0; } @@ -622,7 +673,7 @@ public class TimelineWindow { previousKeyframeTick = lastMarker; } - for (KeyframeTrack track : editorState.keyframeTracks) { + for (KeyframeTrack track : editorScene.keyframeTracks) { Integer floorKey = track.keyframesByTick.floorKey(cursorTicks-1); if (floorKey != null && floorKey > previousKeyframeTick) { previousKeyframeTick = floorKey; @@ -632,10 +683,12 @@ public class TimelineWindow { replayServer.forceApplyKeyframes.set(true); } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_Z, false) && (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_CONTROL))) { - editorState.undo(ReplayUI::setInfoOverlayShort); + editorScene.undo(ReplayUI::setInfoOverlayShort); + editorState.markDirty(); } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_Y, false) && (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_CONTROL))) { - editorState.redo(ReplayUI::setInfoOverlayShort); + editorScene.redo(ReplayUI::setInfoOverlayShort); + editorState.markDirty(); } if (pressedIn || pressedOut) { @@ -647,11 +700,12 @@ public class TimelineWindow { if (pressedOut) { end = cursorTicks; } - editorState.setExportTicks(start, end, totalTicks); + editorScene.setExportTicks(start, end, totalTicks); + editorState.markDirty(); } if (pressedDelete && !selectedKeyframesList.isEmpty()) { - removeAllSelectedKeyframes(editorState); + removeAllSelectedKeyframes(); } if (pressedCopy && !selectedKeyframesList.isEmpty()) { @@ -668,7 +722,7 @@ public class TimelineWindow { } for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(selectedKeyframes.trackIndex()); TreeMap keyframes = new TreeMap<>(); for (int tick : selectedKeyframes.keyframeTicks()) { @@ -696,37 +750,41 @@ public class TimelineWindow { int count = 0; for (SavedTrack savedTrack : tracks) { - count += savedTrack.applyToEditorState(editorState, cursorTicks, totalTicks); + count += savedTrack.applyToScene(editorScene, cursorTicks, totalTicks); } - ReplayUI.setInfoOverlay("Pasted " + count + " keyframe(s) from clipboard"); + if (count > 0) { + ReplayUI.setInfoOverlay("Pasted " + count + " keyframe(s) from clipboard"); + editorState.markDirty(); + } } } catch (Exception ignored) {} } } - private static void removeAllSelectedKeyframes(EditorState editorState) { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + private static void removeAllSelectedKeyframes() { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + KeyframeTrack track = editorScene.keyframeTracks.get(selectedKeyframes.trackIndex()); for (int tick : selectedKeyframes.keyframeTicks()) { Keyframe keyframe = track.keyframesByTick.get(tick); - undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); - redo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick)); + undo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + redo.add(new EditorSceneHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick)); } } selectedKeyframesList.clear(); editingKeyframeTrack = -1; editingKeyframeTick = -1; - editorState.push(new EditorStateHistoryEntry(undo, redo, "Deleted " + undo.size() + " keyframe(s)")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Deleted " + undo.size() + " keyframe(s)")); + editorState.markDirty(); } - private static void handleClick(EditorState editorState, ReplayServer replayServer, int totalTicks) { - releaseGrabbed(editorState, replayServer, totalTicks); + private static void handleClick(ReplayServer replayServer, int totalTicks) { + releaseGrabbed(replayServer, totalTicks); List oldSelectedKeyframesList = new ArrayList<>(selectedKeyframesList); selectedKeyframesList.clear(); @@ -765,7 +823,7 @@ public class TimelineWindow { // Pause button if (hoveredPause) { - togglePaused(replayServer, editorState); + togglePaused(replayServer); return; } @@ -802,9 +860,9 @@ public class TimelineWindow { // Timeline if (mouseY > y && mouseY < y + middleY && mouseX > x + middleX && mouseX < x + width) { - if (editorState.exportStartTicks >= 0 && editorState.exportEndTicks >= 0 && mouseY > y + timestampHeight) { - int exportStartX = replayTickToTimelineX(editorState.exportStartTicks); - int exportEndX = replayTickToTimelineX(editorState.exportEndTicks); + if (editorScene.exportStartTicks >= 0 && editorScene.exportEndTicks >= 0 && mouseY > y + timestampHeight) { + int exportStartX = replayTickToTimelineX(editorScene.exportStartTicks); + int exportEndX = replayTickToTimelineX(editorScene.exportEndTicks); Utils.ClosestElement closestElement = Utils.findClosest(mouseX, exportStartX, exportEndX, 5); @@ -859,8 +917,8 @@ public class TimelineWindow { int trackIndex = (int) Math.max(0, Math.floor((mouseY - (y + middleY + 2))/lineHeight)); - if (trackIndex >= 0 && trackIndex < editorState.keyframeTracks.size()) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + if (trackIndex >= 0 && trackIndex < editorScene.keyframeTracks.size()) { + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(trackIndex); int tick = timelineXToReplayTick(mouseX - x); @@ -919,7 +977,7 @@ public class TimelineWindow { } } - private static void togglePaused(ReplayServer replayServer, EditorState editorState) { + private static void togglePaused(ReplayServer replayServer) { if (replayServer.getReplayTick() >= replayServer.getTotalReplayTicks()) { replayServer.jumpToTick = 0; } @@ -929,25 +987,13 @@ public class TimelineWindow { if (screen != null && screen.isPauseScreen()) { Minecraft.getInstance().setScreen(null); } - - if (ReplayUI.recordCameraMovement) { - editorState.recordingCameraMovementTrack = -1; - - for (int i = 0; i < editorState.keyframeTracks.size(); i++) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i); - if (keyframeTrack.enabled && keyframeTrack.keyframeType == CameraKeyframeType.INSTANCE) { - editorState.recordingCameraMovementTrack = i; - break; - } - } - } } } - private static void renderExportBar(EditorState editorState, ImDrawList drawList) { - if (editorState.exportStartTicks >= 0 && editorState.exportEndTicks >= 0) { - int exportStartX = replayTickToTimelineX(editorState.exportStartTicks); - int exportEndX = replayTickToTimelineX(editorState.exportEndTicks); + private static void renderExportBar(ImDrawList drawList) { + if (editorScene.exportStartTicks >= 0 && editorScene.exportEndTicks >= 0) { + int exportStartX = replayTickToTimelineX(editorScene.exportStartTicks); + int exportEndX = replayTickToTimelineX(editorScene.exportEndTicks); drawList.addRectFilled(x +exportStartX, y + timestampHeight, x +exportEndX, y + middleY, 0x60FFAA00); drawList.addLine(x +exportStartX, y + timestampHeight, x +exportStartX, y + middleY, 0xFFFFAA00, 4); drawList.addLine(x +exportEndX, y + timestampHeight, x +exportEndX, y + middleY, 0xFFFFAA00, 4); @@ -960,12 +1006,12 @@ public class TimelineWindow { } } - private static void renderKeyframeOptionsPopup(EditorState editorState) { + private static void renderKeyframeOptionsPopup() { if (editingKeyframeTrack < 0 || editingKeyframeTick < 0) { return; } - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(editingKeyframeTrack); + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(editingKeyframeTrack); Keyframe editingKeyframe = keyframeTrack.keyframesByTick.get(editingKeyframeTick); if (editingKeyframe == null || selectedKeyframesList.isEmpty()) { @@ -975,27 +1021,28 @@ public class TimelineWindow { } editingKeyframe.renderEditKeyframe(updateFunction -> { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); int modified = 0; for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + KeyframeTrack track = editorScene.keyframeTracks.get(selectedKeyframes.trackIndex()); for (int tick : selectedKeyframes.keyframeTicks()) { Keyframe keyframe = track.keyframesByTick.get(tick); if (keyframe.getClass() == editingKeyframe.getClass()) { modified += 1; - undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + undo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); updateFunction.accept(keyframe); - redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + redo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); } } } if (modified > 0) { - editorState.push(new EditorStateHistoryEntry(undo, redo, "Modified " + modified + " keyframe(s)")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Modified " + modified + " keyframe(s)")); + editorState.markDirty(); } }); @@ -1005,11 +1052,11 @@ public class TimelineWindow { if (ImGuiHelper.combo("Type", type, InterpolationType.NAMES)) { InterpolationType interpolationType = InterpolationType.INTERPOLATION_TYPES[type[0]]; - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + KeyframeTrack track = editorScene.keyframeTracks.get(selectedKeyframes.trackIndex()); for (int tick : selectedKeyframes.keyframeTicks()) { Keyframe keyframe = track.keyframesByTick.get(tick); @@ -1017,13 +1064,14 @@ public class TimelineWindow { Keyframe changed = keyframe.copy(); changed.interpolationType(interpolationType); - undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); - redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, changed)); + undo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + redo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, changed)); } } } - editorState.push(new EditorStateHistoryEntry(undo, redo, "Changed interpolation type to " + interpolationType)); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Changed interpolation type to " + interpolationType)); + editorState.markDirty(); } } if (editingKeyframe.keyframeType().allowChangingTimelineTick()) { @@ -1034,20 +1082,21 @@ public class TimelineWindow { if (ImGui.isItemDeactivatedAfterEdit() && newEditingKeyframeTick != editingKeyframeTick) { for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + KeyframeTrack track = editorScene.keyframeTracks.get(selectedKeyframes.trackIndex()); Keyframe possibleKeyframe = track.keyframesByTick.get(editingKeyframeTick); if (possibleKeyframe == editingKeyframe) { - List undo = List.of( - new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), newEditingKeyframeTick), - new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), editingKeyframeTick, editingKeyframe.copy()) + List undo = List.of( + new EditorSceneHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), newEditingKeyframeTick), + new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), editingKeyframeTick, editingKeyframe.copy()) ); - List redo = List.of( - new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), editingKeyframeTick), - new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), newEditingKeyframeTick, editingKeyframe.copy()) + List redo = List.of( + new EditorSceneHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), editingKeyframeTick), + new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), newEditingKeyframeTick, editingKeyframe.copy()) ); - editorState.push(new EditorStateHistoryEntry(undo, redo, "Moved 1 keyframe(s)")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Moved 1 keyframe(s)")); + editorState.markDirty(); selectedKeyframes.keyframeTicks().remove(editingKeyframeTick); selectedKeyframes.keyframeTicks().add(newEditingKeyframeTick); editingKeyframeTick = newEditingKeyframeTick; @@ -1061,7 +1110,7 @@ public class TimelineWindow { if (ImGui.button(multiple ? "Remove All" : "Remove")) { ImGui.closeCurrentPopup(); - removeAllSelectedKeyframes(editorState); + removeAllSelectedKeyframes(); } if (!multiple && editingKeyframe instanceof CameraKeyframe cameraKeyframe) { @@ -1072,14 +1121,16 @@ public class TimelineWindow { } } - private static void releaseGrabbed(EditorState editorState, ReplayServer replayServer, int totalTicks) { + private static void releaseGrabbed(ReplayServer replayServer, int totalTicks) { grabbedZoomBar = false; grabbedZoomBarResizeLeft = false; grabbedZoomBarResizeRight = false; grabbedExportBarResizeLeft = false; grabbedExportBarResizeRight = false; + if (!ImGui.isAnyMouseDown()) { trackDisabledButtonDrag = false; + repositioningKeyframeTrack = -1; } if (dragSelectOrigin != null) { @@ -1092,10 +1143,10 @@ public class TimelineWindow { int minTrackIndex = (int) Math.floor((dragMinY - (y + middleY + 2))/lineHeight); int maxTrackIndex = (int) Math.floor((dragMaxY - (y + middleY + 2))/lineHeight); minTrackIndex = Math.max(0, minTrackIndex); - maxTrackIndex = Math.min(editorState.keyframeTracks.size()-1, maxTrackIndex); + maxTrackIndex = Math.min(editorScene.keyframeTracks.size()-1, maxTrackIndex); for (int trackIndex = minTrackIndex; trackIndex <= maxTrackIndex; trackIndex++) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(trackIndex); int minTick = timelineXToReplayTick(dragMinX - KEYFRAME_SIZE); int maxTick = timelineXToReplayTick(dragMaxX + KEYFRAME_SIZE); @@ -1127,16 +1178,16 @@ public class TimelineWindow { } if (grabbedKeyframe) { - GrabMovementInfo grabMovementInfo = calculateGrabMovementInfo(editorState, totalTicks); + GrabMovementInfo grabMovementInfo = calculateGrabMovementInfo(totalTicks); if (grabMovementInfo.grabbedScalePivotTick >= 0 || grabMovementInfo.grabbedDelta != 0) { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); int movedKeyframes = 0; for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { int trackIndex = selectedKeyframes.trackIndex(); - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(trackIndex); IntList selectedTicks = new IntArrayList(selectedKeyframes.keyframeTicks()); @@ -1185,27 +1236,28 @@ public class TimelineWindow { for (int removeTick : removeFromTick.keySet()) { if (!addToTick.containsKey(removeTick)) { - redo.add(new EditorStateHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, removeTick)); + redo.add(new EditorSceneHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, removeTick)); } } for (Int2ObjectMap.Entry entry : addToTick.int2ObjectEntrySet()) { - redo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), entry.getValue())); + redo.add(new EditorSceneHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), entry.getValue())); if (!removeFromTick.containsKey(entry.getIntKey())) { Keyframe existing = keyframeTrack.keyframesByTick.get(entry.getIntKey()); if (existing != null) { - undo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), existing.copy())); + undo.add(new EditorSceneHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), existing.copy())); } else { - undo.add(new EditorStateHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey())); + undo.add(new EditorSceneHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey())); } } } for (Int2ObjectMap.Entry entry : removeFromTick.int2ObjectEntrySet()) { - undo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), entry.getValue())); + undo.add(new EditorSceneHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), entry.getValue())); } } - editorState.push(new EditorStateHistoryEntry(undo, redo, "Moved " + movedKeyframes + " keyframe(s)")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Moved " + movedKeyframes + " keyframe(s)")); + editorState.markDirty(); } grabbedKeyframe = false; @@ -1220,7 +1272,7 @@ public class TimelineWindow { record GrabMovementInfo(int grabbedDelta, int grabbedScalePivotTick, float grabbedScaleFactor) {} - private static GrabMovementInfo calculateGrabMovementInfo(EditorState editorState, int totalTicks) { + private static GrabMovementInfo calculateGrabMovementInfo(int totalTicks) { int grabbedDelta = 0; int grabbedScalePivotTick = -1; float grabbedScaleFactor = 0f; @@ -1266,12 +1318,12 @@ public class TimelineWindow { if (isShiftDown) { int closestTick = -1; - for (int i = 0; i < editorState.keyframeTracks.size(); i++) { + for (int i = 0; i < editorScene.keyframeTracks.size(); i++) { if (i == grabbedKeyframeTrack) { continue; } - KeyframeTrack track = editorState.keyframeTracks.get(i); + KeyframeTrack track = editorScene.keyframeTracks.get(i); Integer floor = track.keyframesByTick.floorKey(grabbedKeyframeTick); Integer ceil = track.keyframesByTick.ceilingKey(grabbedKeyframeTick); @@ -1301,7 +1353,7 @@ public class TimelineWindow { tooltip += " (" + grabbedDelta + " ticks)"; } - if (!isShiftDown && editorState.keyframeTracks.size() > 1) { + if (!isShiftDown && editorScene.keyframeTracks.size() > 1) { tooltip += "\nHold SHIFT to snap"; } @@ -1311,18 +1363,18 @@ public class TimelineWindow { return new GrabMovementInfo(grabbedDelta, grabbedScalePivotTick, grabbedScaleFactor); } - private static void renderKeyframes(EditorState editorState, float x, float y, float mouseX, int minTicks, float availableTicks, int totalTicks) { + private static void renderKeyframes(float x, float y, float mouseX, int minTicks, float availableTicks, int totalTicks) { float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); ImDrawList drawList = ImGui.getWindowDrawList(); GrabMovementInfo grabMovementInfo = null; if (grabbedKeyframe) { - grabMovementInfo = calculateGrabMovementInfo(editorState, totalTicks); + grabMovementInfo = calculateGrabMovementInfo(totalTicks); } - for (int trackIndex = 0; trackIndex < editorState.keyframeTracks.size(); trackIndex++) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + for (int trackIndex = 0; trackIndex < editorScene.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(trackIndex); TreeMap keyframeTimes = keyframeTrack.keyframesByTick; @@ -1334,13 +1386,6 @@ public class TimelineWindow { } } - if (editorState.recordingCameraMovementTrack == trackIndex && editorState.recordingCameraMovementMinTick >= 0 && editorState.recordingCameraMovementMaxTick >= 0) { - float fromX = x + replayTickToTimelineX(editorState.recordingCameraMovementMinTick); - float toX = x + replayTickToTimelineX(editorState.recordingCameraMovementMaxTick); - float topY = y + 2 + trackIndex * lineHeight; - drawList.addRectFilled(fromX, topY, toX, topY + lineHeight, 0xFF4040FF); - } - for (int tick = minTicks - 10; tick <= minTicks + availableTicks + 10; tick++) { var entry = keyframeTimes.ceilingEntry(tick); if (entry == null || entry.getKey() > minTicks + availableTicks + 10) { @@ -1499,7 +1544,7 @@ public class TimelineWindow { } } - private static void renderKeyframeElements(ReplayServer replayServer, EditorState editorState, float x, float y, int cursorTicks, int middleX) { + private static void renderKeyframeElements(float x, float y, int cursorTicks, int middleX) { ImGui.setCursorScreenPos(x + 8, y + 6); int keyframeTrackToClear = -1; @@ -1511,8 +1556,10 @@ public class TimelineWindow { boolean hasOpenPopup = false; - for (int trackIndex = 0; trackIndex < editorState.keyframeTracks.size(); trackIndex++) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + double animationMultiplier = Math.pow(0.9D, renderDeltaNanos / 10_000_000D); + + for (int trackIndex = 0; trackIndex < editorScene.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(trackIndex); KeyframeType keyframeType = keyframeTrack.keyframeType; ImGui.pushID(trackIndex); @@ -1527,18 +1574,81 @@ public class TimelineWindow { ImGui.closeCurrentPopup(); ImGui.endPopup(); - createNewKeyframe(editorState, trackIndex, createKeyframeAtTick, keyframeType, keyframeTrack); + createNewKeyframe(trackIndex, createKeyframeAtTick, keyframeType, keyframeTrack); } else { ImGui.endPopup(); } } - ImGui.setCursorPosX(8); + String icon = keyframeType.icon(); + String name = keyframeTrack.customName; + if (name == null) { + name = keyframeType.name(); + } + String nameWithIcon = name; + if (icon != null) { + nameWithIcon = icon + " " + name; + } - if (keyframeTrack.enabled) { - ImGui.text(keyframeType.name()); + keyframeTrack.animatedOffsetInUi *= animationMultiplier; + if (Math.abs(keyframeTrack.animatedOffsetInUi) < 1) { + keyframeTrack.animatedOffsetInUi = 0; + } + + float trackOffset = repositioningKeyframeTrack == trackIndex ? mouseY - dragStartMouseY : (int) keyframeTrack.animatedOffsetInUi; + ImGui.setCursorPosX(repositioningKeyframeTrack == trackIndex ? 3 : 2); + ImGui.setCursorPosY(ImGui.getCursorPosY() + trackOffset); + + ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, 0, 0); + if (repositioningKeyframeTrack == trackIndex) { + ImGui.text("\ue945"); } else { - ImGui.textDisabled(keyframeType.name()); + ImGui.textDisabled("\ue945"); + if (ImGui.isItemClicked(ImGuiMouseButton.Left)) { + repositioningKeyframeTrack = trackIndex; + } + } + ImGui.sameLine(); + ImGui.popStyleVar(); + + if (keyframeTrack.nameEditField != null) { + ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, 0, 0); + ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 0, 0); + if (icon != null) { + ImGui.text(icon + " "); + ImGui.sameLine(); + } + ImGui.setNextItemWidth(120); + if (keyframeTrack.forceFocusTrack) { + keyframeTrack.forceFocusTrack = false; + ImGui.setKeyboardFocusHere(); + } + boolean returnValue = ImGui.inputText("##TrackName", keyframeTrack.nameEditField, ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll); + if (returnValue || ImGui.isItemDeactivated()) { + keyframeTrack.customName = ImGuiHelper.getString(keyframeTrack.nameEditField).trim(); + if (keyframeTrack.customName.isEmpty() || keyframeTrack.customName.equals(keyframeType.name())) { + keyframeTrack.customName = null; + } + keyframeTrack.nameEditField = null; + } + ImGui.popStyleVar(2); + } else { + if (keyframeTrack.enabled) { + if (keyframeTrack.customColour != 0) { + ImGui.textColored(keyframeTrack.customColour, nameWithIcon); + } else { + ImGui.text(nameWithIcon); + } + } else { + ImGui.textDisabled(nameWithIcon); + } + if (ImGui.isItemClicked(ImGuiMouseButton.Left) && ImGui.isMouseDoubleClicked(ImGuiMouseButton.Left)) { + keyframeTrack.nameEditField = ImGuiHelper.createResizableImString(name); + keyframeTrack.forceFocusTrack = true; + } + if (ImGui.isItemClicked(ImGuiMouseButton.Right)) { + ImGui.openPopup("##TrackPopup"); + } } ImGui.sameLine(); @@ -1546,42 +1656,17 @@ public class TimelineWindow { float buttonX = x + middleX - (buttonSize + spacingX) * 3; float buttonY = ImGui.getCursorScreenPosY(); ImGui.setCursorPosX(buttonX - x); - if (ImGui.button("##Add", buttonSize, buttonSize)) { - createNewKeyframe(editorState, trackIndex, cursorTicks, keyframeType, keyframeTrack); - } - drawList.addRectFilled(buttonX + 2, buttonY + buttonSize/2 - 1, buttonX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); - drawList.addRectFilled(buttonX + buttonSize/2 - 1, buttonY + 2, buttonX + buttonSize/2 + 1, buttonY + buttonSize - 2, -1); - ImGuiHelper.tooltip("Add keyframe"); - - if (ImGui.beginPopup("##CreateKeyframe")) { - if (createKeyframeWithPopup != null) { - hasOpenPopup = true; - Keyframe keyframe = createKeyframeWithPopup.render(); - if (keyframe != null) { - editorState.setKeyframe(trackIndex, createKeyframeWithPopupTick, keyframe); - ImGui.closeCurrentPopup(); - } - } else { - ImGui.closeCurrentPopup(); - } - ImGui.endPopup(); + if (ImGui.invisibleButton("##TrackOptions", buttonSize, buttonSize) || ImGui.isItemClicked(ImGuiMouseButton.Right)) { + ImGui.openPopup("##TrackPopup"); } + drawList.addText(buttonX - 2, buttonY, -1, "\ue5d2"); + ImGuiHelper.tooltip("Open track options"); ImGui.sameLine(); buttonX += buttonSize + spacingX; ImGui.setCursorPosX(buttonX - x); - if (ImGui.button("##Clear", buttonSize, buttonSize)) { - keyframeTrackToClear = trackIndex; - } - drawList.addRectFilled(buttonX + 2, buttonY + buttonSize/2 - 1, buttonX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); - ImGuiHelper.tooltip("Remove all keyframes"); - - ImGui.sameLine(); - - buttonX += buttonSize + spacingX; - ImGui.setCursorPosX(buttonX - x); - ImGui.button("##ToggleEnabled", buttonSize, buttonSize); + ImGui.invisibleButton("##ToggleEnabled", buttonSize, buttonSize); if (ImGui.isItemHovered(trackDisabledButtonDrag ? ImGuiHoveredFlags.AllowWhenBlockedByActiveItem : 0)) { if (trackDisabledButtonDrag) { keyframeTrack.enabled = trackDisabledButtonDragValue; @@ -1592,12 +1677,76 @@ public class TimelineWindow { } } if (keyframeTrack.enabled) { - drawList.addCircleFilled(buttonX + buttonSize/2, buttonY + buttonSize/2, buttonSize/3, -1); + drawList.addText(buttonX - 2, buttonY, -1, "\ue8f4"); ImGuiHelper.tooltip("Disable keyframe track"); } else { - drawList.addCircle(buttonX + buttonSize/2, buttonY + buttonSize/2, buttonSize/3, -1, 16, 2); + drawList.addText(buttonX - 2, buttonY, -1, "\ue8f5"); ImGuiHelper.tooltip("Enable keyframe track"); } + ImGui.sameLine(); + + buttonX += buttonSize + spacingX; + ImGui.setCursorPosX(buttonX - x); + if (ImGui.invisibleButton("##Add", buttonSize, buttonSize)) { + createNewKeyframe(trackIndex, cursorTicks, keyframeType, keyframeTrack); + } + drawList.addText(buttonX - 2, buttonY, -1, "\ue148"); + ImGuiHelper.tooltip("Add keyframe"); + + if (ImGui.beginPopup("##CreateKeyframe")) { + if (createKeyframeWithPopup != null) { + hasOpenPopup = true; + Keyframe keyframe = createKeyframeWithPopup.render(); + if (keyframe != null) { + editorScene.setKeyframe(trackIndex, createKeyframeWithPopupTick, keyframe); + editorState.markDirty(); + ImGui.closeCurrentPopup(); + } + } else { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + + boolean openTrackColourPopup = false; + + if (ImGui.beginPopup("##TrackPopup")) { + if (ImGui.menuItem("\ue3c9 Rename")) { + keyframeTrack.nameEditField = ImGuiHelper.createResizableImString(name); + keyframeTrack.forceFocusTrack = true; + } + if (ImGui.menuItem("\ue40a Set Colour")) { + openTrackColourPopup = true; + } + if (ImGui.menuItem("\ue872 Delete track")) { + keyframeTrackToClear = trackIndex; + } + ImGui.endPopup(); + } + + if (openTrackColourPopup) { + ImGui.openPopup("##SetTrackColour"); + } + if (ImGui.beginPopup("##SetTrackColour")) { + if (ImGui.button("Reset to Default")) { + keyframeTrack.customColour = 0; + ImGui.closeCurrentPopup(); + } else { + int colour = keyframeTrack.customColour; + if (colour == 0) { + colour = ImGui.getColorU32(ImGuiCol.Text); + } + ImVec4 imVec4 = new ImVec4(); + ImGui.colorConvertU32ToFloat4(colour, imVec4); + float[] colourArray = new float[]{imVec4.x, imVec4.y, imVec4.z}; + if (ImGui.colorPicker3("Track Colour", colourArray)) { + keyframeTrack.customColour = ImGui.colorConvertFloat4ToU32(colourArray[0], colourArray[1], colourArray[2], 1.0f); + } + } + ImGui.endPopup(); + } + + ImGui.setCursorPosY(ImGui.getCursorPosY() - trackOffset); ImGui.separator(); @@ -1611,19 +1760,20 @@ public class TimelineWindow { openCreateKeyframeAtTickTrack = -1; if (keyframeTrackToClear >= 0) { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(keyframeTrackToClear); + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(keyframeTrackToClear); - undo.add(new EditorStateHistoryAction.AddTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); + undo.add(new EditorSceneHistoryAction.AddTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); for (Map.Entry entry : keyframeTrack.keyframesByTick.entrySet()) { - undo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, keyframeTrackToClear, entry.getKey(), entry.getValue().copy())); + undo.add(new EditorSceneHistoryAction.SetKeyframe(keyframeTrack.keyframeType, keyframeTrackToClear, entry.getKey(), entry.getValue().copy())); } - redo.add(new EditorStateHistoryAction.RemoveTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); + redo.add(new EditorSceneHistoryAction.RemoveTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); - editorState.push(new EditorStateHistoryEntry(undo, redo, "Delete " + keyframeTrack.keyframeType.name() + " track")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Delete " + keyframeTrack.keyframeType.name() + " track")); + editorState.markDirty(); selectedKeyframesList.clear(); } @@ -1631,17 +1781,130 @@ public class TimelineWindow { if (ImGui.smallButton("Add Element")) { ImGui.openPopup("##AddKeyframeElement"); } + + ImGui.sameLine(); + + boolean openNewScenePopup = false; + boolean openRenameScenePopup = false; + boolean openDeleteScenePopup = false; + + ImGui.setNextItemWidth(middleX - ImGui.getCursorPosX() - spacingX); + ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 4, 0); + if (ImGui.beginCombo("##SceneSwitcher", editorScene.name, ImGuiComboFlags.HeightLargest)) { + if (ImGui.menuItem("\ue148 New Scene")) { + openNewScenePopup = true; + } + if (ImGui.menuItem("\ue3c9 Rename")) { + openRenameScenePopup = true; + } + if (editorState.scenes.size() > 1 && editorScene.keyframeTracks.isEmpty() && ImGui.menuItem("\ue92b Delete Forever")) { + openDeleteScenePopup = true; + } + + ImGui.separator(); + + for (int i = 0; i < editorState.scenes.size(); i++) { + EditorScene otherScene = editorState.scenes.get(i); + + ImGui.pushID(i); + boolean selected = i == editorState.sceneIndex; + if (ImGui.selectable(otherScene.name, selected) && !selected) { + editorState.sceneIndex = i; + } + if (selected) ImGui.setItemDefaultFocus(); + ImGui.popID(); + } + + ImGui.endCombo(); + } + ImGui.popStyleVar(); + + if (openNewScenePopup) { + ImGui.openPopup("##NewScene"); + sceneNameString = ImGuiHelper.createResizableImString("Scene " + (editorState.scenes.size() + 1)); + } + if (ImGui.beginPopup("##NewScene")) { + ImGui.inputText("Name", sceneNameString); + + if (ImGui.button("Create")) { + String sceneName = ImGuiHelper.getString(sceneNameString).trim(); + if (!sceneName.isEmpty()) { + editorState.scenes.add(new EditorScene(sceneName)); + editorState.sceneIndex = editorState.scenes.size() - 1; + editorState.markDirty(); + ImGui.closeCurrentPopup(); + } + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + + ImGui.endPopup(); + } + + if (openRenameScenePopup) { + ImGui.openPopup("##RenameScene"); + sceneNameString = ImGuiHelper.createResizableImString(editorScene.name); + } + if (ImGui.beginPopup("##RenameScene")) { + ImGui.inputText("Name", sceneNameString); + + if (ImGui.button("Rename")) { + String sceneName = ImGuiHelper.getString(sceneNameString).trim(); + if (!sceneName.isEmpty()) { + editorScene.name = sceneName; + editorState.markDirty(); + ImGui.closeCurrentPopup(); + } + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + + ImGui.endPopup(); + } + + if (openDeleteScenePopup) { + ImGui.openPopup("##DeleteScene"); + } + if (ImGui.beginPopup("##DeleteScene")) { + if (editorState.scenes.size() > 1 && editorScene.keyframeTracks.isEmpty()) { + ImGui.text("Are you sure you want to delete this scene?"); + ImGui.text("This action is PERMANENT"); + ImGui.text("You will not be able to undo this action"); + + if (ImGui.button("Delete Forever")) { + editorState.scenes.remove(editorState.sceneIndex); + if (editorState.sceneIndex >= editorState.scenes.size()) { + editorState.sceneIndex = editorState.scenes.size() - 1; + } + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + } else { + ImGui.closeCurrentPopup(); + } + + ImGui.endPopup(); + } + if (ImGui.beginPopup("##AddKeyframeElement")) { for (KeyframeType type : KeyframeRegistry.getTypes()) { if (ImGui.selectable(type.name())) { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); - int index = editorState.keyframeTracks.size(); - undo.add(new EditorStateHistoryAction.RemoveTrack(type, index)); - redo.add(new EditorStateHistoryAction.AddTrack(type, index)); + int index = editorScene.keyframeTracks.size(); + undo.add(new EditorSceneHistoryAction.RemoveTrack(type, index)); + redo.add(new EditorSceneHistoryAction.AddTrack(type, index)); - editorState.push(new EditorStateHistoryEntry(undo, redo, "Create " + type.name() + " track")); + editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Create " + type.name() + " track")); + editorState.markDirty(); ImGui.closeCurrentPopup(); } } @@ -1649,13 +1912,15 @@ public class TimelineWindow { } } - private static void createNewKeyframe(EditorState editorState, int trackIndex, int tick, KeyframeType keyframeType, KeyframeTrack keyframeTrack) { + private static void createNewKeyframe(int trackIndex, int tick, KeyframeType keyframeType, KeyframeTrack keyframeTrack) { Keyframe keyframe = keyframeType.createDirect(); if (keyframe != null) { - editorState.setKeyframe(trackIndex, tick, keyframe); + editorScene.setKeyframe(trackIndex, tick, keyframe); + editorState.markDirty(); } else { if (keyframeType == TimelapseKeyframeType.INSTANCE && keyframeTrack.keyframesByTick.isEmpty()) { - editorState.setKeyframe(trackIndex, tick, new TimelapseKeyframe(0)); + editorScene.setKeyframe(trackIndex, tick, new TimelapseKeyframe(0)); + editorState.markDirty(); } else { createKeyframeWithPopup = keyframeType.createPopup(); if (createKeyframeWithPopup != null) { 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 f1781ff..14852cb 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 @@ -6,21 +6,19 @@ import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; import com.moulberry.flashback.keyframe.impl.FOVKeyframe; import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; -import com.moulberry.flashback.keyframe.types.FOVKeyframeType; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.record.FlashbackMeta; +import com.moulberry.flashback.state.EditorScene; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateHistoryAction; -import com.moulberry.flashback.state.EditorStateHistoryEntry; +import com.moulberry.flashback.state.EditorSceneHistoryAction; +import com.moulberry.flashback.state.EditorSceneHistoryEntry; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.KeyframeTrack; import com.moulberry.flashback.visuals.ReplayVisuals; import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.editor.ui.ImGuiHelper; import imgui.ImGui; -import imgui.flag.ImGuiColorEditFlags; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.FogRenderer; import java.util.List; @@ -324,34 +322,36 @@ public class VisualsWindow { private static void addKeyframe(EditorState editorState, ReplayServer replayServer, Keyframe keyframe) { KeyframeType keyframeType = keyframe.keyframeType(); + EditorScene scene = editorState.currentScene(); // Try add to existing enabled keyframe track - for (int i = 0; i < editorState.keyframeTracks.size(); i++) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i); + for (int i = 0; i < scene.keyframeTracks.size(); i++) { + KeyframeTrack keyframeTrack = scene.keyframeTracks.get(i); if (keyframeTrack.enabled && keyframeTrack.keyframeType == keyframeType) { - editorState.setKeyframe(i, replayServer.getReplayTick(), keyframe); + scene.setKeyframe(i, replayServer.getReplayTick(), keyframe); return; } } // Try add to any keyframe track - for (int i = 0; i < editorState.keyframeTracks.size(); i++) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i); + for (int i = 0; i < scene.keyframeTracks.size(); i++) { + KeyframeTrack keyframeTrack = scene.keyframeTracks.get(i); if (keyframeTrack.keyframeType == keyframeType) { - editorState.setKeyframe(i, replayServer.getReplayTick(), keyframe); + scene.setKeyframe(i, replayServer.getReplayTick(), keyframe); return; } } String description = "Added " + keyframeType.name() + " keyframe"; - int newKeyframeTrackIndex = editorState.keyframeTracks.size(); - editorState.push(new EditorStateHistoryEntry( - List.of(new EditorStateHistoryAction.RemoveTrack(keyframeType, newKeyframeTrackIndex)), + int newKeyframeTrackIndex = scene.keyframeTracks.size(); + scene.push(new EditorSceneHistoryEntry( + List.of(new EditorSceneHistoryAction.RemoveTrack(keyframeType, newKeyframeTrackIndex)), List.of( - new EditorStateHistoryAction.AddTrack(keyframeType, newKeyframeTrackIndex), - new EditorStateHistoryAction.SetKeyframe(keyframeType, newKeyframeTrackIndex, replayServer.getReplayTick(), keyframe) + new EditorSceneHistoryAction.AddTrack(keyframeType, newKeyframeTrackIndex), + new EditorSceneHistoryAction.SetKeyframe(keyframeType, newKeyframeTrackIndex, replayServer.getReplayTick(), keyframe) ), description )); + editorState.markDirty(); } } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/WindowType.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/WindowType.java new file mode 100644 index 0000000..a86dddd --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/WindowType.java @@ -0,0 +1,48 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.editor.ui.WindowOpenState; +import imgui.type.ImBoolean; + +import java.util.Set; + +public enum WindowType { + + PLAYER_LIST("player_list", PlayerListWindow::render), + MOVEMENT("movement", MovementWindow::render); + + private final String windowId; + private final ImGuiWindowRenderer renderMethod; + private final ImBoolean open = new ImBoolean(); + private WindowOpenState openState = WindowOpenState.UNKNOWN; + + WindowType(String windowId, ImGuiWindowRenderer renderMethod) { + this.windowId = windowId; + this.renderMethod = renderMethod; + } + + public static void renderAll() { + FlashbackConfig config = Flashback.getConfig(); + Set openWindows = config.openedWindows; + + for (WindowType windowType : values()) { + if (openWindows.contains(windowType.windowId)) { + boolean justOpened = windowType.openState == WindowOpenState.CLOSED; + + windowType.open.set(true); + windowType.renderMethod.render(windowType.open, justOpened); + + if (!windowType.open.get()) { + openWindows.remove(windowType.windowId); + config.delayedSaveToDefaultFolder(); + } + + windowType.openState = WindowOpenState.OPEN; + } else { + windowType.openState = WindowOpenState.CLOSED; + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java index bdfb1c2..424f021 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -8,6 +8,7 @@ import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FreezeSlowdownFormula; import com.moulberry.flashback.Utils; import com.moulberry.flashback.combo_options.VideoContainer; import com.moulberry.flashback.editor.ui.ReplayUI; @@ -16,12 +17,9 @@ import com.moulberry.flashback.exporting.taskbar.TaskbarHost; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; -import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; -import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; +import com.moulberry.flashback.keyframe.handler.TickrateKeyframeCapture; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.playback.ReplayServer; -import it.unimi.dsi.fastutil.doubles.DoubleArrayList; -import it.unimi.dsi.fastutil.doubles.DoubleList; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.Camera; @@ -37,6 +35,7 @@ import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.network.chat.Component; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.phys.Vec3; import org.bytedeco.ffmpeg.global.avutil; import org.joml.Matrix4f; @@ -54,7 +53,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; -import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; @@ -228,23 +226,25 @@ public class ExportJob { } Minecraft.getInstance().resizeDisplay(); - DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate()); + List ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate()); int clientTickCount = 0; this.renderStartTime = System.currentTimeMillis(); - double lastTickDouble = 0; + double lastClientTickDouble = 0; this.taskbar = TaskbarHost.createTaskbar(); for (int tickIndex = 0; tickIndex < ticks.size(); tickIndex++) { - this.currentTickDouble = ticks.getDouble(tickIndex); - float deltaTicksFloat = (float)(currentTickDouble - lastTickDouble); - lastTickDouble = currentTickDouble; - int currentTick = (int) currentTickDouble; - double partialTick = currentTickDouble - currentTick; - int targetServerTick = this.settings.startTick() + currentTick; + TickInfo tickInfo = ticks.get(tickIndex); + boolean frozen = tickInfo.frozen; + this.currentTickDouble = tickInfo.serverTick; + int targetServerTick = this.settings.startTick() + (int) currentTickDouble; + + float deltaTicksFloat = (float)(tickInfo.clientTick - lastClientTickDouble); + lastClientTickDouble = tickInfo.clientTick; + double partialClientTick = tickInfo.clientTick - (int) tickInfo.clientTick; // Wait until server is on correct replay tick long start = System.nanoTime(); @@ -252,10 +252,10 @@ public class ExportJob { serverTickTimeNanos += System.nanoTime() - start; // Tick client - while (clientTickCount < currentTick) { + while (clientTickCount < (int) tickInfo.clientTick) { start = System.nanoTime(); this.updateRandoms(random, mathRandom); - this.runClientTick(); + this.runClientTick(frozen); clientTickTimeNanos += System.nanoTime() - start; clientTickCount += 1; @@ -263,7 +263,7 @@ public class ExportJob { long pauseScreenStart = System.currentTimeMillis(); while (Minecraft.getInstance().getOverlay() != null || Minecraft.getInstance().screen != null) { - this.runClientTick(); + this.runClientTick(frozen); Window window = Minecraft.getInstance().getWindow(); RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget; @@ -292,7 +292,7 @@ public class ExportJob { } } - this.tryUnfreezeClient(); + this.updateClientFreeze(frozen); KeyframeHandler keyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance()); this.settings.editorState().applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble)); @@ -309,12 +309,12 @@ public class ExportJob { RenderSystem.enableCull(); DeltaTracker.Timer timer = Minecraft.getInstance().deltaTracker; - timer.updateFrozenState(false); + timer.updateFrozenState(frozen); timer.updatePauseState(false); timer.deltaTicks = deltaTicksFloat; timer.realtimeDeltaTicks = deltaTicksFloat; - timer.deltaTickResidual = (float) partialTick; - timer.pausedDeltaTickResidual = (float) partialTick; + timer.deltaTickResidual = (float) partialClientTick; + timer.pausedDeltaTickResidual = (float) partialClientTick; start = System.nanoTime(); Minecraft.getInstance().gameRenderer.render(timer, true); @@ -400,16 +400,24 @@ public class ExportJob { // Ensure replay server is paused at currentTick this.setServerTickAndWait(replayServer, currentTick, true); - this.runClientTick(); + this.runClientTick(false); // Clear particles minecraft.particleEngine.clearParticles(); + // Reset all walk animations & tick counts + for (Entity entity : minecraft.level.entitiesForRendering()) { + if (entity instanceof LivingEntity livingEntity) { + livingEntity.walkAnimation.stop(); + } + entity.tickCount = 0; + } + // Advance until tick is at start while (currentTick < this.settings.startTick()) { currentTick += 1; this.setServerTickAndWait(replayServer, currentTick, true); - this.runClientTick(); + this.runClientTick(false); } // Apply initial position and keyframes at start tick @@ -420,11 +428,11 @@ public class ExportJob { player.setDeltaMovement(Vec3.ZERO); } this.settings.editorState().applyKeyframes(new MinecraftKeyframeHandler(Minecraft.getInstance()), this.settings.startTick()); - this.runClientTick(); + this.runClientTick(false); // Ensured replay server is paused at startTick this.setServerTickAndWait(replayServer, this.settings.startTick(), true); - this.runClientTick(); + this.runClientTick(false); // Remove screen minecraft.setScreen(null); @@ -444,19 +452,20 @@ public class ExportJob { } } - private void runClientTick() { - this.tryUnfreezeClient(); + private void runClientTick(boolean frozen) { + this.updateClientFreeze(frozen); Minecraft minecraft = Minecraft.getInstance(); while (minecraft.pollTask()) {} + this.updateClientFreeze(frozen); minecraft.tick(); - this.updateSoundSound(minecraft); + this.updateSoundSource(minecraft); - this.tryUnfreezeClient(); + this.updateClientFreeze(frozen); } - private void updateSoundSound(Minecraft minecraft) { + private void updateSoundSource(Minecraft minecraft) { EditorState editorState = this.settings.editorState(); if (editorState != null) { Camera audioCamera = editorState.getAudioCamera(); @@ -469,10 +478,10 @@ public class ExportJob { minecraft.getSoundManager().updateSource(Minecraft.getInstance().gameRenderer.getMainCamera()); } - private void tryUnfreezeClient() { + private void updateClientFreeze(boolean frozen) { ClientLevel level = Minecraft.getInstance().level; if (level != null) { - level.tickRateManager().setFrozen(false); + level.tickRateManager().setFrozen(frozen); } } @@ -641,29 +650,12 @@ public class ExportJob { } } - private static class TickrateKeyframeCapture implements KeyframeHandler { - private float tickrate = 20.0f; + private record TickInfo(double serverTick, double clientTick, boolean frozen) {} - @Override - public Set> supportedKeyframes() { - return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE); - } + private static List calculateTicks(EditorState editorState, int startTick, int endTick, double fps) { + List ticks = new ArrayList<>(); - @Override - public boolean alwaysApplyLastKeyframe() { - return true; - } - - @Override - public void applyTickrate(float tickrate) { - this.tickrate = tickrate; - } - } - - private static DoubleList calculateTicks(EditorState editorState, int startTick, int endTick, double fps) { - DoubleList ticks = new DoubleArrayList(); - - ticks.add(0); + ticks.add(new TickInfo(0, 0, false)); double residual = 0; int currentTick = 0; @@ -671,8 +663,10 @@ public class ExportJob { TickrateKeyframeCapture capture = new TickrateKeyframeCapture(); int count = endTick - startTick; + int startFrozen = -1; while (currentTick <= count) { capture.tickrate = 20.0f; + capture.frozen = false; editorState.applyKeyframes(capture, startTick + currentTick + (float) residual); residual += capture.tickrate / fps; @@ -685,10 +679,37 @@ public class ExportJob { break; } - ticks.add(currentTick + residual); + double currentTickDouble = currentTick + residual; + if (!capture.frozen) { + startFrozen = -1; + ticks.add(new TickInfo(currentTickDouble, currentTickDouble, false)); + } else { + if (startFrozen < 0) { + startFrozen = currentTick; + } + + if (capture.frozenDelay == 0) { + ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen), true)); + continue; + } + + double deltaFromStart = currentTickDouble - startFrozen; + double freezeClientTicks = capture.frozenDelay <= 5 ? 0.999 : 1.999; + double freezeDerivative = capture.frozenDelay <= 5 ? 1.0 : 0.5; + if (deltaFromStart > capture.frozenDelay) { + ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen + freezeClientTicks), true)); + } else if (capture.frozenDelay == 1) { + ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen + freezeClientTicks), false)); + } else { + double freezePowerBase = FreezeSlowdownFormula.getFreezePowerBase(capture.frozenDelay, freezeDerivative); + double clientTicks = freezeClientTicks * FreezeSlowdownFormula.calculateFreezeClientTick(deltaFromStart, capture.frozenDelay, freezePowerBase); + ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen + clientTicks), false)); + } + } } return ticks; } + } diff --git a/src/main/java/com/moulberry/flashback/io/ReplayReader.java b/src/main/java/com/moulberry/flashback/io/ReplayReader.java index 1c0eb03..e948134 100644 --- a/src/main/java/com/moulberry/flashback/io/ReplayReader.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayReader.java @@ -14,9 +14,6 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - public class ReplayReader { private final FriendlyByteBuf friendlyByteBuf; @@ -93,8 +90,8 @@ public class ReplayReader { RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess); action.handle(replayServer, registryFriendlyByteBuf); - if (slice.readerIndex() < size) { - throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); + if (slice.readerIndex() < slice.writerIndex()) { + throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + slice.writerIndex() + " bytes available, only read " + slice.readerIndex()); } } @@ -127,8 +124,8 @@ public class ReplayReader { RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess); action.handle(replayServer, registryFriendlyByteBuf); - if (slice.readerIndex() < size) { - throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); + if (slice.readerIndex() < slice.writerIndex()) { + throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + slice.writerIndex() + " bytes available, only read " + slice.readerIndex()); } return true; diff --git a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java index fc0e7f7..8bafbe4 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java @@ -7,6 +7,7 @@ import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; import com.moulberry.flashback.keyframe.impl.FOVKeyframe; +import com.moulberry.flashback.keyframe.impl.FreezeKeyframe; import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; @@ -52,6 +53,7 @@ public abstract class Keyframe { case "camera_orbit" -> context.deserialize(json, CameraOrbitKeyframe.class); case "fov" -> context.deserialize(json, FOVKeyframe.class); case "tickrate" -> context.deserialize(json, TickrateKeyframe.class); + case "freeze" -> context.deserialize(json, FreezeKeyframe.class); case "timelapse" -> context.deserialize(json, TimelapseKeyframe.class); case "time" -> context.deserialize(json, TimeOfDayKeyframe.class); case "camera_shake" -> context.deserialize(json, CameraShakeKeyframe.class); @@ -81,6 +83,10 @@ public abstract class Keyframe { jsonObject = (JsonObject) context.serialize(tickrateKeyframe); jsonObject.addProperty("type", "tickrate"); } + case FreezeKeyframe freezeKeyframe -> { + jsonObject = (JsonObject) context.serialize(freezeKeyframe); + jsonObject.addProperty("type", "freeze"); + } case TimeOfDayKeyframe timeOfDayKeyframe -> { jsonObject = (JsonObject) context.serialize(timeOfDayKeyframe); jsonObject.addProperty("type", "time"); diff --git a/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java index 91a2712..af24a69 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java @@ -1,13 +1,12 @@ package com.moulberry.flashback.keyframe; -import com.moulberry.flashback.keyframe.handler.KeyframeHandler; -import com.moulberry.flashback.state.KeyframeTrack; import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; - public interface KeyframeType { + default @Nullable String icon() { + return null; + } String name(); String id(); @Nullable T createDirect(); diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java b/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java index b04ae90..bc839ce 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java @@ -27,6 +27,10 @@ public interface KeyframeHandler { throw new UnsupportedOperationException(); } + default void applyFreeze(boolean frozen, int frozenDelay) { + throw new UnsupportedOperationException(); + } + default void applyTimeOfDay(int timeOfDay) { throw new UnsupportedOperationException(); } diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java b/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java index 678a8f8..83ba7e5 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java @@ -6,6 +6,7 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType; import com.moulberry.flashback.keyframe.types.CameraShakeKeyframeType; import com.moulberry.flashback.keyframe.types.FOVKeyframeType; +import com.moulberry.flashback.keyframe.types.FreezeKeyframeType; import com.moulberry.flashback.keyframe.types.TimeOfDayKeyframeType; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java b/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java index 2e5a8e7..0179dd2 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java @@ -1,6 +1,7 @@ package com.moulberry.flashback.keyframe.handler; import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.types.FreezeKeyframeType; import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; import com.moulberry.flashback.playback.ReplayServer; @@ -23,7 +24,7 @@ public class ReplayServerKeyframeHandler implements KeyframeHandler { @Override public Set> supportedKeyframes() { - return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE); + return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE, FreezeKeyframeType.INSTANCE); } @Override @@ -36,6 +37,11 @@ public class ReplayServerKeyframeHandler implements KeyframeHandler { this.replayServer.setDesiredTickRate(tickrate, false); } + @Override + public void applyFreeze(boolean frozen, int frozenDelay) { + this.replayServer.setFrozen(frozen, frozenDelay); + } + @Override public void applyTimeOfDay(int timeOfDay) { throw new UnsupportedOperationException(); diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/TickrateKeyframeCapture.java b/src/main/java/com/moulberry/flashback/keyframe/handler/TickrateKeyframeCapture.java new file mode 100644 index 0000000..b3a9c6d --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/TickrateKeyframeCapture.java @@ -0,0 +1,35 @@ +package com.moulberry.flashback.keyframe.handler; + +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.types.FreezeKeyframeType; +import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; +import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; + +import java.util.Set; + +public class TickrateKeyframeCapture implements KeyframeHandler { + public float tickrate = 20.0f; + public boolean frozen = false; + public int frozenDelay = 0; + + @Override + public Set> supportedKeyframes() { + return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE, FreezeKeyframeType.INSTANCE); + } + + @Override + public boolean alwaysApplyLastKeyframe() { + return true; + } + + @Override + public void applyTickrate(float tickrate) { + this.tickrate = tickrate; + } + + @Override + public void applyFreeze(boolean frozen, int frozenDelay) { + this.frozen = frozen; + this.frozenDelay = frozenDelay; + } +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/FreezeKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/FreezeKeyframe.java new file mode 100644 index 0000000..c90b593 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/FreezeKeyframe.java @@ -0,0 +1,99 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; +import com.moulberry.flashback.spline.CatmullRom; +import imgui.ImGui; + +import java.lang.reflect.Type; +import java.util.function.Consumer; + +public class FreezeKeyframe extends Keyframe { + + private boolean frozen; + private int frozenDelay; + + public FreezeKeyframe(boolean frozen, int frozenDelay) { + this(frozen, frozenDelay, InterpolationType.HOLD); + } + + public FreezeKeyframe(boolean frozen, int frozenDelay, InterpolationType interpolationType) { + this.frozen = frozen; + this.frozenDelay = frozenDelay; + this.interpolationType(interpolationType); + } + + @Override + public KeyframeType keyframeType() { + return SpeedKeyframeType.INSTANCE; + } + + @Override + public Keyframe copy() { + return new FreezeKeyframe(this.frozen, this.frozenDelay, this.interpolationType()); + } + + @Override + public void renderEditKeyframe(Consumer> update) { + ImGui.setNextItemWidth(160); + if (ImGui.checkbox("Frozen", this.frozen)) { + boolean newFrozen = !this.frozen; + update.accept(keyframe -> ((FreezeKeyframe)keyframe).frozen = newFrozen); + } + int[] delay = new int[]{this.frozenDelay}; + ImGui.setNextItemWidth(160); + if (ImGui.sliderInt("Delay", delay, 0, 10)) { + delay[0] = Math.max(0, Math.min(10, delay[0])); + update.accept(keyframe -> ((FreezeKeyframe)keyframe).frozenDelay = delay[0]); + } + ImGuiHelper.tooltip("Smooth freeze delay (in ticks)\nSetting this will make the game gradually slow down over the specified delay until it comes to a freeze"); + } + + @Override + public void apply(KeyframeHandler keyframeHandler) { + keyframeHandler.applyFreeze(this.frozen, Math.max(0, Math.min(10, this.frozenDelay))); + } + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) { + this.apply(keyframeHandler); + } + + @Override + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + p1.apply(keyframeHandler); + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public FreezeKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + boolean freeze = jsonObject.get("freeze").getAsBoolean(); + int freezeDelay = jsonObject.has("freezeDelay") ? jsonObject.get("freezeDelay").getAsInt() : 0; + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new FreezeKeyframe(freeze, freezeDelay, interpolationType); + } + + @Override + public JsonElement serialize(FreezeKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("freeze", src.frozen); + jsonObject.addProperty("freezeDelay", src.frozenDelay); + jsonObject.addProperty("type", "freeze"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); + return jsonObject; + } + } +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java b/src/main/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java index b4d56ab..ce01254 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java @@ -29,7 +29,7 @@ public enum SidedInterpolationType { } else if (left == SidedInterpolationType.EASE) { if (right == SidedInterpolationType.LINEAR) { // https://easings.net/#easeInCubic - return amount * amount * amount; + return (float) Math.pow(amount, 3); } else if (right == SidedInterpolationType.EASE) { // https://easings.net/#easeInOutCubic if (amount < 0.5) { 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 a743f7d..235d736 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/CameraKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/CameraKeyframeType.java @@ -14,6 +14,11 @@ public class CameraKeyframeType implements KeyframeType { private CameraKeyframeType() { } + @Override + public @Nullable String icon() { + return "\ue04b"; + } + @Override public String name() { return "Camera"; diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java index c7ca82e..98a1466 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/CameraOrbitKeyframeType.java @@ -22,6 +22,11 @@ public class CameraOrbitKeyframeType implements KeyframeType { private FOVKeyframeType() { } + @Override + public @Nullable String icon() { + return "\ue3af"; + } + @Override public String name() { return "FOV"; diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/FreezeKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/FreezeKeyframeType.java new file mode 100644 index 0000000..90d4141 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/types/FreezeKeyframeType.java @@ -0,0 +1,59 @@ +package com.moulberry.flashback.keyframe.types; + +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.impl.FreezeKeyframe; +import imgui.ImGui; +import imgui.type.ImBoolean; +import org.jetbrains.annotations.Nullable; + +public class FreezeKeyframeType implements KeyframeType { + + public static FreezeKeyframeType INSTANCE = new FreezeKeyframeType(); + + private FreezeKeyframeType() { + } + + @Override + public @Nullable String icon() { + return "\ue9e4"; + } + + @Override + public String name() { + return "Freeze"; + } + + @Override + public String id() { + return "FREEZE"; + } + + @Override + public @Nullable FreezeKeyframe createDirect() { + return null; + } + + @Override + public KeyframeCreatePopup createPopup() { + ImBoolean frozen = new ImBoolean(); + int[] delay = new int[]{0}; + + return () -> { + ImGui.checkbox("Frozen", frozen); + ImGui.sliderInt("Delay", delay, 0, 10); + ImGuiHelper.tooltip("Smooth freeze delay (in ticks)\nSetting this will make the game gradually slow down over the specified delay until it comes to a freeze"); + + delay[0] = Math.max(0, Math.min(10, delay[0])); + + if (ImGui.button("Add")) { + return new FreezeKeyframe(frozen.get(), delay[0]); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + return null; + }; + } +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/SpeedKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/SpeedKeyframeType.java index 107209d..c96e965 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/SpeedKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/SpeedKeyframeType.java @@ -20,6 +20,11 @@ public class SpeedKeyframeType implements KeyframeType { private SpeedKeyframeType() { } + @Override + public @Nullable String icon() { + return "\ue9e4"; + } + @Override public String name() { return "Speed"; diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java index ca67224..563fd83 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/TimeOfDayKeyframeType.java @@ -20,6 +20,11 @@ public class TimeOfDayKeyframeType implements KeyframeType { private TimeOfDayKeyframeType() { } + @Override + public @Nullable String icon() { + return "\ue518"; + } + @Override public String name() { return "Time of day"; diff --git a/src/main/java/com/moulberry/flashback/keyframe/types/TimelapseKeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/types/TimelapseKeyframeType.java index 2bf7814..e3efae4 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/types/TimelapseKeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/types/TimelapseKeyframeType.java @@ -15,6 +15,11 @@ public class TimelapseKeyframeType implements KeyframeType { private TimelapseKeyframeType() { } + @Override + public @Nullable String icon() { + return "\ue422"; + } + @Override public String name() { return "Timelapse"; diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java index ddcf331..e89de7f 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java @@ -169,9 +169,6 @@ public abstract class MixinLevelRenderer { } } - @Unique - private Biome.Precipitation forcePrecipitation = null; - @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(); @@ -198,33 +195,33 @@ public abstract class MixinLevelRenderer { } } - @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; - while (doCompile) { - doCompile = false; - - int before = this.visibleSections.size(); - original.call(instance, camera, frustum, capturedFrustum, isSpectator); - if (this.visibleSections.size() != before) { - doCompile = true; - } - - RenderRegionCache renderRegionCache = new RenderRegionCache(); - for (SectionRenderDispatcher.RenderSection renderSection : this.visibleSections) { - if (renderSection.isDirty()) { - this.sectionRenderDispatcher.rebuildSectionSync(renderSection, renderRegionCache); - renderSection.setNotDirty(); - doCompile = true; - } - } - - this.sectionRenderDispatcher.uploadAllPendingUploads(); - } - } else { - original.call(instance, camera, frustum, capturedFrustum, isSpectator); - } - } +// @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; +// while (doCompile) { +// doCompile = false; +// +// int before = this.visibleSections.size(); +// original.call(instance, camera, frustum, capturedFrustum, isSpectator); +// if (this.visibleSections.size() != before) { +// doCompile = true; +// } +// +// RenderRegionCache renderRegionCache = new RenderRegionCache(); +// for (SectionRenderDispatcher.RenderSection renderSection : this.visibleSections) { +// if (renderSection.isDirty()) { +// this.sectionRenderDispatcher.rebuildSectionSync(renderSection, renderRegionCache); +// renderSection.setNotDirty(); +// doCompile = true; +// } +// } +// +// this.sectionRenderDispatcher.uploadAllPendingUploads(); +// } +// } else { +// original.call(instance, camera, frustum, capturedFrustum, isSpectator); +// } +// } } diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java index b9d9fc9..267e81d 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java @@ -5,16 +5,17 @@ import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; import com.mojang.blaze3d.systems.RenderSystem; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FreezeSlowdownFormula; import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.exporting.ExportJobQueue; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; +import com.moulberry.flashback.keyframe.handler.TickrateKeyframeCapture; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.exporting.PerfectFrames; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.editor.ui.ReplayUI; -import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import it.unimi.dsi.fastutil.floats.FloatUnaryOperator; import net.minecraft.CrashReport; import net.minecraft.ReportedException; @@ -43,7 +44,6 @@ import net.minecraft.server.level.progress.ProcessorChunkProgressListener; import net.minecraft.server.level.progress.StoringChunkProgressListener; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.players.GameProfileCache; -import net.minecraft.util.Mth; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.TickRateManager; import net.minecraft.world.entity.Entity; @@ -131,6 +131,13 @@ public abstract class MixinMinecraft implements MinecraftExt { @Nullable public Entity cameraEntity; + @Shadow + @Final + public DeltaTracker.Timer deltaTracker; + + @Shadow + public long clientTickCount; + @Inject(method="", at=@At("RETURN")) public void init(GameConfig gameConfig, CallbackInfo ci) { ReplayUI.init(); @@ -195,17 +202,70 @@ public abstract class MixinMinecraft implements MinecraftExt { } } + @Unique + private int serverTickFreezeDelayStart = -1; + @Unique + private double clientTickFreezeDelayStart = -1; + @Inject(method = "getTickTargetMillis", at = @At("HEAD"), cancellable = true) public void getTickTargetMillis(float f, CallbackInfoReturnable cir) { - if (Flashback.isInReplay()) { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null) { if (this.level == null) { + clientTickFreezeDelayStart = -1; + serverTickFreezeDelayStart = -1; return; } - TickRateManager tickRateManager = this.level.tickRateManager(); - if (tickRateManager.runsNormally()) { - cir.setReturnValue(tickRateManager.millisecondsPerTick()); + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !replayServer.replayPaused) { + float partialReplayTick = replayServer.getPartialReplayTick(); + + TickrateKeyframeCapture capture = new TickrateKeyframeCapture(); + editorState.applyKeyframes(capture, partialReplayTick); + + if (capture.frozen && capture.frozenDelay > 0 && this.deltaTracker instanceof DeltaTracker.Timer timer) { + if (clientTickFreezeDelayStart < 0) { + clientTickFreezeDelayStart = this.clientTickCount + 1; + serverTickFreezeDelayStart = (int) partialReplayTick; + + TickRateManager tickRateManager = this.level.tickRateManager(); + tickRateManager.setFrozenTicksToRun(capture.frozenDelay <= 5 ? 1 : 2); + } + + double freezeClientTicks = capture.frozenDelay <= 5 ? 0.999 : 1.999; + double freezeDerivative = capture.frozenDelay <= 5 ? 1.0 : 0.5; + + double deltaFromStart = partialReplayTick - serverTickFreezeDelayStart; + + if (deltaFromStart >= 0 && deltaFromStart <= capture.frozenDelay) { + double freezePowerBase = FreezeSlowdownFormula.getFreezePowerBase(capture.frozenDelay, freezeDerivative); + double clientTicks = freezeClientTicks * FreezeSlowdownFormula.calculateFreezeClientTick(deltaFromStart, + capture.frozenDelay, freezePowerBase); + + double currentClientTicks = this.clientTickCount + timer.deltaTickResidual - clientTickFreezeDelayStart; + double freezeRate = Math.max(0.01f, Math.min(1f, clientTicks - currentClientTicks)); + + float tickrate = Math.max(1f, capture.tickrate) * (float) freezeRate; + cir.setReturnValue(1000f / tickrate); + return; + } + } else { + clientTickFreezeDelayStart = -1; + serverTickFreezeDelayStart = -1; + } + + TickRateManager tickRateManager = this.level.tickRateManager(); + if (tickRateManager.runsNormally()) { + cir.setReturnValue(1000f / Math.max(1f, capture.tickrate)); + } + } else { + TickRateManager tickRateManager = this.level.tickRateManager(); + if (tickRateManager.runsNormally()) { + cir.setReturnValue(tickRateManager.millisecondsPerTick()); + } } + } } @@ -275,7 +335,9 @@ public abstract class MixinMinecraft implements MinecraftExt { this.applyKeyframes.set(true); } - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", ordinal = 1), cancellable = true) + @Inject(method = "runTick", at = @At(value = "INVOKE", + target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", + ordinal = 1), cancellable = true) public void runTick_setErrorSection(boolean bl, CallbackInfo ci) { ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer == null) { diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java index 16358dc..149cf19 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java @@ -5,6 +5,7 @@ import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java index 42dc11c..45878c9 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java @@ -1,5 +1,6 @@ package com.moulberry.flashback.mixin.playback; +import com.llamalad7.mixinextras.injector.ModifyReturnValue; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayPlayer; import net.minecraft.client.Minecraft; @@ -22,32 +23,25 @@ public abstract class MixinTickRateManager { @Shadow protected boolean runGameElements; - - /* - * Freeze the replay server, preventing game elements from running normally - */ + @Unique + private final boolean isServerTickRateManager = ((Object)this instanceof ServerTickRateManager); @Inject(method = "tick", at = @At("RETURN")) public void tick(CallbackInfo ci) { - if (Flashback.isInReplay() && this.isServerTickRateManager) { - this.runGameElements = false; + if (Flashback.isInReplay()) { + if (this.isServerTickRateManager) { + this.runGameElements = false; + } } } - @Unique - private final boolean isServerTickRateManager = ((Object)this instanceof ServerTickRateManager); - @Inject(method = "isEntityFrozen", at = @At("HEAD"), cancellable = true) public void isEntityFrozen(Entity entity, CallbackInfoReturnable cir) { if (Flashback.isInReplay()) { if (this.isServerTickRateManager) { cir.setReturnValue(!(entity instanceof ReplayPlayer)); } else { - if (Flashback.isExporting()) { - cir.setReturnValue(false); - } else { - cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); - } + cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java index 3b89bcb..3f53f20 100644 --- a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java +++ b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java @@ -2,26 +2,18 @@ package com.moulberry.flashback.mixin.ui; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; -import com.llamalad7.mixinextras.sugar.Local; -import com.llamalad7.mixinextras.sugar.ref.LocalIntRef; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.screen.FlashbackButton; -import com.moulberry.flashback.screen.SelectReplayScreen; -import net.fabricmc.fabric.api.client.screen.v1.Screens; +import com.moulberry.flashback.screen.select_replay.SelectReplayScreen; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.ImageButton; import net.minecraft.client.gui.components.Renderable; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.AlertScreen; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.TitleScreen; -import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen; import net.minecraft.network.chat.Component; -import net.minecraft.util.StringUtil; import org.apache.commons.lang3.StringUtils; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; @@ -96,7 +88,7 @@ public class MixinTitleScreen extends Screen { List incompatibleMods = Screen.hasShiftDown() ? List.of() : Flashback.getReplayIncompatibleMods(); if (incompatibleMods.isEmpty()) { - this.minecraft.setScreen(new SelectReplayScreen(this)); + this.minecraft.setScreen(new SelectReplayScreen(this, Flashback.getReplayFolder())); } else { String mods = StringUtils.join(incompatibleMods, ", "); String description = """ diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackClearEntities.java b/src/main/java/com/moulberry/flashback/packet/FlashbackClearEntities.java new file mode 100644 index 0000000..be0c1ca --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackClearEntities.java @@ -0,0 +1,15 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public class FlashbackClearEntities implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("clear_entities")); + public static final FlashbackClearEntities INSTANCE = new FlashbackClearEntities(); + + @Override + public Type type() { + return TYPE; + } + +} diff --git a/src/main/java/com/moulberry/flashback/playback/FakePlayer.java b/src/main/java/com/moulberry/flashback/playback/FakePlayer.java index e63788d..18cc8ac 100644 --- a/src/main/java/com/moulberry/flashback/playback/FakePlayer.java +++ b/src/main/java/com/moulberry/flashback/playback/FakePlayer.java @@ -19,6 +19,16 @@ public class FakePlayer extends ServerPlayer { super(minecraftServer, serverLevel, gameProfile, clientInformation); } + @Override + public void remove(RemovalReason removalReason) { + if (removalReason == RemovalReason.DISCARDED && !this.hasDisconnected()) { + this.disconnect(); + this.server.getPlayerList().remove(this); + } else { + super.remove(removalReason); + } + } + @Override public void sendChatMessage(OutgoingChatMessage outgoingChatMessage, boolean bl, ChatType.Bound bound) { } diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java index 9111c47..6ab9f30 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java @@ -192,7 +192,7 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack // Remove all players for (ServerPlayer player : new ArrayList<>(this.replayServer.getPlayerList().getPlayers())) { - player.connection.disconnect(Component.empty()); + player.discard(); } // Remove all levels diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index 0a5f250..4a5dd47 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -14,6 +14,8 @@ import com.moulberry.flashback.packet.FlashbackRemoteSetSlot; import io.netty.channel.embedded.EmbeddedChannel; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.impl.screenhandler.Networking; import net.minecraft.client.multiplayer.PlayerInfo; @@ -95,11 +97,11 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { private void forward(Entity entity, Packet packet) { if (entity == null) { - return; + this.forward(packet); + } else { + ServerChunkCache serverChunkCache = this.level().getChunkSource(); + serverChunkCache.broadcast(entity, packet); } - - ServerChunkCache serverChunkCache = this.level().getChunkSource(); - serverChunkCache.broadcast(entity, packet); } private void setBlockState(ServerLevel level, BlockPos blockPos, BlockState blockState) { @@ -121,7 +123,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { Entity existingEntity = level.getEntity(pendingEntity.getId()); if (existingEntity != null) { if (existingEntity instanceof ServerPlayer existingPlayer) { - existingPlayer.connection.disconnect(Component.empty()); + existingPlayer.discard(); } else if (existingEntity.getType().equals(pendingEntity.getType())) { existingEntity.restoreFrom(pendingEntity); existingEntity.setPos(pendingEntity.getX(), pendingEntity.getY(), pendingEntity.getZ()); @@ -209,16 +211,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { ServerPlayer existingPlayer = this.replayServer.getPlayerList().getPlayer(serverPlayer.getUUID()); if (existingPlayer != null) { - existingPlayer.connection.disconnect(Component.empty()); + existingPlayer.discard(); } Entity existingEntity = this.level().getEntity(serverPlayer.getId()); if (existingEntity != null) { - if (existingEntity instanceof ServerPlayer existingPlayer2) { - existingPlayer2.connection.disconnect(Component.empty()); - } else { - existingEntity.discard(); - } + existingEntity.discard(); } for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { @@ -281,8 +279,6 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { if (existingEntity instanceof ExperienceOrb) { existingEntity.restoreFrom(entity); return; - } else if (existingEntity instanceof ServerPlayer serverPlayer) { - serverPlayer.connection.disconnect(Component.empty()); } else if (existingEntity != null) { existingEntity.discard(); } @@ -483,11 +479,20 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleEntityLinkPacket(ClientboundSetEntityLinkPacket clientboundSetEntityLinkPacket) { Entity source = this.level().getEntity(clientboundSetEntityLinkPacket.getSourceId()); + if (source == null) { + forward(clientboundSetEntityLinkPacket); + return; + } + if (source instanceof Leashable leashable) { if (clientboundSetEntityLinkPacket.getDestId() == 0) { leashable.setLeashedTo(null, true); } else { Entity dest = this.level().getEntity(clientboundSetEntityLinkPacket.getDestId()); + if (dest == null) { + forward(clientboundSetEntityLinkPacket); + return; + } leashable.setLeashedTo(dest, true); } } @@ -677,7 +682,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { if (level != null && level.getEntity(this.localPlayerId) instanceof ServerPlayer serverPlayer) { localPlayer = serverPlayer; if (this.localPlayerId != clientboundLoginPacket.playerId()) { - localPlayer.connection.disconnect(Component.empty()); + localPlayer.discard(); recreatePlayer = true; } } @@ -908,22 +913,26 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleRemoveEntities(ClientboundRemoveEntitiesPacket clientboundRemoveEntitiesPacket) { + IntList forwardRemoveUnknown = new IntArrayList(); clientboundRemoveEntitiesPacket.getEntityIds().forEach(i -> { Entity entity = this.level().getEntity(i); - if (entity != null) { - if (entity instanceof ServerPlayer serverPlayer) { - serverPlayer.connection.disconnect(Component.empty()); - } else { - entity.discard(); - } + if (entity == null) { + forwardRemoveUnknown.add(i); + } else { + entity.discard(); } }); + if (!forwardRemoveUnknown.isEmpty()) { + forward(new ClientboundRemoveEntitiesPacket(forwardRemoveUnknown)); + } } @Override public void handleRemoveMobEffect(ClientboundRemoveMobEffectPacket clientboundRemoveMobEffectPacket) { - Entity entity = clientboundRemoveMobEffectPacket.getEntity(this.level()); - if (entity instanceof LivingEntity livingEntity) { + Entity entity = this.getEntityOrPending(clientboundRemoveMobEffectPacket.entityId()); + if (entity == null) { + forward(clientboundRemoveMobEffectPacket); + } else if (entity instanceof LivingEntity livingEntity) { livingEntity.removeEffect(clientboundRemoveMobEffectPacket.effect()); } } @@ -969,7 +978,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleRotateMob(ClientboundRotateHeadPacket clientboundRotateHeadPacket) { Entity entity = this.getEntityOrPending(clientboundRotateHeadPacket.entityId); - if (entity == null || entity.getId() == this.localPlayerId) { + if (entity == null) { + forward(clientboundRotateHeadPacket); + return; + } + + if (entity.getId() == this.localPlayerId) { return; } @@ -1012,6 +1026,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { public void handleSetEntityData(ClientboundSetEntityDataPacket clientboundSetEntityDataPacket) { Entity entity = this.getEntityOrPending(clientboundSetEntityDataPacket.id()); if (entity == null) { + forward(clientboundSetEntityDataPacket); return; } @@ -1019,6 +1034,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { SynchedEntityData entityData = entity.getEntityData(); for (SynchedEntityData.DataValue dataValue : clientboundSetEntityDataPacket.packedItems()) { + if (dataValue.id() >= entityData.itemsById.length) { + continue; + } + SynchedEntityData.DataItem dataItem = entityData.itemsById[dataValue.id()]; entityData.set((EntityDataAccessor) dataItem.getAccessor(), dataValue.value(), true); } @@ -1028,6 +1047,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { public void handleSetEntityMotion(ClientboundSetEntityMotionPacket clientboundSetEntityMotionPacket) { Entity entity = this.getEntityOrPending(clientboundSetEntityMotionPacket.getId()); if (entity == null) { + forward(clientboundSetEntityMotionPacket); return; } @@ -1041,6 +1061,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleSetEquipment(ClientboundSetEquipmentPacket clientboundSetEquipmentPacket) { Entity entity = this.getEntityOrPending(clientboundSetEquipmentPacket.getEntity()); + if (entity == null) { + forward(clientboundSetEquipmentPacket); + return; + } if (entity instanceof LivingEntity livingEntity) { clientboundSetEquipmentPacket.getSlots().forEach((pair) -> { livingEntity.setItemSlot(pair.getFirst(), pair.getSecond()); @@ -1168,6 +1192,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { public void handleSoundEntityEvent(ClientboundSoundEntityPacket clientboundSoundEntityPacket) { Entity entity = this.level().getEntity(clientboundSoundEntityPacket.getId()); if (entity == null) { + forward(clientboundSoundEntityPacket); return; } @@ -1187,11 +1212,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { Entity taken = this.level().getEntity(clientboundTakeItemEntityPacket.getItemId()); if (taken != null) { - if (taken instanceof ServerPlayer serverPlayer) { - serverPlayer.connection.disconnect(Component.empty()); - } else { - taken.discard(); - } + taken.discard(); } } @@ -1199,6 +1220,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { public void handleTeleportEntity(ClientboundTeleportEntityPacket clientboundTeleportEntityPacket) { Entity entity = this.getEntityOrPending(clientboundTeleportEntityPacket.id()); if (entity == null) { + forward(clientboundTeleportEntityPacket); return; } @@ -1227,6 +1249,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleUpdateAttributes(ClientboundUpdateAttributesPacket clientboundUpdateAttributesPacket) { Entity entity = this.getEntityOrPending(clientboundUpdateAttributesPacket.getEntityId()); + if (entity == null) { + forward(clientboundUpdateAttributesPacket); + return; + } if (entity instanceof LivingEntity livingEntity) { AttributeMap attributeMap = livingEntity.getAttributes(); for (ClientboundUpdateAttributesPacket.AttributeSnapshot snapshot : clientboundUpdateAttributesPacket.getValues()) { @@ -1247,6 +1273,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleUpdateMobEffect(ClientboundUpdateMobEffectPacket clientboundUpdateMobEffectPacket) { Entity entity = this.getEntityOrPending(clientboundUpdateMobEffectPacket.getEntityId()); + if (entity == null) { + forward(clientboundUpdateMobEffectPacket); + return; + } if (entity instanceof LivingEntity livingEntity) { Holder holder = clientboundUpdateMobEffectPacket.getEffect(); MobEffectInstance mobEffectInstance = new MobEffectInstance(holder, clientboundUpdateMobEffectPacket.getEffectDurationTicks(), clientboundUpdateMobEffectPacket.getEffectAmplifier(), diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java index afde1cc..e7ca620 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java @@ -4,11 +4,13 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.PacketHelper; import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.ext.LevelChunkExt; import com.moulberry.flashback.TempFolderProvider; import com.moulberry.flashback.keyframe.handler.ReplayServerKeyframeHandler; import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; +import com.moulberry.flashback.packet.FlashbackClearEntities; import com.moulberry.flashback.packet.FlashbackClearParticles; import com.moulberry.flashback.packet.FlashbackForceClientTick; import com.moulberry.flashback.packet.FlashbackInstantlyLerp; @@ -34,8 +36,6 @@ 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.FileUtil; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; @@ -49,6 +49,7 @@ import net.minecraft.network.protocol.configuration.ClientConfigurationPacketLis import net.minecraft.network.protocol.configuration.ConfigurationProtocols; import net.minecraft.network.protocol.game.*; import net.minecraft.resources.ResourceKey; +import net.minecraft.server.ServerTickRateManager; import net.minecraft.server.Services; import net.minecraft.server.WorldStem; import net.minecraft.server.level.ChunkMap; @@ -111,6 +112,10 @@ public class ReplayServer extends IntegratedServer { public AtomicBoolean sendFinishedServerTick = new AtomicBoolean(false); private volatile float desiredTickRate = 20.0f; private volatile float desiredTickRateManual = 20.0f; + private boolean desiredFrozen = false; + private int desiredFrozenDelay = -1; + private boolean isFrozen = false; + private int frozenDelay = -1; private int currentTick = 0; private volatile int targetTick = 0; @@ -367,8 +372,8 @@ public class ReplayServer extends IntegratedServer { super.removeAll(); } else { List players = this.getPlayers(); - for (int i = 0; i < players.size(); ++i) { - players.get(i).connection.disconnect(shutdownReason); + for (ServerPlayer player : players) { + player.connection.disconnect(shutdownReason); } } } @@ -426,6 +431,11 @@ public class ReplayServer extends IntegratedServer { } } + public void setFrozen(boolean frozen, int delay) { + this.desiredFrozen = frozen; + this.desiredFrozenDelay = delay; + } + public int getReplayTick() { return this.targetTick; } @@ -643,6 +653,10 @@ public class ReplayServer extends IntegratedServer { } positionUpdateSet.add(id); + } else if (!this.isFrozen) { + byte yRot = (byte) Mth.floor(yaw * 256.0F / 360.0F); + byte xRot = (byte) Mth.floor(pitch * 256.0F / 360.0F); + this.getPlayerList().broadcastAll(PacketHelper.createTeleportForUnknown(id, x, y, z, yRot, xRot, onGround)); } } } @@ -702,6 +716,9 @@ public class ReplayServer extends IntegratedServer { public static final TicketType ENTITY_LOAD_TICKET = TicketType.create("replay_entity_load", Comparator.comparingLong(ChunkPos::toLong), 5); public void closeLevel(ServerLevel serverLevel) { + if (serverLevel == null) { + return; + } this.clearLevel(serverLevel); try { serverLevel.close(); @@ -711,12 +728,15 @@ public class ReplayServer extends IntegratedServer { } public void clearLevel(ServerLevel serverLevel) { + if (serverLevel == null) { + return; + } for (ServerPlayer player : new ArrayList<>(serverLevel.players())) { if (player instanceof ReplayPlayer replayPlayer) { replayPlayer.lastFirstPersonDataUUID = null; continue; } - player.connection.disconnect(Component.empty()); + player.discard(); } List entities = new ArrayList<>(); for (Entity entity : serverLevel.getAllEntities()) { @@ -731,6 +751,12 @@ public class ReplayServer extends IntegratedServer { } } serverLevel.setDayTime(0); + + for (ServerPlayer player : serverLevel.players()) { + if (player instanceof ReplayPlayer replayPlayer) { + ServerPlayNetworking.send(replayPlayer, FlashbackClearEntities.INSTANCE); + } + } } @Override @@ -755,9 +781,7 @@ public class ReplayServer extends IntegratedServer { replayReader.handleSnapshot(this); } -// this.accurateEntityPositions = this.pendingAccurateEntityPositions; -// this.pendingAccurateEntityPositions = new ConcurrentHashMap<>(); - this.lastReplayTick = this.currentTick; + this.lastReplayTick = this.targetTick; this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick(); // Update list of replay viewers @@ -803,10 +827,8 @@ public class ReplayServer extends IntegratedServer { this.replayPaused = true; } - boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false) && Flashback.EXPORT_JOB == null; - - if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback) { - this.runUpdates(booleanSupplier, forceApplyKeyframes); + if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback || this.isFrozen) { + this.runUpdates(booleanSupplier); } else { int realTargetTick = this.targetTick; @@ -819,12 +841,12 @@ public class ReplayServer extends IntegratedServer { if (this.targetTick >= realTargetTick) { this.targetTick = realTargetTick; - this.runUpdates(booleanSupplier, forceApplyKeyframes); + this.runUpdates(booleanSupplier); } else { while (this.targetTick <= realTargetTick) { this.fastForwarding = this.targetTick < realTargetTick; - this.runUpdates(booleanSupplier, forceApplyKeyframes); + this.runUpdates(booleanSupplier); if (this.targetTick == realTargetTick) { break; @@ -836,7 +858,7 @@ public class ReplayServer extends IntegratedServer { } } - if (forceApplyKeyframes) { + if (this.forceApplyKeyframes.compareAndSet(true, false)) { ((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes(); } @@ -964,10 +986,19 @@ public class ReplayServer extends IntegratedServer { } } - private void runUpdates(BooleanSupplier booleanSupplier, boolean forceApplyKeyframes) { - if (!this.replayPaused || forceApplyKeyframes) { - this.desiredTickRate = 20.0f; - this.getEditorState().applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick); + private void runUpdates(BooleanSupplier booleanSupplier) { + this.desiredTickRate = 20.0f; + this.desiredFrozen = false; + this.getEditorState().applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick); + + if (this.desiredFrozen && this.frozenDelay < 0) { + if (this.desiredFrozenDelay <= 0) { + this.frozenDelay = 1; + } else if (this.desiredFrozenDelay <= 5) { + this.frozenDelay = 2; + } else { + this.frozenDelay = 3; + } } float tickRate = this.desiredTickRate; @@ -975,14 +1006,34 @@ public class ReplayServer extends IntegratedServer { tickRate *= this.desiredTickRateManual / 20f; } + if (this.desiredFrozen) { + if (this.frozenDelay > 0) { + this.frozenDelay -= 1; + } + if (this.frozenDelay == 0) { + this.isFrozen = true; + } + } else { + this.frozenDelay = -1; + this.isFrozen = false; + } + // Update tick rate & frozen state - if (this.tickRateManager().tickrate() != tickRate) { - this.tickRateManager().setTickRate(tickRate); + ServerTickRateManager tickRateManager = this.tickRateManager(); + if (tickRateManager.tickrate() != tickRate) { + tickRateManager.setTickRate(tickRate); + } + if (tickRateManager.isFrozen() != isFrozen) { + tickRateManager.setFrozen(isFrozen); } boolean tickChanged = this.targetTick != this.currentTick; - this.handleActions(); + if (this.isFrozen && this.targetTick >= this.currentTick) { + tickChanged = false; + } else { + this.handleActions(); + } // Add tickets for keeping entities loaded for (ServerLevel level : this.getAllLevels()) { @@ -996,7 +1047,7 @@ public class ReplayServer extends IntegratedServer { super.tickServer(booleanSupplier); // Teleport entities - if (!this.needsPositionUpdate.isEmpty()) { + if (!this.isFrozen && !this.needsPositionUpdate.isEmpty()) { for (Map.Entry, IntSet> entry : this.needsPositionUpdate.entrySet()) { ResourceKey dimension = entry.getKey(); IntSet entities = entry.getValue(); @@ -1060,18 +1111,18 @@ public class ReplayServer extends IntegratedServer { if (this.replayPaused) { if (tickChanged) { - if (this.tickRateManager().isFrozen()) { - this.tickRateManager().setFrozen(false); + if (tickRateManager.isFrozen()) { + tickRateManager.setFrozen(false); } for (ReplayPlayer replayViewer : this.replayViewers) { ServerPlayNetworking.send(replayViewer, FlashbackForceClientTick.INSTANCE); } - this.tickRateManager().setFrozen(true); - } else if (!this.tickRateManager().isFrozen()) { - this.tickRateManager().setFrozen(true); + tickRateManager.setFrozen(true); + } else if (!tickRateManager.isFrozen()) { + tickRateManager.setFrozen(true); } - } else if (this.tickRateManager().isFrozen()) { - this.tickRateManager().setFrozen(false); + } else if (tickRateManager.isFrozen() != isFrozen) { + tickRateManager.setFrozen(isFrozen); } } } diff --git a/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java index ab40f3f..1a71c99 100644 --- a/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java +++ b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java @@ -20,6 +20,7 @@ public class FlashbackMeta { public UUID replayIdentifier = UUID.randomUUID(); public String name = "Unnamed"; public String versionString = null; + public String worldName = null; public String bobbyWorldName = null; public int dataVersion = 0; public int protocolVersion = 0; @@ -39,6 +40,9 @@ public class FlashbackMeta { if (this.versionString != null) { meta.addProperty("version_string", this.versionString); } + if (this.worldName != null) { + meta.addProperty("world_name", this.worldName); + } if (this.dataVersion != 0) { meta.addProperty("data_version", this.dataVersion); } @@ -98,6 +102,9 @@ public class FlashbackMeta { if (meta.has("version_string")) { flashbackMeta.versionString = meta.get("version_string").getAsString(); } + if (meta.has("world_name")) { + flashbackMeta.worldName = meta.get("world_name").getAsString(); + } if (meta.has("data_version")) { flashbackMeta.dataVersion = meta.get("data_version").getAsInt(); } diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java index aa890b8..866626f 100644 --- a/src/main/java/com/moulberry/flashback/record/Recorder.java +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -27,9 +27,12 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.resources.language.I18n; import net.minecraft.client.resources.server.ServerPackManager; +import net.minecraft.client.server.IntegratedServer; import net.minecraft.core.*; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; @@ -159,6 +162,24 @@ public class Recorder { if (Flashback.supportsDistantHorizons) { this.metadata.distantHorizonPaths.putAll(DistantHorizonsSupport.getDimensionPaths()); } + + String worldName = null; + ServerData serverData = Minecraft.getInstance().getCurrentServer(); + if (serverData != null) { + worldName = serverData.name; + if (worldName.equalsIgnoreCase(I18n.get("selectServer.defaultName"))) { + worldName = null; + } + } else { + IntegratedServer integratedServer = Minecraft.getInstance().getSingleplayerServer(); + if (integratedServer != null) { + worldName = integratedServer.worldData.getLevelName(); + if (worldName.equalsIgnoreCase(I18n.get("selectWorld.newWorld"))) { + worldName = null; + } + } + } + this.metadata.worldName = worldName; } public boolean readyToWrite() { @@ -883,13 +904,13 @@ public class Recorder { Set addedEntries = new HashSet<>(); for (AbstractClientPlayer player : level.players()) { if (addedEntries.add(player.getUUID())) { - PlayerInfo info = connection.getPlayerInfo(player.getUUID()); + PlayerInfo info = player.getPlayerInfo(); if (info != null) { infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), player.getGameProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), info.getTabListOrder(), null)); } else { infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), - player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), info.getTabListOrder(), null)); + player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), 0, null)); } } } diff --git a/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java index b388365..8816c0d 100644 --- a/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java @@ -36,7 +36,7 @@ public class EditReplayScreen extends Screen { private Path replayPath; - protected EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) { + public EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) { super(Component.literal("Edit Replay")); this.lastScreen = lastScreen; this.metadata = summary.getReplayMetadata(); diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java deleted file mode 100644 index 2255906..0000000 --- a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java +++ /dev/null @@ -1,526 +0,0 @@ -/* - * Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4). - */ -package com.moulberry.flashback.screen; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.logging.LogUtils; -import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.FlashbackGson; -import com.moulberry.flashback.SneakyThrow; -import com.moulberry.flashback.record.FlashbackMeta; -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.SharedConstants; -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; -import net.minecraft.client.gui.screens.*; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.resources.language.I18n; -import net.minecraft.client.resources.sounds.SimpleSoundInstance; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.sounds.SoundEvents; -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.Nullable; -import org.slf4j.Logger; - -import java.io.IOException; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributeView; -import java.nio.file.attribute.BasicFileAttributes; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.*; -import java.util.concurrent.CancellationException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; - -public class ReplaySelectionList extends ObjectSelectionList { - private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault()); - private static final ResourceLocation ERROR_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error_highlighted"); - private static final ResourceLocation ERROR_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error"); - private static final ResourceLocation WARNING_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning_highlighted"); - static private final ResourceLocation WARNING_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning"); - private static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join_highlighted"); - private static final ResourceLocation JOIN_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join"); - private static final Logger LOGGER = LogUtils.getLogger(); - private final SelectReplayScreen screen; - private CompletableFuture> pendingReplays; - @Nullable - private List currentlyDisplayedReplays; - private String filter; - private final LoadingHeader loadingHeader; - private final LoadFromDeviceHeader loadFromDeviceHeader; - - private Map lastOpenTimes = null; - - public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l, String string, @Nullable ReplaySelectionList replaySelectionList) { - super(minecraft, i, j, k, l); - this.screen = selectReplayScreen; - this.loadingHeader = new LoadingHeader(minecraft); - this.loadFromDeviceHeader = new LoadFromDeviceHeader(minecraft); - this.filter = string; - this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays(); - this.handleNewReplays(this.pollReplaysIgnoreErrors()); - } - - @Override - protected void clearEntries() { - this.children().forEach(Entry::close); - super.clearEntries(); - } - - @Nullable - private List pollReplaysIgnoreErrors() { - try { - return this.pendingReplays.getNow(null); - } catch (CancellationException | CompletionException runtimeException) { - return null; - } - } - - private void reloadWorldList() { - this.pendingReplays = this.loadReplays(); - } - - @Override - public boolean keyPressed(int i, int j, int k) { - if (CommonInputs.selected(i)) { - ReplayListEntry replayListEntry = this.getReplayListEntry(); - if (replayListEntry != null && replayListEntry.canOpen()) { - this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); - replayListEntry.openReplay(); - return true; - } - } - - return super.keyPressed(i, j, k); - } - - @Override - public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { - List list = this.pollReplaysIgnoreErrors(); - if (list != this.currentlyDisplayedReplays) { - this.handleNewReplays(list); - } - super.renderWidget(guiGraphics, i, j, f); - } - - private void handleNewReplays(@Nullable List list) { - if (list == null) { - this.fillLoadingReplays(); - } else { - this.fillReplays(this.filter, list); - } - this.currentlyDisplayedReplays = list; - } - - public void updateFilter(String string) { - if (this.currentlyDisplayedReplays != null && !string.equals(this.filter)) { - this.fillReplays(string, this.currentlyDisplayedReplays); - } - this.filter = string; - } - -// private Path getOpenTimeCachePath() { -// Path flashbackDir = Flashback.getDataDirectory(); -// Path replayDir = flashbackDir.resolve("replays"); -// return replayDir.resolve(".lastopened.json"); -// } -// -// private synchronized long getOpenTime(UUID uuid) { -// if (this.lastOpenTimes == null) { -// Path path = getOpenTimeCachePath(); -// -// if (Files.exists(path)) { -// try { -// String serialized = Files.readString(path); -// TypeToken> typeToken = (TypeToken>) TypeToken.getParameterized(Map.class, UUID.class, Long.class); -// this.lastOpenTimes = FlashbackGson.PRETTY.fromJson(serialized, typeToken); -// return this.lastOpenTimes.getOrDefault(uuid, 0L); -// } catch (IOException e) { -// Flashback.LOGGER.error("Unable to read last opened cache", e); -// } -// } -// -// this.lastOpenTimes = new HashMap<>(); -// } -// -// return this.lastOpenTimes.getOrDefault(uuid, 0L); -// } -// -// private synchronized void setOpenTime(UUID uuid, long time) { -// this.lastOpenTimes.put(uuid, time); -// } -// -// private synchronized void saveOpenTimeCache() { -// String serialized = FlashbackGson.PRETTY.toJson(this.lastOpenTimes); -// try { -// Files.writeString(getOpenTimeCachePath(), serialized, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, -// StandardOpenOption.CREATE); -// } catch (IOException e) { -// Flashback.LOGGER.error("Unable to write last opened cache", e); -// } -// } - - private CompletableFuture> loadReplays() { - Path flashbackDir = Flashback.getDataDirectory(); - Path replayDir = flashbackDir.resolve("replays"); - - if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) { - return CompletableFuture.completedFuture(List.of()); - } - - ArrayList> futures = new ArrayList<>(); - - try (DirectoryStream directoryStream = Files.newDirectoryStream(replayDir)) { - for (Path path : directoryStream) { - if (!path.toString().endsWith(".zip")) { - continue; - } - - futures.add(CompletableFuture.supplyAsync(() -> { - try { - String fileName = path.getFileName().toString(); - - BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class); - BasicFileAttributes basicFileAttributes = attributeView.readAttributes(); - - long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis()); - - byte[] iconBytes = null; - String metadataString = null; - - try (FileSystem fs = FileSystems.newFileSystem(path)) { - Path iconPath = fs.getPath("/icon.png"); - if (Files.exists(iconPath)) { - iconBytes = Files.readAllBytes(iconPath); - } - - Path metadataPath = fs.getPath("/metadata.json"); - if (Files.exists(metadataPath)) { - metadataString = Files.readString(metadataPath); - } - } catch (IOException e) { - SneakyThrow.sneakyThrow(e); - } - - if (metadataString == null) { - return null; - } - - JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class); - FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson); - if (metadata != null) { - return new ReplaySummary(path, metadata, fileName, lastModified, iconBytes); - } - } catch (IOException e) { - Flashback.LOGGER.error("Failed to load replay", e); - } - return null; - }, Util.backgroundExecutor())); - } - } catch (IOException e) { - SneakyThrow.sneakyThrow(e); - } - - return Util.sequenceFailFastAndCancel(futures).thenApply(list -> list.stream().filter(Objects::nonNull).sorted().toList()); - } - - private void fillReplays(String string, List list) { - this.clearEntries(); - this.addEntry(this.loadFromDeviceHeader); - string = string.toLowerCase(Locale.ROOT); - for (ReplaySummary ReplaySummary : list) { - if (!this.filterAccepts(string, ReplaySummary)) continue; - this.addEntry(new ReplayListEntry(this, ReplaySummary)); - } - this.notifyListUpdated(); - } - - private boolean filterAccepts(String string, ReplaySummary ReplaySummary) { - return ReplaySummary.getReplayName().toLowerCase(Locale.ROOT).contains(string) || ReplaySummary.getReplayId().toLowerCase(Locale.ROOT).contains(string); - } - - private void fillLoadingReplays() { - this.clearEntries(); - this.addEntry(this.loadFromDeviceHeader); - this.addEntry(this.loadingHeader); - this.notifyListUpdated(); - } - - private void notifyListUpdated() { - this.setScrollAmount(this.getScrollAmount()); - this.screen.triggerImmediateNarration(true); - this.screen.updateButtonStatus(null); - } - - @Override - public int getRowWidth() { - return 270; - } - - @Override - public void setSelected(@Nullable Entry entry) { - if (entry instanceof LoadFromDeviceHeader) { - Flashback.openReplayFromFileBrowser(); - return; - } - - super.setSelected(entry); - - if (entry instanceof ReplayListEntry replayListEntry) { - this.screen.updateButtonStatus(replayListEntry.summary); - } else { - this.screen.updateButtonStatus(null); - } - } - - @Nullable - public ReplayListEntry getReplayListEntry() { - if (this.getSelected() instanceof ReplayListEntry replayListEntry) { - return replayListEntry; - } else { - return null; - } - } - - public SelectReplayScreen getScreen() { - return this.screen; - } - - @Override - public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) { - if (this.children().contains(this.loadingHeader)) { - this.loadingHeader.updateNarration(narrationElementOutput); - return; - } - super.updateWidgetNarration(narrationElementOutput); - } - - public static class LoadingHeader extends Entry { - private static final Component LOADING_LABEL = Component.translatable("flashback.select_replay.loading_replays"); - private final Minecraft minecraft; - - public LoadingHeader(Minecraft minecraft) { - this.minecraft = minecraft; - } - - @Override - public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) { - int p = (this.minecraft.screen.width - this.minecraft.font.width(LOADING_LABEL)) / 2; - int q = j + (m - this.minecraft.font.lineHeight) / 2; - guiGraphics.drawString(this.minecraft.font, LOADING_LABEL, p, q, 0xFFFFFF, false); - String string = LoadingDotsText.get(Util.getMillis()); - int r = (this.minecraft.screen.width - this.minecraft.font.width(string)) / 2; - int s = q + this.minecraft.font.lineHeight; - guiGraphics.drawString(this.minecraft.font, string, r, s, -8355712, false); - } - - @Override - public Component getNarration() { - return LOADING_LABEL; - } - } - - public static class LoadFromDeviceHeader extends Entry { - private static final Component LOAD_REPLAY_LABEL = Component.translatable("flashback.select_replay.load_replay_from_file"); - private static final WidgetSprites SPRITES = new WidgetSprites(ResourceLocation.withDefaultNamespace("widget/button"), ResourceLocation.withDefaultNamespace("widget/button_disabled"), - ResourceLocation.withDefaultNamespace("widget/button_highlighted")); - private final Minecraft minecraft; - - public LoadFromDeviceHeader(Minecraft minecraft) { - this.minecraft = minecraft; - } - - @Override - public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) { - guiGraphics.blitSprite(RenderType::guiTextured, SPRITES.get(true, hovered), x + 4, y + 2, width - 8, height - 4); - - int p = (this.minecraft.screen.width - this.minecraft.font.width(LOAD_REPLAY_LABEL)) / 2; - int q = y + (height - this.minecraft.font.lineHeight) / 2 + 1; - guiGraphics.drawString(this.minecraft.font, LOAD_REPLAY_LABEL, p, q, 0xFFFFFF, true); - } - - @Override - public Component getNarration() { - return LOAD_REPLAY_LABEL; - } - } - - public final class ReplayListEntry extends Entry implements AutoCloseable { - private static final int ICON_WIDTH = 32; - private static final int ICON_HEIGHT = 32; - private final Minecraft minecraft; - private final SelectReplayScreen screen; - final ReplaySummary summary; - private final FaviconTexture icon; - private long lastClickTime; - - public ReplayListEntry(ReplaySelectionList replaySelectionList2, ReplaySummary ReplaySummary) { - this.minecraft = replaySelectionList2.minecraft; - this.screen = replaySelectionList2.getScreen(); - this.summary = ReplaySummary; - this.icon = FaviconTexture.forWorld(this.minecraft.getTextureManager(), ReplaySummary.getReplayId()); - this.loadIcon(); - } - - @Override - public Component getNarration() { - MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(), - Component.translationArg(new Date(this.summary.getLastModified())), - this.summary.getInfo()); - return Component.translatable("narrator.select", component); - } - - @Override - public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) { - String title = this.summary.getReplayName(); - String fileAndTime = this.summary.getReplayId(); - long p = this.summary.getLastModified(); - if (p != -1L) { - fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")"; - } - if (StringUtils.isEmpty(title)) { - title = I18n.get("flashback.select_replay.replay") + " " + (index + 1); - } - Component info = this.summary.getInfo(); - - int titleColour = 0xFFFFFF; - if (!this.summary.canOpen()) { - titleColour = 0xFF5555; - } else if (this.summary.hasWarning()) { - titleColour = 0xFFAA55; - } - - guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, false); - guiGraphics.drawString(this.minecraft.font, fileAndTime, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + 3, 0xFF808080, false); - guiGraphics.drawString(this.minecraft.font, info, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false); - - RenderSystem.enableBlend(); - guiGraphics.blit(RenderType::guiTextured, this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32); - RenderSystem.disableBlend(); - - if (this.minecraft.options.touchscreen().get() || hovered) { - guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544); - int q = mouseX - x; - boolean hoveredIcon = q < 32; - - if (hovered && this.summary.getHoverInfo() != null) { - guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY); - } - - ResourceLocation iconOverlay; - if (!this.summary.canOpen()) { - iconOverlay = hoveredIcon ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE; - } else if (this.summary.hasWarning()) { - iconOverlay = hoveredIcon ? WARNING_HIGHLIGHTED_SPRITE : WARNING_SPRITE; - } else { - iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE; - } - guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT); - } - } - - @Override - public boolean mouseClicked(double d, double e, int i) { - if (!this.summary.canOpen()) { - return true; - } - ReplaySelectionList.this.setSelected(this); - if (d - (double) ReplaySelectionList.this.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) { - if (this.canOpen()) { - this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); - this.openReplay(); - } - return true; - } - this.lastClickTime = Util.getMillis(); - return super.mouseClicked(d, e, i); - } - - public boolean canOpen() { - return this.summary.canOpen(); - } - - public void openReplay() { - if (this.summary.canOpen()) { - this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("flashback.select_replay.data_read"))); - Flashback.openReplayWorld(this.summary.getPath()); - -// setOpenTime(this.summary.getReplayMetadata().replayIdentifier, System.currentTimeMillis()); -// saveOpenTimeCache(); - } - } - - public void deleteReplay() { - this.minecraft.setScreen(new ConfirmScreen(bl -> { - if (bl) { - this.minecraft.setScreen(new ProgressScreen(true)); - this.doDeleteReplay(); - } - this.minecraft.setScreen(this.screen); - }, Component.translatable("flashback.select_replay.delete_question"), - Component.translatable("selectWorld.deleteWarning", this.summary.getReplayName()), - Component.translatable("selectWorld.deleteButton"), - CommonComponents.GUI_CANCEL) - ); - } - - private void doDeleteReplay() { - String id = this.summary.getReplayId(); - try { - Files.delete(this.summary.getPath()); - } catch (IOException e) { - SystemToast.onWorldDeleteFailure(this.minecraft, id); - LOGGER.error("Failed to delete replay {}", id, e); - } - - ReplaySelectionList.this.reloadWorldList(); - } - - public void editReplay() { - Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary)); - } - - private void loadIcon() { - byte[] iconBytes = this.summary.getIconBytes(); - - if (iconBytes != null) { - try { - this.icon.upload(NativeImage.read(iconBytes)); - return; - } catch (Throwable t) { - LOGGER.error("Invalid icon for replay {}", this.summary.getReplayId(), t); - } - } - - this.icon.clear(); - } - - @Override - public void close() { - this.icon.close(); - } - } - - public static abstract class Entry extends ObjectSelectionList.Entry implements AutoCloseable { - @Override - public void close() {} - } -} - diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java b/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java index bd66d72..ab056b1 100644 --- a/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java +++ b/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java @@ -19,17 +19,19 @@ public class ReplaySummary implements Comparable { private final FlashbackMeta metadata; private final String replayId; private final long lastModified; + private final long filesize; private final byte[] iconBytes; private Component info = null; private Component hoverInfo = null; private boolean canOpen = true; private boolean hasWarning = false; - public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, @Nullable byte[] iconBytes) { + public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, long filesize, @Nullable byte[] iconBytes) { this.path = path; this.metadata = metadata; this.replayId = replayId; this.lastModified = lastModified; + this.filesize = filesize; this.iconBytes = iconBytes; if (metadata.protocolVersion != 0 && metadata.protocolVersion != SharedConstants.getProtocolVersion()) { @@ -71,10 +73,18 @@ public class ReplaySummary implements Comparable { return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name; } + public @Nullable String getWorldName() { + return this.metadata.worldName; + } + public long getLastModified() { return this.lastModified; } + public long getFilesize() { + return filesize; + } + public Component getInfo() { if (this.info == null) { MutableComponent mutable = Component.empty(); diff --git a/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java b/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java index 96d85f2..ba405b1 100644 --- a/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java @@ -48,7 +48,7 @@ public class UnsupportedLoaderScreen extends Screen { if (this.countdown == 0) { var button = Button.builder(Component.literal("I Understand"), b -> { Flashback.getConfig().nextUnsupportedModLoaderWarning = System.currentTimeMillis() + Duration.ofDays(7).toMillis(); - Flashback.getConfig().saveToDefaultFolder(); + Flashback.getConfig().delayedSaveToDefaultFolder(); Minecraft.getInstance().setScreen(this.lastScreen); }).bounds((this.width - 150) / 2, buttonY, 150, 20).build(); this.addRenderableWidget(button); diff --git a/src/main/java/com/moulberry/flashback/screen/select_replay/NaturalOrderComparator.java b/src/main/java/com/moulberry/flashback/screen/select_replay/NaturalOrderComparator.java new file mode 100644 index 0000000..e786b63 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/NaturalOrderComparator.java @@ -0,0 +1,157 @@ +package com.moulberry.flashback.screen.select_replay;/* + NaturalOrderComparator.java -- Perform 'natural order' comparisons of strings in Java. + Copyright (C) 2003 by Pierre-Luc Paour + + Based on the C version by Martin Pool, of which this is more or less a straight conversion. + Copyright (C) 2000 by Martin Pool + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + +===== Moulberry ===== +This is an altered source version. +This message is marking it as such. +===================== + */ + +import java.util.*; + +public class NaturalOrderComparator implements Comparator { + public static NaturalOrderComparator INSTANCE = new NaturalOrderComparator(); + + private int compareRight(String a, String b) { + int bias = 0, ia = 0, ib = 0; + + // The longest run of digits wins. That aside, the greatest + // value wins, but we can't know that it will until we've scanned + // both numbers to know that they have the same magnitude, so we + // remember it in BIAS. + for (;; ia++, ib++) { + char ca = charAt(a, ia); + char cb = charAt(b, ib); + + if (!isDigit(ca) && !isDigit(cb)) { + return bias; + } + if (!isDigit(ca)) { + return -1; + } + if (!isDigit(cb)) { + return +1; + } + if (ca == 0 && cb == 0) { + return bias; + } + + if (bias == 0) { + if (ca < cb) { + bias = -1; + } else if (ca > cb) { + bias = +1; + } + } + } + } + + public int compare(String a, String b) { + int indexA = 0, indexB = 0; + int numZeroesA, numZeroesB; + char charA, charB; + + while (true) { + // Only count the number of zeroes leading the last number compared + numZeroesA = numZeroesB = 0; + + charA = charAt(a, indexA); + charB = charAt(b, indexB); + + // skip over leading spaces or zeros + while (Character.isSpaceChar(charA) || charA == '0') { + if (charA == '0') { + numZeroesA++; + } else { + // Only count consecutive zeroes + numZeroesA = 0; + } + + charA = charAt(a, ++indexA); + } + + while (Character.isSpaceChar(charB) || charB == '0') { + if (charB == '0') { + numZeroesB++; + } else { + // Only count consecutive zeroes + numZeroesB = 0; + } + + charB = charAt(b, ++indexB); + } + + if (charA == 0 && charB == 0) { + // The strings compare the same. Perhaps the caller + // will want to call strcmp to break the tie. + return compareEqual(a, b, numZeroesA, numZeroesB); + } + + // Process run of digits + boolean isDigitA = Character.isDigit(charA); + boolean isDigitB = Character.isDigit(charB); + if (isDigitA && isDigitB) { + int bias = compareRight(a.substring(indexA), b.substring(indexB)); + if (bias != 0) { + return bias; + } + } + + if (isDigitA && !isDigitB) { + return 1; + } + if (isDigitB && !isDigitA) { + return -1; + } + + int charCompare = Character.compare(charA, charB); + if (charCompare != 0) { + return charCompare; + } + + ++indexA; + ++indexB; + } + } + + private static boolean isDigit(char c) { + return Character.isDigit(c) || c == '.' || c == ','; + } + + private static char charAt(String s, int i) { + return i >= s.length() ? 0 : s.charAt(i); + } + + private static int compareEqual(String a, String b, int nza, int nzb) { + if (nza - nzb != 0) { + return nza - nzb; + } + + if (a.length() == b.length()) { + return a.compareTo(b); + } + + return a.length() - b.length(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/screen/select_replay/PendingSelectionEntry.java b/src/main/java/com/moulberry/flashback/screen/select_replay/PendingSelectionEntry.java new file mode 100644 index 0000000..afb0558 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/PendingSelectionEntry.java @@ -0,0 +1,52 @@ +package com.moulberry.flashback.screen.select_replay; + +import com.moulberry.flashback.screen.ReplaySummary; +import net.minecraft.client.Minecraft; + +import java.nio.file.Path; +import java.util.Locale; + +public interface PendingSelectionEntry { + + ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft); + boolean matchesFilter(String filter); + + record Folder(Path path, String filename, long modifiedTime, int replayCount) implements PendingSelectionEntry { + public Folder(Path path, long modifiedTime, int replayCount) { + this(path, path.getFileName().toString().toLowerCase(Locale.ROOT), modifiedTime, replayCount); + } + + @Override + public ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft) { + return new ReplaySelectionEntry.ReplayFolder(replaySelectionList, minecraft, this.path, this.modifiedTime, this.replayCount); + } + + @Override + public boolean matchesFilter(String filter) { + return this.filename.contains(filter); + } + } + + record Replay(ReplaySummary summary) implements PendingSelectionEntry { + @Override + public ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft) { + return new ReplaySelectionEntry.ReplayListEntry(replaySelectionList, minecraft, this.summary); + } + + @Override + public boolean matchesFilter(String filter) { + if (this.summary.getReplayName().toLowerCase(Locale.ROOT).contains(filter) || + this.summary.getReplayId().toLowerCase(Locale.ROOT).contains(filter)) { + return true; + } + String worldName = this.summary.getWorldName(); + if (worldName != null) { + return worldName.toLowerCase(Locale.ROOT).contains(filter); + } else { + return false; + } + } + } + + +} diff --git a/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySelectionEntry.java b/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySelectionEntry.java new file mode 100644 index 0000000..b0214b9 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySelectionEntry.java @@ -0,0 +1,342 @@ +package com.moulberry.flashback.screen.select_replay; + +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.logging.LogUtils; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.screen.EditReplayScreen; +import com.moulberry.flashback.screen.ReplaySummary; +import net.minecraft.ChatFormatting; +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.screens.ConfirmScreen; +import net.minecraft.client.gui.screens.FaviconTexture; +import net.minecraft.client.gui.screens.GenericMessageScreen; +import net.minecraft.client.gui.screens.LoadingDotsText; +import net.minecraft.client.gui.screens.ProgressScreen; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.resources.language.I18n; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundEvents; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.Date; +import java.util.Locale; + +public abstract class ReplaySelectionEntry extends ObjectSelectionList.Entry implements AutoCloseable { + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault()); + private static final ResourceLocation FOLDER_SPRITE = Flashback.createResourceLocation("folder"); + private static final ResourceLocation ERROR_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error_highlighted"); + private static final ResourceLocation ERROR_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error"); + private static final ResourceLocation WARNING_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning_highlighted"); + static private final ResourceLocation WARNING_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning"); + private static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join_highlighted"); + private static final ResourceLocation JOIN_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join"); + private static final Logger LOGGER = LogUtils.getLogger(); + + @Override + public void close() { + } + + public static class LoadFromDeviceHeader extends ReplaySelectionEntry { + private static final Component LOAD_REPLAY_LABEL = Component.translatable("flashback.select_replay.load_replay_from_file"); + private static final WidgetSprites SPRITES = new WidgetSprites(ResourceLocation.withDefaultNamespace("widget/button"), ResourceLocation.withDefaultNamespace("widget/button_disabled"), + ResourceLocation.withDefaultNamespace("widget/button_highlighted")); + private final Minecraft minecraft; + + public LoadFromDeviceHeader(Minecraft minecraft) { + this.minecraft = minecraft; + } + + @Override + public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) { + guiGraphics.blitSprite(RenderType::guiTextured, SPRITES.get(true, hovered), x + 4, y + 2, width - 8, height - 4); + + int p = (this.minecraft.screen.width - this.minecraft.font.width(LOAD_REPLAY_LABEL)) / 2; + int q = y + (height - this.minecraft.font.lineHeight) / 2 + 1; + guiGraphics.drawString(this.minecraft.font, LOAD_REPLAY_LABEL, p, q, 0xFFFFFF, true); + } + + @Override + public Component getNarration() { + return LOAD_REPLAY_LABEL; + } + } + + public static class LoadingHeader extends ReplaySelectionEntry { + private static final Component LOADING_LABEL = Component.translatable("flashback.select_replay.loading_replays"); + private final Minecraft minecraft; + + public LoadingHeader(Minecraft minecraft) { + this.minecraft = minecraft; + } + + @Override + public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) { + int p = (this.minecraft.screen.width - this.minecraft.font.width(LOADING_LABEL)) / 2; + int q = j + (m - this.minecraft.font.lineHeight) / 2; + guiGraphics.drawString(this.minecraft.font, LOADING_LABEL, p, q, 0xFFFFFF, false); + String string = LoadingDotsText.get(Util.getMillis()); + int r = (this.minecraft.screen.width - this.minecraft.font.width(string)) / 2; + int s = q + this.minecraft.font.lineHeight; + guiGraphics.drawString(this.minecraft.font, string, r, s, -8355712, false); + } + + @Override + public Component getNarration() { + return LOADING_LABEL; + } + } + + public static class ReplayFolder extends ReplaySelectionEntry implements AutoCloseable { + private static final int ICON_WIDTH = 32; + private static final int ICON_HEIGHT = 32; + private final Minecraft minecraft; + private final ReplaySelectionList replaySelectionList; + private final Path path; + private final String nameString; + private final Component nameComponent; + private final long modifiedTime; + private final int replayCount; + + private long lastClickTime; + + public ReplayFolder(ReplaySelectionList replaySelectionList, Minecraft minecraft, Path path, long modifiedTime, int replayCount) { + this.minecraft = minecraft; + this.replaySelectionList = replaySelectionList; + this.path = path; + this.nameString = path.getFileName().toString(); + this.nameComponent = Component.literal(this.nameString).withStyle(ChatFormatting.BOLD); + this.modifiedTime = modifiedTime; + this.replayCount = replayCount; + } + + @Override + public Component getNarration() { + return Component.translatable("narrator.select", nameComponent); + } + + @Override + public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) { + guiGraphics.drawString(this.minecraft.font, this.nameComponent, x + ICON_WIDTH + 3, y + 1, -1, false); + + int textY = y + this.minecraft.font.lineHeight + 2; + + if (this.modifiedTime > 0) { + String time = "Created: " + DATE_FORMAT.format(Instant.ofEpochMilli(this.modifiedTime)); + guiGraphics.drawString(this.minecraft.font, time, x + ICON_WIDTH + 3, textY + 1, 0xFF808080, false); + textY += this.minecraft.font.lineHeight; + } + + guiGraphics.drawString(this.minecraft.font, "Replays: " + this.replayCount, x + ICON_WIDTH + 3, textY + 3, 0xFF808080, false); + + RenderSystem.enableBlend(); + guiGraphics.blitSprite(RenderType::guiTextured, FOLDER_SPRITE, x, y, ICON_WIDTH, ICON_HEIGHT); + RenderSystem.disableBlend(); + + if (this.minecraft.options.touchscreen().get() || hovered) { + guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544); + int q = mouseX - x; + boolean hoveredIcon = q < 32; + + ResourceLocation iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE; + guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT); + } + } + + @Override + public boolean mouseClicked(double d, double e, int i) { + this.replaySelectionList.setSelected(this); + if (d - (double) this.replaySelectionList.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) { + this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); + this.minecraft.setScreen(new SelectReplayScreen(this.replaySelectionList.getScreen(), this.path)); + return true; + } + this.lastClickTime = Util.getMillis(); + return super.mouseClicked(d, e, i); + } + } + + public static class ReplayListEntry extends ReplaySelectionEntry implements AutoCloseable { + private static final int ICON_WIDTH = 32; + private static final int ICON_HEIGHT = 32; + private final Minecraft minecraft; + private final ReplaySelectionList replaySelectionList; + final ReplaySummary summary; + private FaviconTexture icon; + private long lastClickTime; + + public ReplayListEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft, ReplaySummary ReplaySummary) { + this.minecraft = minecraft; + this.replaySelectionList = replaySelectionList; + this.summary = ReplaySummary; + this.icon = FaviconTexture.forWorld(this.minecraft.getTextureManager(), ReplaySummary.getReplayId()); + this.loadIcon(); + } + + @Override + public Component getNarration() { + MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(), + Component.translationArg(new Date(this.summary.getLastModified())), + this.summary.getInfo()); + return Component.translatable("narrator.select", component); + } + + @Override + public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) { + String title = this.summary.getReplayName(); + String fileAndTime = this.summary.getReplayId(); + long p = this.summary.getLastModified(); + if (p != -1L) { + fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")"; + } + if (StringUtils.isEmpty(title)) { + title = I18n.get("flashback.select_replay.replay") + " " + (index + 1); + } + Component info = this.summary.getInfo(); + + int titleColour = 0xFFFFFF; + if (!this.summary.canOpen()) { + titleColour = 0xFF5555; + } else if (this.summary.hasWarning()) { + titleColour = 0xFFAA55; + } + + int titleEnd = guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, false); + + String worldName = this.summary.getWorldName(); + if (worldName != null) { + guiGraphics.drawString(this.minecraft.font, "(" + worldName + ")", titleEnd + 4, y + 1, 0xFF808080, false); + } + + guiGraphics.drawString(this.minecraft.font, fileAndTime, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + 3, 0xFF808080, false); + guiGraphics.drawString(this.minecraft.font, info, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false); + + RenderSystem.enableBlend(); + guiGraphics.blit(RenderType::guiTextured, this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32); + RenderSystem.disableBlend(); + + if (this.minecraft.options.touchscreen().get() || hovered) { + guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544); + int q = mouseX - x; + boolean hoveredIcon = q < 32; + + if (hovered && this.summary.getHoverInfo() != null) { + guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY); + } + + ResourceLocation iconOverlay; + if (!this.summary.canOpen()) { + iconOverlay = hoveredIcon ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE; + } else if (this.summary.hasWarning()) { + iconOverlay = hoveredIcon ? WARNING_HIGHLIGHTED_SPRITE : WARNING_SPRITE; + } else { + iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE; + } + guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT); + } + } + + @Override + public boolean mouseClicked(double d, double e, int i) { + if (!this.summary.canOpen()) { + return true; + } + this.replaySelectionList.setSelected(this); + if (d - (double) this.replaySelectionList.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) { + if (this.canOpen()) { + this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); + this.openReplay(); + } + return true; + } + this.lastClickTime = Util.getMillis(); + return super.mouseClicked(d, e, i); + } + + public boolean canOpen() { + return this.summary.canOpen(); + } + + public void openReplay() { + if (this.summary.canOpen()) { + this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("flashback.select_replay.data_read"))); + Flashback.openReplayWorld(this.summary.getPath()); + +// setOpenTime(this.summary.getReplayMetadata().replayIdentifier, System.currentTimeMillis()); +// saveOpenTimeCache(); + } + } + + public void deleteReplay() { + this.minecraft.setScreen(new ConfirmScreen(bl -> { + if (bl) { + this.minecraft.setScreen(new ProgressScreen(true)); + this.doDeleteReplay(); + } + this.minecraft.setScreen(this.replaySelectionList.getScreen()); + }, Component.translatable("flashback.select_replay.delete_question"), + Component.translatable("selectWorld.deleteWarning", this.summary.getReplayName()), + Component.translatable("selectWorld.deleteButton"), + CommonComponents.GUI_CANCEL) + ); + } + + private void doDeleteReplay() { + String id = this.summary.getReplayId(); + try { + Files.delete(this.summary.getPath()); + } catch (IOException e) { + SystemToast.onWorldDeleteFailure(this.minecraft, id); + LOGGER.error("Failed to delete replay {}", id, e); + } + + this.replaySelectionList.reloadReplayList(); + } + + public void editReplay() { + Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary)); + } + + private void loadIcon() { + byte[] iconBytes = this.summary.getIconBytes(); + + if (iconBytes != null) { + try { + this.icon.upload(NativeImage.read(iconBytes)); + return; + } catch (Throwable t) { + LOGGER.error("Invalid icon for replay {}", this.summary.getReplayId(), t); + } + } + + this.icon.clear(); + } + + @Override + public void close() { + if (this.icon != null) { + this.icon.close(); + this.icon = null; + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySelectionList.java b/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySelectionList.java new file mode 100644 index 0000000..2211bf8 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySelectionList.java @@ -0,0 +1,282 @@ +/* + * Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4). + */ +package com.moulberry.flashback.screen.select_replay; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.SneakyThrow; +import com.moulberry.flashback.record.FlashbackMeta; +import com.moulberry.flashback.screen.ReplaySummary; +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.narration.NarrationElementOutput; +import net.minecraft.client.gui.navigation.CommonInputs; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.*; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +public class ReplaySelectionList extends ObjectSelectionList { + private final SelectReplayScreen screen; + private CompletableFuture> pendingReplays; + @Nullable + private List currentlyDisplayedReplays; + private String filter; + private ReplaySorting replaySorting; + private boolean sortDescending; + private final ReplaySelectionEntry.LoadingHeader loadingHeader; + private final ReplaySelectionEntry.LoadFromDeviceHeader loadFromDeviceHeader; + + public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l, + String filter, ReplaySorting replaySorting, boolean sortDescending, + @Nullable ReplaySelectionList replaySelectionList) { + super(minecraft, i, j, k, l); + this.screen = selectReplayScreen; + this.loadingHeader = new ReplaySelectionEntry.LoadingHeader(minecraft); + this.loadFromDeviceHeader = new ReplaySelectionEntry.LoadFromDeviceHeader(minecraft); + this.filter = filter; + this.replaySorting = replaySorting; + this.sortDescending = sortDescending; + this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays(); + this.fillLoadingReplays(); + } + + @Override + protected void clearEntries() { + this.children().forEach(ReplaySelectionEntry::close); + super.clearEntries(); + } + + @Nullable + private List pollReplaysIgnoreErrors() { + try { + return this.pendingReplays.getNow(null); + } catch (CancellationException | CompletionException runtimeException) { + return null; + } + } + + public void reloadReplayList() { + this.pendingReplays = this.loadReplays(); + } + + @Override + public boolean keyPressed(int i, int j, int k) { + if (CommonInputs.selected(i)) { + ReplaySelectionEntry.ReplayListEntry replayListEntry = this.getReplayListEntry(); + if (replayListEntry != null && replayListEntry.canOpen()) { + this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); + replayListEntry.openReplay(); + return true; + } + } + + return super.keyPressed(i, j, k); + } + + @Override + public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { + List list = this.pollReplaysIgnoreErrors(); + if (this.currentlyDisplayedReplays != list) { + if (list == null) { + this.fillLoadingReplays(); + } else { + list.sort(this.replaySorting.comparator(this.sortDescending)); + this.fillReplays(this.filter, list); + } + + this.currentlyDisplayedReplays = list; + } + super.renderWidget(guiGraphics, i, j, f); + } + + public void updateFilter(String filter, ReplaySorting replaySorting, boolean sortDescending) { + if (this.currentlyDisplayedReplays != null) { + if (this.replaySorting != replaySorting || this.sortDescending != sortDescending) { + this.currentlyDisplayedReplays.sort(replaySorting.comparator(sortDescending)); + this.fillReplays(filter, this.currentlyDisplayedReplays); + } else if (!filter.equals(this.filter)) { + this.fillReplays(filter, this.currentlyDisplayedReplays); + } + } + this.filter = filter; + this.replaySorting = replaySorting; + this.sortDescending = sortDescending; + } + + private CompletableFuture> loadReplays() { + Path replayDir = this.screen.path; + + if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) { + return CompletableFuture.completedFuture(new ArrayList<>()); + } + + ArrayList> futures = new ArrayList<>(); + + try (DirectoryStream directoryStream = Files.newDirectoryStream(replayDir)) { + for (Path path : directoryStream) { + if (Files.isDirectory(path)) { + futures.add(CompletableFuture.supplyAsync(() -> { + try { + BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class); + BasicFileAttributes basicFileAttributes = attributeView.readAttributes(); + + long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis()); + + int replaysInFolder = 0; + try (DirectoryStream filesInFolder = Files.newDirectoryStream(path)) { + for (Path fileInFolder : filesInFolder) { + if (fileInFolder.toString().endsWith(".zip")) { + replaysInFolder += 1; + } + } + } + + return new PendingSelectionEntry.Folder(path, lastModified, replaysInFolder); + } catch (IOException e) { + Flashback.LOGGER.error("Failed to load replay folder", e); + } + return null; + }, Util.backgroundExecutor())); + continue; + } + + if (!path.toString().endsWith(".zip")) { + continue; + } + + futures.add(CompletableFuture.supplyAsync(() -> { + try { + String fileName = path.getFileName().toString(); + + BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class); + BasicFileAttributes basicFileAttributes = attributeView.readAttributes(); + + long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis()); + long filesize = basicFileAttributes.size(); + + byte[] iconBytes = null; + String metadataString = null; + + try (FileSystem fs = FileSystems.newFileSystem(path)) { + Path iconPath = fs.getPath("/icon.png"); + if (Files.exists(iconPath)) { + iconBytes = Files.readAllBytes(iconPath); + } + + Path metadataPath = fs.getPath("/metadata.json"); + if (Files.exists(metadataPath)) { + metadataString = Files.readString(metadataPath); + } + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + + if (metadataString == null) { + return null; + } + + JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class); + FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson); + if (metadata != null) { + ReplaySummary summary = new ReplaySummary(path, metadata, fileName, lastModified, filesize, iconBytes); + return new PendingSelectionEntry.Replay(summary); + } + } catch (IOException e) { + Flashback.LOGGER.error("Failed to load replay", e); + } + return null; + }, Util.backgroundExecutor())); + } + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + + return Util.sequenceFailFastAndCancel(futures).thenApply(list -> { + list.removeIf(Objects::isNull); + return list; + }); + } + + private void fillReplays(String filter, List list) { + this.clearEntries(); + this.addEntry(this.loadFromDeviceHeader); + filter = filter.toLowerCase(Locale.ROOT); + for (PendingSelectionEntry entry : list) { + if (entry.matchesFilter(filter)) { + this.addEntry(entry.createEntry(this, this.minecraft)); + } + } + this.notifyListUpdated(); + } + + private void fillLoadingReplays() { + this.clearEntries(); + this.addEntry(this.loadFromDeviceHeader); + this.addEntry(this.loadingHeader); + this.notifyListUpdated(); + } + + private void notifyListUpdated() { + this.setScrollAmount(this.getScrollAmount()); + this.screen.triggerImmediateNarration(true); + this.screen.updateButtonStatus(null); + } + + @Override + public int getRowWidth() { + return 270; + } + + @Override + public void setSelected(@Nullable ReplaySelectionEntry entry) { + if (entry instanceof ReplaySelectionEntry.LoadFromDeviceHeader) { + Flashback.openReplayFromFileBrowser(); + return; + } + + super.setSelected(entry); + + if (entry instanceof ReplaySelectionEntry.ReplayListEntry replayListEntry) { + this.screen.updateButtonStatus(replayListEntry.summary); + } else { + this.screen.updateButtonStatus(null); + } + } + + @Nullable + public ReplaySelectionEntry.ReplayListEntry getReplayListEntry() { + if (this.getSelected() instanceof ReplaySelectionEntry.ReplayListEntry replayListEntry) { + return replayListEntry; + } else { + return null; + } + } + + public SelectReplayScreen getScreen() { + return this.screen; + } + + @Override + public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) { + if (this.children().contains(this.loadingHeader)) { + this.loadingHeader.updateNarration(narrationElementOutput); + return; + } + super.updateWidgetNarration(narrationElementOutput); + } + +} + diff --git a/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySorting.java b/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySorting.java new file mode 100644 index 0000000..64b716f --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/ReplaySorting.java @@ -0,0 +1,76 @@ +package com.moulberry.flashback.screen.select_replay; + +import com.moulberry.flashback.screen.ReplaySummary; +import net.minecraft.network.chat.Component; + +import java.util.Comparator; + +public enum ReplaySorting { + + CREATED_DATE( + Component.literal("Created Date"), + Comparator.comparingLong(ReplaySummary::getLastModified).reversed(), + Comparator.comparingLong(ReplaySummary::getLastModified) + ), + REPLAY_NAME( + Component.literal("Replay Name"), + Comparator.comparing(ReplaySummary::getReplayName, NaturalOrderComparator.INSTANCE), + Comparator.comparing(ReplaySummary::getReplayName, NaturalOrderComparator.INSTANCE.reversed()) + ), + WORLD_NAME( + Component.literal("World Name"), + Comparator.comparing(ReplaySummary::getWorldName, Comparator.nullsLast(NaturalOrderComparator.INSTANCE)), + Comparator.comparing(ReplaySummary::getWorldName, Comparator.nullsLast(NaturalOrderComparator.INSTANCE.reversed())) + ), + DURATION( + Component.literal("Duration"), + Comparator.comparingLong(replay -> replay.getReplayMetadata().totalTicks).reversed(), + Comparator.comparingLong(replay -> replay.getReplayMetadata().totalTicks) + ), + FILESIZE( + Component.literal("Filesize"), + Comparator.comparingLong(ReplaySummary::getFilesize).reversed(), + Comparator.comparingLong(ReplaySummary::getFilesize) + ); + + private final Component component; + private final Comparator descendingComparator; + private final Comparator ascendingComparator; + + ReplaySorting(Component component, Comparator descendingComparator, Comparator ascendingComparator) { + this.component = component; + this.descendingComparator = descendingComparator.thenComparing(ReplaySummary::getReplayId, NaturalOrderComparator.INSTANCE); + this.ascendingComparator = ascendingComparator.thenComparing(ReplaySummary::getReplayId, NaturalOrderComparator.INSTANCE); + } + + public Component component() { + return this.component; + } + + public Comparator comparator(boolean descending) { + Comparator replayComparator; + if (descending) { + replayComparator = this.descendingComparator; + } else { + replayComparator = this.ascendingComparator; + } + return (entry1, entry2) -> { + if (entry1 instanceof PendingSelectionEntry.Replay replay1) { + if (entry2 instanceof PendingSelectionEntry.Replay replay2) { + return replayComparator.compare(replay1.summary(), replay2.summary()); + } else { + return 1; + } + } else if (entry1 instanceof PendingSelectionEntry.Folder folder1) { + if (entry2 instanceof PendingSelectionEntry.Folder folder2) { + return NaturalOrderComparator.INSTANCE.compare(folder1.filename(), folder2.filename()); + } else { + return -1; + } + } else { + return 0; + } + }; + } + +} diff --git a/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/select_replay/SelectReplayScreen.java similarity index 59% rename from src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java rename to src/main/java/com/moulberry/flashback/screen/select_replay/SelectReplayScreen.java index 2d5c792..cfaa966 100644 --- a/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/SelectReplayScreen.java @@ -1,44 +1,77 @@ -package com.moulberry.flashback.screen; +package com.moulberry.flashback.screen.select_replay; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.screen.ConfigScreen; +import com.moulberry.flashback.screen.ReplaySummary; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.CycleButton; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import org.jetbrains.annotations.Nullable; +import java.nio.file.Path; + public class SelectReplayScreen extends Screen { protected final Screen lastScreen; + public final Path path; private Button selectButton; private Button editButton; private Button deleteButton; protected EditBox searchBox; private ReplaySelectionList list; - public SelectReplayScreen(Screen screen) { + public SelectReplayScreen(Screen screen, Path path) { super(Component.translatable("flashback.select_replay")); this.lastScreen = screen; + this.path = path; } @Override protected void init() { - this.searchBox = new EditBox(this.font, this.width / 2 - 100, 22, 200, 20, this.searchBox, Component.translatable("selectWorld.search")); - this.searchBox.setResponder(string -> this.list.updateFilter(string)); + this.searchBox = new EditBox(this.font, this.width / 2 - 128, 22, 126, 20, this.searchBox, Component.translatable("selectWorld.search")); + this.searchBox.setResponder(string -> { + FlashbackConfig config = Flashback.getConfig(); + this.list.updateFilter(string, config.replaySorting, config.sortDescending); + }); this.addWidget(this.searchBox); + + FlashbackConfig config = Flashback.getConfig(); + + this.addRenderableWidget(CycleButton.builder(ReplaySorting::component) + .withValues(ReplaySorting.values()) + .withInitialValue(config.replaySorting) + .create(this.width / 2 + 2, 22, 125, 20, Component.literal("Sort"), (button, sorting) -> { + FlashbackConfig configuration = Flashback.getConfig(); + configuration.replaySorting = sorting; + configuration.delayedSaveToDefaultFolder(); + this.list.updateFilter(this.searchBox.getValue(), configuration.replaySorting, configuration.sortDescending); + }) + ); + + this.addRenderableWidget(new SortDirectionButton(this.width / 2 + 131, 22, 20, 20, Component.literal("Sort Direction"), + sortDescending -> { + FlashbackConfig configuration = Flashback.getConfig(); + configuration.sortDescending = sortDescending; + configuration.delayedSaveToDefaultFolder(); + this.list.updateFilter(this.searchBox.getValue(), configuration.replaySorting, configuration.sortDescending); + }, config.sortDescending)); + this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft, - this.width, this.height - 112, 48, 36, this.searchBox.getValue(), this.list)); + this.width, this.height - 112, 48, 36, this.searchBox.getValue(), config.replaySorting, config.sortDescending, this.list)); this.selectButton = this.addRenderableWidget(Button.builder(Component.translatable("flashback.select_replay.open"), this::tryOpenReplay) - .bounds(this.width / 2 - 154, this.height - 52, 308, 20).build()); + .bounds(this.width / 2 - 151, this.height - 52, 302, 20).build()); this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay) - .bounds(this.width / 2 - 154, this.height - 28, 97, 20).build()); + .bounds(this.width / 2 - 151, this.height - 28, 98, 20).build()); this.deleteButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.delete"), this::tryDeleteReplay) .bounds(this.width / 2 - 49, this.height - 28, 98, 20).build()); this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, button -> this.minecraft.setScreen(this.lastScreen)) - .bounds(this.width / 2 + 57, this.height - 28, 97, 20).build()); + .bounds(this.width / 2 + 53, this.height - 28, 98, 20).build()); if (this.width/2 > 154 + 128) { this.addRenderableWidget(Button.builder(Component.literal("Flashback Settings"), btn -> Minecraft.getInstance().setScreen(new ConfigScreen(this))) @@ -83,26 +116,26 @@ public class SelectReplayScreen extends Screen { @Override public void removed() { if (this.list != null) { - this.list.children().forEach(ReplaySelectionList.Entry::close); + this.list.clearEntries(); } } private void tryOpenReplay(Button button) { - ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry(); + ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry(); if (entry != null) { entry.openReplay(); } } private void tryEditReplay(Button button) { - ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry(); + ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry(); if (entry != null) { entry.editReplay(); } } private void tryDeleteReplay(Button button) { - ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry(); + ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry(); if (entry != null) { entry.deleteReplay(); } diff --git a/src/main/java/com/moulberry/flashback/screen/select_replay/SortDirectionButton.java b/src/main/java/com/moulberry/flashback/screen/select_replay/SortDirectionButton.java new file mode 100644 index 0000000..5825552 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/select_replay/SortDirectionButton.java @@ -0,0 +1,50 @@ +package com.moulberry.flashback.screen.select_replay; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +import java.util.function.Consumer; + +public class SortDirectionButton extends Button { + + private static final ResourceLocation DOWN_ARROW = ResourceLocation.parse("flashback:down_arrow.png"); + private static final ResourceLocation UP_ARROW = ResourceLocation.parse("flashback:up_arrow.png"); + + public boolean sortDescending; + + public SortDirectionButton(int x, int y, int width, int height, Component component, Consumer changed, boolean initialSortDescending) { + super(x, y, width, height, component, button -> { + SortDirectionButton sortButton = (SortDirectionButton) button; + sortButton.sortDescending = !sortButton.sortDescending; + changed.accept(sortButton.sortDescending); + }, DEFAULT_NARRATION); + this.sortDescending = initialSortDescending; + } + + @Override + protected void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { + super.renderWidget(guiGraphics, i, j, f); + + final int size = 16; + int paddingX = (this.getWidth() - size) / 2; + int paddingY = (this.getHeight() - size) / 2; + + int x = this.getX() + paddingX; + int y = this.getY() + paddingY; + + if (this.sortDescending) { + guiGraphics.blit(RenderType::guiTextured, DOWN_ARROW, x, y, 0f, 0f, size, size, size, size); + } else { + guiGraphics.blit(RenderType::guiTextured, UP_ARROW, x, y, 0f, 0f, size, size, size, size); + } + } + + @Override + public void renderString(GuiGraphics guiGraphics, Font font, int i) { + } + +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorScene.java b/src/main/java/com/moulberry/flashback/state/EditorScene.java new file mode 100644 index 0000000..04853f7 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorScene.java @@ -0,0 +1,90 @@ +package com.moulberry.flashback.state; + +import com.moulberry.flashback.keyframe.Keyframe; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +public class EditorScene { + + public String name; + public final List keyframeTracks = new ArrayList<>(); + public int exportStartTicks = -1; + public int exportEndTicks = -1; + + private final EditorSceneHistory history = new EditorSceneHistory(); + + public EditorScene(String name) { + this.name = name; + } + + public void setKeyframe(int trackIndex, int tick, Keyframe keyframe) { + if (trackIndex >= this.keyframeTracks.size()) { + return; + } + + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + String description; + + KeyframeTrack track = this.keyframeTracks.get(trackIndex); + Keyframe old = track.keyframesByTick.get(tick); + if (old != null) { + undo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy())); + description = "Replaced " + track.keyframeType.name() + " keyframe"; + } else { + undo.add(new EditorSceneHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick)); + description = "Added " + track.keyframeType.name() + " keyframe"; + } + redo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, keyframe.copy())); + + this.push(new EditorSceneHistoryEntry(undo, redo, description)); + } + + public void push(EditorSceneHistoryEntry entry) { + if (entry.undo().isEmpty() && entry.redo().isEmpty()) { + return; + } + + this.history.push(this, entry); + } + + public void undo(Consumer descriptionConsumer) { + this.history.undo(this, descriptionConsumer); + } + + public void redo(Consumer descriptionConsumer) { + this.history.redo(this, descriptionConsumer); + } + + public void setExportTicks(int start, int end, int totalTicks) { + if (this.exportEndTicks < 0) { + this.exportEndTicks = totalTicks; + } + this.exportStartTicks = Math.max(0, Math.min(totalTicks, this.exportStartTicks)); + this.exportEndTicks = Math.max(0, Math.min(totalTicks, this.exportEndTicks)); + + if (start >= 0) { + this.exportStartTicks = start; + if (this.exportEndTicks < start) { + this.exportEndTicks = start; + } + } + + if (end >= 0) { + this.exportEndTicks = end; + if (this.exportStartTicks > end) { + this.exportStartTicks = end; + } + } + + if (this.exportStartTicks <= 0 && this.exportEndTicks >= totalTicks) { + this.exportStartTicks = -1; + this.exportEndTicks = -1; + } + } + + +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateHistory.java b/src/main/java/com/moulberry/flashback/state/EditorSceneHistory.java similarity index 57% rename from src/main/java/com/moulberry/flashback/state/EditorStateHistory.java rename to src/main/java/com/moulberry/flashback/state/EditorSceneHistory.java index 3307fba..0efda64 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorStateHistory.java +++ b/src/main/java/com/moulberry/flashback/state/EditorSceneHistory.java @@ -4,12 +4,12 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; -public class EditorStateHistory { +public class EditorSceneHistory { - private final List entries = new ArrayList<>(); + private final List entries = new ArrayList<>(); private int position = 0; - public void push(EditorState editorState, EditorStateHistoryEntry entry) { + public void push(EditorScene editorScene, EditorSceneHistoryEntry entry) { while (this.entries.size() > this.position) { this.entries.removeLast(); } @@ -18,35 +18,35 @@ public class EditorStateHistory { this.position -= 1; } - for (EditorStateHistoryAction redo : entry.redo()) { - redo.apply(editorState); + for (EditorSceneHistoryAction redo : entry.redo()) { + redo.apply(editorScene); } this.entries.add(entry); this.position += 1; } - public void undo(EditorState editorState, Consumer descriptionConsumer) { + public void undo(EditorScene editorScene, Consumer descriptionConsumer) { if (this.position == 0) { return; } this.position -= 1; - EditorStateHistoryEntry entry = this.entries.get(this.position); - for (EditorStateHistoryAction undo : entry.undo()) { - undo.apply(editorState); + EditorSceneHistoryEntry entry = this.entries.get(this.position); + for (EditorSceneHistoryAction undo : entry.undo()) { + undo.apply(editorScene); } descriptionConsumer.accept("Undo '" + entry.description() + "'"); } - public void redo(EditorState editorState, Consumer descriptionConsumer) { + public void redo(EditorScene editorScene, Consumer descriptionConsumer) { if (this.position >= this.entries.size()) { return; } - EditorStateHistoryEntry entry = this.entries.get(this.position); - for (EditorStateHistoryAction redo : entry.redo()) { - redo.apply(editorState); + EditorSceneHistoryEntry entry = this.entries.get(this.position); + for (EditorSceneHistoryAction redo : entry.redo()) { + redo.apply(editorScene); } descriptionConsumer.accept("Redo '" + entry.description() + "'"); diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateHistoryAction.java b/src/main/java/com/moulberry/flashback/state/EditorSceneHistoryAction.java similarity index 86% rename from src/main/java/com/moulberry/flashback/state/EditorStateHistoryAction.java rename to src/main/java/com/moulberry/flashback/state/EditorSceneHistoryAction.java index 44a6243..385d74a 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorStateHistoryAction.java +++ b/src/main/java/com/moulberry/flashback/state/EditorSceneHistoryAction.java @@ -12,15 +12,15 @@ import com.moulberry.flashback.keyframe.KeyframeType; import java.lang.reflect.Type; -public interface EditorStateHistoryAction { +public interface EditorSceneHistoryAction { - void apply(EditorState editorState); + void apply(EditorScene editorScene); - record SetKeyframe(KeyframeType type, int trackIndex, int tick, Keyframe keyframe) implements EditorStateHistoryAction { + record SetKeyframe(KeyframeType type, int trackIndex, int tick, Keyframe keyframe) implements EditorSceneHistoryAction { @Override - public void apply(EditorState editorState) { - if (this.trackIndex < editorState.keyframeTracks.size()) { - KeyframeTrack track = editorState.keyframeTracks.get(this.trackIndex); + public void apply(EditorScene editorScene) { + if (this.trackIndex < editorScene.keyframeTracks.size()) { + KeyframeTrack track = editorScene.keyframeTracks.get(this.trackIndex); if (track.keyframeType == this.type) { track.keyframesByTick.put(this.tick, this.keyframe.copy()); } @@ -51,11 +51,11 @@ public interface EditorStateHistoryAction { } } - record RemoveKeyframe(KeyframeType type, int trackIndex, int tick) implements EditorStateHistoryAction { + record RemoveKeyframe(KeyframeType type, int trackIndex, int tick) implements EditorSceneHistoryAction { @Override - public void apply(EditorState editorState) { - if (this.trackIndex < editorState.keyframeTracks.size()) { - KeyframeTrack track = editorState.keyframeTracks.get(this.trackIndex); + public void apply(EditorScene editorScene) { + if (this.trackIndex < editorScene.keyframeTracks.size()) { + KeyframeTrack track = editorScene.keyframeTracks.get(this.trackIndex); if (track.keyframeType == this.type) { track.keyframesByTick.remove(this.tick); } @@ -84,11 +84,11 @@ public interface EditorStateHistoryAction { } } - record AddTrack(KeyframeType type, int trackIndex) implements EditorStateHistoryAction { + record AddTrack(KeyframeType type, int trackIndex) implements EditorSceneHistoryAction { @Override - public void apply(EditorState editorState) { - if (this.trackIndex <= editorState.keyframeTracks.size()) { - editorState.keyframeTracks.add(this.trackIndex, new KeyframeTrack(this.type)); + public void apply(EditorScene editorScene) { + if (this.trackIndex <= editorScene.keyframeTracks.size()) { + editorScene.keyframeTracks.add(this.trackIndex, new KeyframeTrack(this.type)); } } @@ -112,13 +112,13 @@ public interface EditorStateHistoryAction { } } - record RemoveTrack(KeyframeType type, int trackIndex) implements EditorStateHistoryAction { + record RemoveTrack(KeyframeType type, int trackIndex) implements EditorSceneHistoryAction { @Override - public void apply(EditorState editorState) { - if (this.trackIndex < editorState.keyframeTracks.size()) { - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.trackIndex); + public void apply(EditorScene editorScene) { + if (this.trackIndex < editorScene.keyframeTracks.size()) { + KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(this.trackIndex); if (keyframeTrack.keyframeType == type) { - editorState.keyframeTracks.remove(this.trackIndex); + editorScene.keyframeTracks.remove(this.trackIndex); } } } @@ -143,9 +143,9 @@ public interface EditorStateHistoryAction { } } - class TypeAdapter implements JsonSerializer, JsonDeserializer { + class TypeAdapter implements JsonSerializer, JsonDeserializer { @Override - public EditorStateHistoryAction deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + public EditorSceneHistoryAction deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); String type = jsonObject.get("action_type").getAsString(); return switch (type) { @@ -158,7 +158,7 @@ public interface EditorStateHistoryAction { } @Override - public JsonElement serialize(EditorStateHistoryAction src, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(EditorSceneHistoryAction src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject; switch (src) { case SetKeyframe setKeyframe -> { diff --git a/src/main/java/com/moulberry/flashback/state/EditorSceneHistoryEntry.java b/src/main/java/com/moulberry/flashback/state/EditorSceneHistoryEntry.java new file mode 100644 index 0000000..9b3add8 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorSceneHistoryEntry.java @@ -0,0 +1,6 @@ +package com.moulberry.flashback.state; + +import java.util.List; + +public record EditorSceneHistoryEntry(List undo, List redo, String description) { +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java index a6283b0..cc611d0 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorState.java +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -35,14 +35,13 @@ public class EditorState { transient boolean dirty = false; public transient int modCount = ThreadLocalRandom.current().nextInt(); - public final List keyframeTracks = new ArrayList<>(); public final ReplayVisuals replayVisuals = new ReplayVisuals(); - private final EditorStateHistory history = new EditorStateHistory(); + + public final List scenes; + public int sceneIndex = 0; public double zoomMin = 0.0; public double zoomMax = 1.0; - public int exportStartTicks = -1; - public int exportEndTicks = -1; public UUID audioSourceEntity = null; public Set hideDuringExport = new HashSet<>(); @@ -50,105 +49,16 @@ public class EditorState { public Map skinOverride = new HashMap<>(); public Map nameOverride = new HashMap<>(); - public transient int recordingCameraMovementTrack = -1; - public transient int recordingCameraMovementMinTick = -1; - public transient int recordingCameraMovementMaxTick = -1; - public transient Int2ObjectMap recordingCameraKeyframes = new Int2ObjectOpenHashMap<>(); - - public void recordCameraMovement() { - if (recordingCameraMovementTrack < 0) { - return; - } - - if (!ReplayUI.recordCameraMovement) { - finishRecordingCameraMovement(); - return; - } - - ReplayServer replayServer = Flashback.getReplayServer(); - if (replayServer != null) { - if (replayServer.replayPaused) { - finishRecordingCameraMovement(); - return; - } - - Entity cameraEntity = Minecraft.getInstance().getCameraEntity(); - if (cameraEntity == null) { - return; - } - - int tick = replayServer.getReplayTick(); - if (recordingCameraMovementMaxTick >= 0) { - int nextCapture = recordingCameraMovementMaxTick + 4; - if (tick >= nextCapture) { - tick = nextCapture; - } else { - return; - } - } - - recordingCameraKeyframes.put(tick, new CameraKeyframe(Minecraft.getInstance().getCameraEntity())); - - if (recordingCameraMovementMinTick < 0) { - recordingCameraMovementMinTick = tick; - } - - recordingCameraMovementMinTick = Math.min(recordingCameraMovementMinTick, tick); - recordingCameraMovementMaxTick = Math.max(recordingCameraMovementMaxTick, tick); - } + public EditorState() { + this.scenes = new ArrayList<>(); + this.scenes.add(new EditorScene("Scene 1")); } - public void finishRecordingCameraMovement() { - int trackIndex = recordingCameraMovementTrack; - if (trackIndex >= 0 && trackIndex < this.keyframeTracks.size()) { - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); - - KeyframeTrack track = this.keyframeTracks.get(trackIndex); - - for (Int2ObjectMap.Entry entry : recordingCameraKeyframes.int2ObjectEntrySet()) { - int tick = entry.getIntKey(); - - Keyframe old = track.keyframesByTick.get(entry.getIntKey()); - if (old != null) { - undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy())); - } else { - undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick)); - } - redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, entry.getValue())); - } - - this.push(new EditorStateHistoryEntry(undo, redo, "Record movement as keyframes")); + public EditorScene currentScene() { + if (this.scenes.isEmpty()) { + this.scenes.add(new EditorScene("Scene 1")); } - - recordingCameraMovementTrack = -1; - recordingCameraMovementMinTick = -1; - recordingCameraMovementMaxTick = -1; - recordingCameraKeyframes.clear(); - } - - public void setKeyframe(int trackIndex, int tick, Keyframe keyframe) { - if (trackIndex >= this.keyframeTracks.size()) { - return; - } - - List undo = new ArrayList<>(); - List redo = new ArrayList<>(); - - String description; - - KeyframeTrack track = this.keyframeTracks.get(trackIndex); - Keyframe old = track.keyframesByTick.get(tick); - if (old != null) { - undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy())); - description = "Replaced " + track.keyframeType.name() + " keyframe"; - } else { - undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick)); - description = "Added " + track.keyframeType.name() + " keyframe"; - } - redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, keyframe.copy())); - - this.push(new EditorStateHistoryEntry(undo, redo, description)); + return this.scenes.get(this.sceneIndex); } @Nullable @@ -173,54 +83,6 @@ public class EditorState { return dummyCamera; } - public void push(EditorStateHistoryEntry entry) { - if (entry.undo().isEmpty() && entry.redo().isEmpty()) { - return; - } - - this.history.push(this, entry); - this.markDirty(); - } - - public void undo(Consumer descriptionConsumer) { - this.history.undo(this, descriptionConsumer); - this.markDirty(); - } - - public void redo(Consumer descriptionConsumer) { - this.history.redo(this, descriptionConsumer); - this.markDirty(); - } - - public void setExportTicks(int start, int end, int totalTicks) { - if (this.exportEndTicks < 0) { - this.exportEndTicks = totalTicks; - } - this.exportStartTicks = Math.max(0, Math.min(totalTicks, this.exportStartTicks)); - this.exportEndTicks = Math.max(0, Math.min(totalTicks, this.exportEndTicks)); - - if (start >= 0) { - this.exportStartTicks = start; - if (this.exportEndTicks < start) { - this.exportEndTicks = start; - } - } - - if (end >= 0) { - this.exportEndTicks = end; - if (this.exportStartTicks > end) { - this.exportStartTicks = end; - } - } - - if (this.exportStartTicks <= 0 && this.exportEndTicks >= totalTicks) { - this.exportStartTicks = -1; - this.exportEndTicks = -1; - } - - this.dirty = true; - } - public void markDirty() { this.dirty = true; this.modCount += 1; @@ -264,7 +126,7 @@ public class EditorState { public void applyKeyframes(KeyframeHandler keyframeHandler, float tick) { Set> applied = new HashSet<>(); - for (KeyframeTrack keyframeTrack : this.keyframeTracks) { + for (KeyframeTrack keyframeTrack : this.currentScene().keyframeTracks) { // Ignore lines that are disabled if (!keyframeTrack.enabled) { continue; diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateHistoryEntry.java b/src/main/java/com/moulberry/flashback/state/EditorStateHistoryEntry.java deleted file mode 100644 index 7a4d2e6..0000000 --- a/src/main/java/com/moulberry/flashback/state/EditorStateHistoryEntry.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.moulberry.flashback.state; - -import java.util.List; - -public record EditorStateHistoryEntry(List undo, List redo, String description) { -} diff --git a/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java b/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java index 592296c..63ac491 100644 --- a/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java +++ b/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java @@ -10,6 +10,7 @@ import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import com.moulberry.flashback.keyframe.interpolation.SidedInterpolationType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; +import imgui.type.ImString; import java.util.Map; import java.util.TreeMap; @@ -19,6 +20,12 @@ public class KeyframeTrack { public final KeyframeType keyframeType; public TreeMap keyframesByTick = new TreeMap<>(); public boolean enabled = true; + public String customName = null; + public int customColour = 0; + + public transient ImString nameEditField = null; + public transient boolean forceFocusTrack = false; + public transient float animatedOffsetInUi = 0.0f; public KeyframeTrack(KeyframeType keyframeType) { this.keyframeType = keyframeType; diff --git a/src/main/java/com/moulberry/flashback/visuals/CameraPath.java b/src/main/java/com/moulberry/flashback/visuals/CameraPath.java index 4b8c486..aa62d72 100644 --- a/src/main/java/com/moulberry/flashback/visuals/CameraPath.java +++ b/src/main/java/com/moulberry/flashback/visuals/CameraPath.java @@ -20,6 +20,7 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType; import com.moulberry.flashback.keyframe.types.FOVKeyframeType; import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.state.EditorScene; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.KeyframeTrack; @@ -58,7 +59,7 @@ public class CameraPath { int replayTick = TimelineWindow.getCursorTick(); if (lastEditorStateModCount != state.modCount || lastCursorTick != replayTick) { - CameraPathArgs cameraPathArgs = createCameraPathArgs(state, replayTick, SUPPORTED_CAMERA_KEYFRAMES); + CameraPathArgs cameraPathArgs = createCameraPathArgs(state.currentScene(), replayTick, SUPPORTED_CAMERA_KEYFRAMES); if (lastEditorStateModCount != state.modCount || !cameraPathArgs.equals(lastCameraPathArgs)) { lastCameraPathArgs = cameraPathArgs; @@ -134,12 +135,12 @@ public class CameraPath { private record CameraPathArgs(int lastLastCameraTick, int lastCameraTick, int nextCameraTick, int nextNextCameraTick) {} - private static CameraPathArgs createCameraPathArgs(EditorState state, int replayTick, Set> supportedKeyframes) { + private static CameraPathArgs createCameraPathArgs(EditorScene scene, int replayTick, Set> supportedKeyframes) { int lastCameraTick = -1; int nextCameraTick = -1; - for (int trackIndex = 0; trackIndex < state.keyframeTracks.size(); trackIndex++) { - KeyframeTrack keyframeTrack = state.keyframeTracks.get(trackIndex); + for (int trackIndex = 0; trackIndex < scene.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = scene.keyframeTracks.get(trackIndex); if (keyframeTrack.enabled && supportedKeyframes.contains(keyframeTrack.keyframeType) && !keyframeTrack.keyframesByTick.isEmpty()) { var lastEntry = keyframeTrack.keyframesByTick.floorEntry(replayTick); var nextEntry = keyframeTrack.keyframesByTick.ceilingEntry(replayTick + 1); @@ -160,8 +161,8 @@ public class CameraPath { int lastLastCameraTick = -1; int nextNextCameraTick = -1; - for (int trackIndex = 0; trackIndex < state.keyframeTracks.size(); trackIndex++) { - KeyframeTrack keyframeTrack = state.keyframeTracks.get(trackIndex); + for (int trackIndex = 0; trackIndex < scene.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = scene.keyframeTracks.get(trackIndex); if (keyframeTrack.enabled && supportedKeyframes.contains(keyframeTrack.keyframeType) && !keyframeTrack.keyframesByTick.isEmpty()) { var lastLastEntry = lastCameraTick == -1 ? null : keyframeTrack.keyframesByTick.floorEntry(lastCameraTick - 1); var nextNextEntry = nextCameraTick == -1 ? null : keyframeTrack.keyframesByTick.ceilingEntry(nextCameraTick + 1); diff --git a/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java b/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java index 4f4276d..6bf3647 100644 --- a/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java +++ b/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java @@ -35,6 +35,8 @@ public class CameraRotation { ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer != null && visuals.overrideCameraShake && (Flashback.isExporting() || !replayServer.replayPaused)) { float tick = Flashback.isExporting() ? (float) Flashback.EXPORT_JOB.getCurrentTickDouble() : replayServer.getPartialReplayTick(); + float speedFactor = 20.0f / replayServer.getDesiredTickRate(false); + if (tick < lastShakeReplayTick) { lastShakeReplayTick = tick; shakeTimeY = 0.0f; @@ -43,8 +45,8 @@ public class CameraRotation { float yFrequency = visuals.cameraShakeYFrequency; float xFrequency = visuals.cameraShakeXFrequency; - shakeTimeY += (tick - lastShakeReplayTick) * yFrequency * 2.0f; - shakeTimeX += (tick - lastShakeReplayTick) * xFrequency * 2.0f; + shakeTimeY += (tick - lastShakeReplayTick) * speedFactor * yFrequency * 2.0f; + shakeTimeX += (tick - lastShakeReplayTick) * speedFactor * xFrequency * 2.0f; lastShakeReplayTick = tick; } diff --git a/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java b/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java index ac9e05d..b0061f9 100644 --- a/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java +++ b/src/main/java/com/moulberry/flashback/visuals/ShaderManager.java @@ -6,8 +6,6 @@ import net.minecraft.client.renderer.ShaderDefines; import net.minecraft.client.renderer.ShaderProgram; import net.minecraft.resources.ResourceLocation; -import java.io.IOException; - public class ShaderManager { public static final ShaderManager INSTANCE = new ShaderManager(); diff --git a/src/main/resources/assets/flashback/down_arrow.png b/src/main/resources/assets/flashback/down_arrow.png new file mode 100644 index 0000000..eaa853d Binary files /dev/null and b/src/main/resources/assets/flashback/down_arrow.png differ diff --git a/src/main/resources/assets/flashback/materialiconsround-regular.otf b/src/main/resources/assets/flashback/materialiconsround-regular.otf new file mode 100644 index 0000000..dacf094 Binary files /dev/null and b/src/main/resources/assets/flashback/materialiconsround-regular.otf differ diff --git a/src/main/resources/assets/flashback/textures/gui/sprites/folder.png b/src/main/resources/assets/flashback/textures/gui/sprites/folder.png new file mode 100644 index 0000000..183d77b Binary files /dev/null and b/src/main/resources/assets/flashback/textures/gui/sprites/folder.png differ diff --git a/src/main/resources/assets/flashback/up_arrow.png b/src/main/resources/assets/flashback/up_arrow.png new file mode 100644 index 0000000..09b8309 Binary files /dev/null and b/src/main/resources/assets/flashback/up_arrow.png differ