Public Release

This commit is contained in:
Moulberry committed 2024-08-24 04:41:01 +08:00
1 parent 666398e480
commit 61bb497a22
126 files changed
+8435 -1240

No files matched your search

@@ -1,26 +1,46 @@
package com.moulberry.flashback;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.realmsclient.RealmsMainScreen;
import com.mojang.serialization.Lifecycle;
import com.moulberry.flashback.action.*;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.packet.FlashbackClearParticles;
import com.moulberry.flashback.packet.FinishedServerTick;
import com.moulberry.flashback.packet.FlashbackForceClientTick;
import com.moulberry.flashback.packet.FlashbackInstantlyLerp;
import com.moulberry.flashback.playback.EmptyLevelSource;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.record.Recorder;
import com.moulberry.flashback.record.ReplayExporter;
import com.moulberry.flashback.screen.ConfigScreen;
import com.moulberry.flashback.screen.SaveReplayScreen;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.FileUtil;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.client.gui.screens.PauseScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.commands.Commands;
import net.minecraft.core.*;
import net.minecraft.core.registries.Registries;
@@ -31,6 +51,9 @@ import net.minecraft.server.*;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.*;
import net.minecraft.world.level.biome.Biome;
@@ -48,12 +71,20 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class Flashback implements ModInitializer, ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("flashback");
@@ -61,12 +92,26 @@ public class Flashback implements ModInitializer, ClientModInitializer {
public static final int MAGIC = 0xD780E884;
public static Recorder RECORDER = null;
public static ExportJob EXPORT_JOB = null;
private static FlashbackConfig config;
private static Path configDirectory = null;
private static int delayedStartRecording = 0;
private static boolean delayedOpenConfig = false;
private static final List<Path> pendingReplaySave = new ArrayList<>();
public static ResourceLocation createResourceLocation(String value) {
return ResourceLocation.fromNamespaceAndPath("flashback", value);
}
public static Path getDataDirectory() {
return FabricLoader.getInstance().getGameDir().resolve("flashback");
}
public static Path getReplayFolder() {
return Flashback.getDataDirectory().resolve("replays");
}
public static Path getConfigDirectory() {
if (configDirectory == null) {
configDirectory = FabricLoader.getInstance().getConfigDir().resolve("flashback");
@@ -81,19 +126,57 @@ public class Flashback implements ModInitializer, ClientModInitializer {
@Override
public void onInitialize() {
net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry.playS2C().register(FinishedServerTick.TYPE,
PayloadTypeRegistry.playS2C().register(FinishedServerTick.TYPE,
StreamCodec.unit(FinishedServerTick.INSTANCE));
PayloadTypeRegistry.playS2C().register(FlashbackForceClientTick.TYPE, StreamCodec.unit(FlashbackForceClientTick.INSTANCE));
ClientPlayNetworking.registerGlobalReceiver(FlashbackForceClientTick.TYPE, (payload, context) -> {
if (Flashback.isInReplay()) {
Minecraft.getInstance().tick();
}
});
PayloadTypeRegistry.playS2C().register(FlashbackClearParticles.TYPE, StreamCodec.unit(FlashbackClearParticles.INSTANCE));
ClientPlayNetworking.registerGlobalReceiver(FlashbackClearParticles.TYPE, (payload, context) -> {
if (Flashback.isInReplay()) {
Minecraft.getInstance().particleEngine.clearParticles();
}
});
PayloadTypeRegistry.playS2C().register(FlashbackInstantlyLerp.TYPE, StreamCodec.unit(FlashbackInstantlyLerp.INSTANCE));
ClientPlayNetworking.registerGlobalReceiver(FlashbackInstantlyLerp.TYPE, (payload, context) -> {
if (Flashback.isInReplay()) {
for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) {
if (entity instanceof LivingEntity && !entity.isRemoved() && !(entity instanceof LocalPlayer)) {
entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(),
entity.lerpTargetYRot(), entity.lerpTargetXRot());
}
entity.setOldPosAndRot();
}
}
});
}
@Override
public void onInitializeClient() {
// todo: try recover unfinished recordings
Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback");
try {
Files.createDirectories(configFolder);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to create config folder", e);
}
config = FlashbackConfig.tryLoadFromFolder(configFolder);
// todo: try recover unfinished recordings
TempFolderProvider.tryDeleteStaleFolders();
try {
FileUtils.deleteDirectory(Path.of("replay_export_temp").toFile());
} catch (Exception ignored) {}
this.deleteUnusedReplayStates();
ActionRegistry.register(ActionNextTick.INSTANCE);
ActionRegistry.register(ActionGamePacket.INSTANCE);
ActionRegistry.register(ActionConfigurationPacket.INSTANCE);
@@ -104,11 +187,142 @@ public class Flashback implements ModInitializer, ClientModInitializer {
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
var flashback = ClientCommandManager.literal("flashback");
flashback.then(ClientCommandManager.literal("start").executes(this::startRecordingReplay));
flashback.then(ClientCommandManager.literal("finish").executes(this::finishRecordingReplay));
flashback.then(ClientCommandManager.literal("end").executes(this::finishRecordingReplay));
flashback.then(ClientCommandManager.literal("config").executes(this::openFlashbackConfig));
dispatcher.register(flashback);
});
ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {
if (!Flashback.isInReplay() && Flashback.getConfig().automaticallyStart && RECORDER == null) {
delayedStartRecording = 20;
}
});
ClientTickEvents.START_CLIENT_TICK.register(tick -> {
if (!pendingReplaySave.isEmpty()) {
Screen currentScreen = Minecraft.getInstance().screen;
if (currentScreen == null || currentScreen instanceof PauseScreen || currentScreen instanceof TitleScreen
|| currentScreen instanceof RealmsMainScreen || currentScreen instanceof JoinMultiplayerScreen) {
Path recordFolder = pendingReplaySave.getFirst();
LocalDateTime dateTime = LocalDateTime.now();
dateTime = dateTime.withNano(0);
Minecraft.getInstance().setScreen(new SaveReplayScreen(Minecraft.getInstance().screen,
recordFolder, dateTime.toString()));
}
}
if (Minecraft.getInstance().level != null && delayedStartRecording > 0) {
IntegratedServer integratedServer = Minecraft.getInstance().getSingleplayerServer();
if (integratedServer != null && integratedServer.getClass() != IntegratedServer.class) {
delayedStartRecording = 0; // Only allow on actual integrated servers, not replay servers or any other custom server a mod might spin up
} else if (Flashback.getConfig().automaticallyStart && RECORDER == null) {
delayedStartRecording -= 1;
if (delayedStartRecording == 0) {
startRecordingReplay();
}
} else {
delayedStartRecording = 0;
}
}
if (delayedOpenConfig) {
if (Minecraft.getInstance().screen == null) {
Minecraft.getInstance().setScreen(new ConfigScreen(null));
}
delayedOpenConfig = false;
}
});
}
private void deleteUnusedReplayStates() {
Path flashbackDir = Flashback.getDataDirectory();
Path replayDir = flashbackDir.resolve("replays");
Path replayStatesDir = flashbackDir.resolve("editor_states");
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
return;
}
if (!Files.exists(replayStatesDir) || !Files.isDirectory(replayStatesDir)) {
return;
}
CompletableFuture.runAsync(() -> {
Map<UUID, Path> replayStates = new HashMap<>();
// Find existing replay states
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayStatesDir)) {
for (Path path : directoryStream) {
String filename = path.getFileName().toString();
String withoutExtension = null;
if (filename.endsWith(".json")) {
withoutExtension = filename.substring(0, filename.length() - 5);
} else if (filename.endsWith(".json.old")) {
withoutExtension = filename.substring(0, filename.length() - 9);
}
if (withoutExtension != null) {
UUID uuid;
try {
uuid = UUID.fromString(withoutExtension);
} catch (Exception ignored) {
continue;
}
replayStates.put(uuid, path);
}
}
} catch (IOException ignored) {}
// Find which uuids are still valid because they have replays
Set<UUID> replayUuids = new HashSet<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayDir)) {
for (Path path : directoryStream) {
if (!path.toString().endsWith(".zip")) {
continue;
}
String metadataString = null;
try (FileSystem fs = FileSystems.newFileSystem(path)) {
Path metadataPath = fs.getPath("/metadata.json");
if (Files.exists(metadataPath)) {
metadataString = Files.readString(metadataPath);
}
} catch (IOException ignored) {
continue;
}
if (metadataString != null) {
JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class);
FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson);
if (metadata != null) {
replayUuids.add(metadata.replayIdentifier);
}
}
}
} catch (IOException e) {
Flashback.LOGGER.error("Unable to iterate replay directory", e);
return;
}
for (Map.Entry<UUID, Path> entry : replayStates.entrySet()) {
if (!replayUuids.contains(entry.getKey())) {
try {
Files.deleteIfExists(entry.getValue());
} catch (IOException ignored) {}
}
}
}, Util.backgroundExecutor());
}
public static FlashbackConfig getConfig() {
return config;
}
@Nullable
public static ReplayServer getReplayServer() {
if (Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer replayServer) {
@@ -117,6 +331,14 @@ public class Flashback implements ModInitializer, ClientModInitializer {
return null;
}
public static void removePendingReplaySave(Path recordFolder) {
pendingReplaySave.remove(recordFolder);
}
public static boolean isExporting() {
return EXPORT_JOB != null && EXPORT_JOB.isRunning();
}
public static boolean isInReplay() {
return Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer;
}
@@ -131,6 +353,11 @@ public class Flashback implements ModInitializer, ClientModInitializer {
return 0;
}
private int openFlashbackConfig(CommandContext<FabricClientCommandSource> command) {
delayedOpenConfig = true;
return 0;
}
public static void startRecordingReplay() {
if (RECORDER != null) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
@@ -138,29 +365,35 @@ public class Flashback implements ModInitializer, ClientModInitializer {
return;
}
RECORDER = new Recorder(Minecraft.getInstance().player.registryAccess());
if (FlashbackConfig.showRecordingToasts) {
if (Flashback.getConfig().showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Started Recording"), Component.literal("Started recording"));
Component.literal("Flashback"), Component.literal("Started recording"));
}
}
public static void pauseRecordingReplay(boolean pause) {
RECORDER.setPaused(pause);
if (FlashbackConfig.showRecordingToasts) {
if (Flashback.getConfig().showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Paused Recording"), Component.literal("Paused recording"));
Component.literal("Flashback"), Component.literal("Paused recording"));
}
}
public static void cancelRecordingReplay() {
Recorder recorder = RECORDER;
RECORDER = null;
recorder.finish(null);
if (FlashbackConfig.showRecordingToasts) {
Path recordFolder = recorder.finish();
try {
FileUtils.deleteDirectory(recordFolder.toFile());
} catch (Exception e) {
Flashback.LOGGER.error("Exception deleting record folder", e);
}
if (Flashback.getConfig().showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Cancelled Recording"), Component.literal("Cancelled recording"));
Component.literal("Flashback"), Component.literal("Cancelled recording"));
}
}
@@ -175,31 +408,28 @@ public class Flashback implements ModInitializer, ClientModInitializer {
RECORDER = null;
recorder.endTick(true);
Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback");
Path replayDir = flashbackDir.resolve("replays");
if (Flashback.getConfig().quicksave) {
Path replayDir = getReplayFolder();
try {
Files.createDirectories(replayDir);
} catch (IOException e) {
Flashback.LOGGER.error("Error while trying to create replay directory", e);
String filename;
try {
LocalDateTime dateTime = LocalDateTime.now();
dateTime = dateTime.withNano(0);
filename = FileUtil.findAvailableName(replayDir, dateTime.toString(), ".zip");
} catch (IOException e) {
Flashback.LOGGER.error("Error while trying to determine filename", e);
filename = UUID.randomUUID() + ".zip";
}
Path outputFile = replayDir.resolve(filename);
ReplayExporter.export(recorder.finish(), outputFile, null);
} else {
pendingReplaySave.add(recorder.finish());
}
String name;
try {
LocalDateTime dateTime = LocalDateTime.now();
dateTime = dateTime.withNano(0);
name = FileUtil.findAvailableName(replayDir, dateTime.toString(), ".zip");
Path outputFile = replayDir.resolve(name);
recorder.finish(outputFile);
} catch (IOException e) {
throw SneakyThrow.sneakyThrow(e);
}
if (FlashbackConfig.showRecordingToasts) {
if (Flashback.getConfig().showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Finished Recording"), Component.literal(name));
Component.literal("Flashback"), Component.literal("Finished recording"));
}
}
@@ -231,6 +461,14 @@ public class Flashback implements ModInitializer, ClientModInitializer {
GameRules gameRules = new GameRules();
gameRules.getRule(GameRules.RULE_DOMOBSPAWNING).set(false, null);
gameRules.getRule(GameRules.RULE_DOENTITYDROPS).set(false, null);
gameRules.getRule(GameRules.RULE_ANNOUNCE_ADVANCEMENTS).set(false, null);
gameRules.getRule(GameRules.RULE_DISABLE_RAIDS).set(true, null);
gameRules.getRule(GameRules.RULE_DO_PATROL_SPAWNING).set(false, null);
gameRules.getRule(GameRules.RULE_DO_WARDEN_SPAWNING).set(false, null);
gameRules.getRule(GameRules.RULE_DO_TRADER_SPAWNING).set(false, null);
gameRules.getRule(GameRules.RULE_DO_VINES_SPREAD).set(false, null);
gameRules.getRule(GameRules.RULE_DOFIRETICK).set(false, null);
gameRules.getRule(GameRules.RULE_WEATHER_CYCLE).set(false, null);
gameRules.getRule(GameRules.RULE_RANDOMTICKING).set(0, null);
@@ -4,11 +4,15 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.moulberry.flashback.keyframe.Keyframe;
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.TickrateKeyframe;
import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe;
import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe;
import com.moulberry.flashback.serialization.QuaternionTypeAdapater;
import com.moulberry.flashback.serialization.Vector3fTypeAdapater;
import com.moulberry.flashback.state.EditorStateHistoryAction;
import org.joml.Quaternionf;
import org.joml.Vector3f;
@@ -19,13 +23,23 @@ public class FlashbackGson {
private static GsonBuilder build() {
return new GsonBuilder()
.registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapater())
.registerTypeAdapter(Quaternionf.class, new QuaternionTypeAdapater())
.registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter())
.registerTypeAdapter(FOVKeyframe.class, new FOVKeyframe.TypeAdapter())
.registerTypeAdapter(TickrateKeyframe.class, new TickrateKeyframe.TypeAdapter())
.registerTypeAdapter(TimeOfDayKeyframe.class, new TimeOfDayKeyframe.TypeAdapter())
.registerTypeAdapter(Keyframe.class, new Keyframe.TypeAdapter());
.registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapater())
.registerTypeAdapter(Quaternionf.class, new QuaternionTypeAdapater())
.registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter())
.registerTypeAdapter(CameraOrbitKeyframe.class, new CameraOrbitKeyframe.TypeAdapter())
.registerTypeAdapter(FOVKeyframe.class, new FOVKeyframe.TypeAdapter())
.registerTypeAdapter(CameraShakeKeyframe.class, new CameraShakeKeyframe.TypeAdapter())
.registerTypeAdapter(TickrateKeyframe.class, new TickrateKeyframe.TypeAdapter())
.registerTypeAdapter(TimelapseKeyframe.class, new TimelapseKeyframe.TypeAdapter())
.registerTypeAdapter(TimeOfDayKeyframe.class, new TimeOfDayKeyframe.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());
}
}
@@ -1,5 +1,6 @@
package com.moulberry.flashback;
import net.minecraft.util.Mth;
import org.joml.Quaternionf;
public class Interpolation {
@@ -12,6 +13,11 @@ public class Interpolation {
return from + (to - from) * amount;
}
public static float linearAngle(float from, float to, float amount) {
return from + Mth.wrapDegrees(to - from) * amount;
}
public static Quaternionf linear(Quaternionf from, Quaternionf to, float amount) {
return from.slerp(to, amount, new Quaternionf());
}
@@ -1,11 +1,60 @@
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.VecDeltaCodec;
import net.minecraft.server.level.ServerEntity;
import net.minecraft.util.Mth;
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.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 java.util.ArrayList;
public class PacketHelper {
public static ClientboundAddEntityPacket createAddEntity(Entity entity) {
public static boolean shouldIgnoreEntity(Entity entity) {
return entity == null || entity.isRemoved() || entity instanceof EnderDragonPart || entity.getType().clientTrackingRange() <= 0;
}
public static Packet<ClientGamePacketListener> createAddEntity(Entity entity) {
ServerEntity serverEntity = null;
// Try to construct ServerEntity with dummy values
try {
serverEntity = new ServerEntity(null, entity, 1, false, packet -> {});
} catch (Exception e) {}
// Error while trying to construct, possibly mod incompatibility? Try bypassing the constructor
if (serverEntity == null) {
try {
serverEntity = (ServerEntity) UnsafeWrapper.UNSAFE.allocateInstance(ServerEntity.class);
serverEntity.positionCodec = new VecDeltaCodec();
serverEntity.lastPassengers = new ArrayList<>();
serverEntity.broadcast = packet -> {};
serverEntity.entity = entity;
serverEntity.positionCodec.setBase(entity.trackingPosition());
serverEntity.lastSentMovement = entity.getDeltaMovement();
serverEntity.lastSentYRot = Mth.floor((entity.getYRot() * 256.0f / 360.0f));
serverEntity.lastSentXRot = Mth.floor((entity.getXRot() * 256.0f / 360.0f));
serverEntity.lastSentYHeadRot = Mth.floor((entity.getYHeadRot() * 256.0f / 360.0f));
serverEntity.wasOnGround = entity.onGround();
serverEntity.trackedDataValues = entity.getEntityData().getNonDefaultValues();
} catch (Exception e) {}
}
try {
return entity.getAddEntityPacket(serverEntity);
} catch (Exception e) {}
return createAddEntity(entity, 0);
}
@@ -1,79 +0,0 @@
package com.moulberry.flashback;
import com.moulberry.flashback.combo_options.AspectRatio;
import com.moulberry.flashback.combo_options.Sizing;
import net.minecraft.client.Minecraft;
public class ReplayVisuals {
// todo: move all of this to replaystate?
public static boolean showChat = true;
public static boolean showBossBar = true;
public static boolean showTitleText = true;
public static boolean showScoreboard = true;
public static boolean showActionBar = true;
public static boolean renderBlocks = true;
public static boolean renderEntities = true;
public static boolean renderPlayers = true;
public static boolean renderParticles = true;
public static boolean renderSky = true;
public static boolean renderNametags = true;
public static boolean overrideFog = false;
public static float overrideFogStart = 0.0f;
public static float overrideFogEnd = 256.0f;
public static boolean overrideFov = false;
public static float overrideFovAmount = 70f;
public static long overrideTimeOfDay = -1;
public static boolean ruleOfThirdsGuide = false;
public static boolean centerGuide = false;
public static Sizing sizing = Sizing.KEEP_ASPECT_RATIO;
public static AspectRatio changeAspectRatio = AspectRatio.ASPECT_16_9;
public static volatile int forceEntityLerpTicks = 0;
public static void setFov(float fov) {
if (!overrideFov || Math.abs(overrideFovAmount - fov) >= 0.01) {
Minecraft.getInstance().levelRenderer.needsUpdate();
}
overrideFov = true;
overrideFovAmount = fov;
}
public static void disable() {
showBossBar = true;
showTitleText = true;
showScoreboard = true;
showActionBar = true;
renderBlocks = true;
renderEntities = true;
renderParticles = true;
renderSky = true;
renderNametags = true;
overrideFog = false;
ruleOfThirdsGuide = false;
centerGuide = false;
overrideFov = false;
forceEntityLerpTicks = 0;
overrideTimeOfDay = -1;
}
public static void setupReplay() {
disable();
showChat = false;
showBossBar = false;
showTitleText = false;
showActionBar = false;
showScoreboard = false;
}
}
@@ -15,8 +15,7 @@ public class TempFolderProvider {
public enum TempFolderType {
SERVER("server"),
RECORDING("recording"),
PLAYBACK("playback");
RECORDING("recording");
private final String id;
@@ -26,9 +25,7 @@ public class TempFolderProvider {
}
private static Path getSharedTempFolder() {
return FabricLoader.getInstance().getGameDir()
.resolve("flashback")
.resolve("temp");
return Flashback.getDataDirectory().resolve("temp");
}
public static void tryDeleteStaleFolders() {
@@ -126,7 +123,7 @@ public class TempFolderProvider {
try {
FileUtils.deleteDirectory(path.toFile());
} catch (Exception e) {
throw new RuntimeException(e);
Flashback.LOGGER.error("Failed to delete temp directory", e);
}
deleteDirectoryIfEmpty(path.getParent());
@@ -0,0 +1,52 @@
package com.moulberry.flashback;
import org.lwjgl.system.Pointer;
import org.lwjgl.system.jni.JNINativeInterface;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.function.LongPredicate;
public class UnsafeWrapper {
public static final Unsafe UNSAFE;
static {
UNSAFE = getUnsafeInstance();
}
private static Unsafe getUnsafeInstance() {
// Try getting theUnsafe
try {
final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
return (Unsafe) theUnsafe.get(null);
} catch (Exception ignored) {}
// Try searching for fields
Field[] fields = Unsafe.class.getDeclaredFields();
for (Field field : fields) {
if (!field.getType().equals(Unsafe.class)) {
continue;
}
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers)) {
continue;
}
try {
field.setAccessible(true);
return (Unsafe) field.get(null);
} catch (Exception ignored) {}
break;
}
// Unavailable! :(
throw new Error("Flashback requires sun.misc.Unsafe to be available.");
}
}
@@ -3,6 +3,9 @@ package com.moulberry.flashback;
import it.unimi.dsi.fastutil.objects.Object2FloatFunction;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.Random;
public class Utils {
/*
@@ -57,4 +60,92 @@ public class Utils {
}
}
public static float fovToFocalLength(float fov) {
return 1.0f / (float) Math.tan(Math.toRadians(fov) * 0.5);
}
public static float focalLengthToFov(float focalLength) {
return (float) Math.toDegrees(Math.atan(1.0 / focalLength) * 2.0f);
}
public static Random getInternalMathRandom() {
for (Class<?> declaredClass : Math.class.getDeclaredClasses()) {
try {
if (declaredClass.getSimpleName().endsWith("RandomNumberGeneratorHolder")) {
Field field = declaredClass.getDeclaredField("randomNumberGenerator");
if (field.trySetAccessible()) {
return (Random) field.get(null);
} else {
return (Random) UnsafeWrapper.UNSAFE.getObject(UnsafeWrapper.UNSAFE.staticFieldBase(field),
UnsafeWrapper.UNSAFE.staticFieldOffset(field));
}
}
} catch (Exception e) {
Flashback.LOGGER.error("Failed to get internal Math random", e);
}
}
return null;
}
private static final int SECOND_TO_TICKS = 20;
private static final int MINUTE_TO_TICKS = SECOND_TO_TICKS * 60;
private static final int HOUR_TO_TICKS = MINUTE_TO_TICKS * 60;
public static int stringToTime(String string) {
int number = 0;
int modifier = 1;
int total = 0;
for (char c : string.toCharArray()) {
if (c >= '0' && c <= '9') {
if (modifier > 1) {
total += number * modifier;
number = 0;
modifier = 1;
}
number *= 10;
number += c - '0';
} else if (c == 's') {
modifier *= SECOND_TO_TICKS;
} else if (c == 'm') {
modifier *= MINUTE_TO_TICKS;
} else if (c == 'h') {
modifier *= HOUR_TO_TICKS;
}
}
total += number * modifier;
return total;
}
public static String timeToString(int ticks) {
StringBuilder builder = new StringBuilder();
timeToString(builder, ticks);
if (builder.isEmpty()) {
return "0s";
}
return builder.toString();
}
private static void timeToString(StringBuilder builder, int ticks) {
if (ticks >= HOUR_TO_TICKS) {
int hours = ticks / HOUR_TO_TICKS;
builder.append(hours).append('h');
timeToString(builder, ticks - hours*HOUR_TO_TICKS);
} else if (ticks >= MINUTE_TO_TICKS) {
int minutes = ticks / MINUTE_TO_TICKS;
builder.append(minutes).append('m');
timeToString(builder, ticks - minutes*MINUTE_TO_TICKS);
} else if (ticks >= SECOND_TO_TICKS) {
int seconds = ticks / SECOND_TO_TICKS;
builder.append(seconds).append('s');
timeToString(builder, ticks - seconds*SECOND_TO_TICKS);
} else if (ticks > 0) {
builder.append(ticks).append('t');
}
}
}
@@ -0,0 +1,87 @@
package com.moulberry.flashback.combo_options;
import org.bytedeco.ffmpeg.avcodec.AVCodec;
import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacpp.Pointer;
import java.util.ArrayList;
import java.util.List;
public enum AudioCodec implements ComboOption {
AAC("AAC", avcodec.AV_CODEC_ID_AAC),
FLAC("FLAC", avcodec.AV_CODEC_ID_FLAC),
MP3("MP3", avcodec.AV_CODEC_ID_MP3),
OPUS("Opus", avcodec.AV_CODEC_ID_OPUS),
VORBIS("Vorbis", avcodec.AV_CODEC_ID_VORBIS);
private final String text;
private final int codecId;
private String[] encoders;
AudioCodec(String text, int codecId) {
this.text = text;
this.codecId = codecId;
}
@Override
public String text() {
return this.text;
}
public int codecId() {
return this.codecId;
}
public String[] getEncoders() {
if (this.encoders == null) {
List<String> encodersHardware = new ArrayList<>();
List<String> encodersHybrid = new ArrayList<>();
List<String> encodersSoftware = new ArrayList<>();
List<String> encodersAvoid = new ArrayList<>();
try (Pointer pointer = new Pointer()) {
while (true) {
try (AVCodec codec = avcodec.av_codec_iterate(pointer)) {
if (codec == null) {
break;
} else if (codec.id() == this.codecId && avcodec.av_codec_is_encoder(codec) != 0) {
int capabilities = codec.capabilities();
String name = codec.name().getString();
if ((capabilities & avcodec.AV_CODEC_CAP_HARDWARE) != 0) {
encodersHardware.add(name);
} else if ((capabilities & avcodec.AV_CODEC_CAP_HYBRID) != 0 || codecHasHwConfig(codec)) {
encodersHybrid.add(name);
} else if ((capabilities & avcodec.AV_CODEC_CAP_EXPERIMENTAL) != 0) {
encodersAvoid.add(name);
} else {
encodersSoftware.add(name);
}
}
}
}
}
List<String> encoders = new ArrayList<>();
encoders.addAll(encodersHardware);
encoders.addAll(encodersHybrid);
encoders.addAll(encodersSoftware);
encoders.addAll(encodersAvoid);
this.encoders = encoders.toArray(new String[0]);
}
return this.encoders;
}
private static boolean codecHasHwConfig(AVCodec codec) {
try (AVCodecHWConfig config = avcodec.avcodec_get_hw_config(codec, 0)) {
return config != null;
} catch (Throwable t) {
return false;
}
}
}
@@ -3,9 +3,9 @@ package com.moulberry.flashback.combo_options;
public enum Sizing implements ComboOption {
KEEP_ASPECT_RATIO("Keep Aspect Ratio"),
CHANGE_ASPECT_RATIO("Change Aspect Ratio"),
FILL("Fill"),
UNDERLAY("Underlay"),
CHANGE_ASPECT_RATIO("Change Aspect Ratio");
UNDERLAY("Underlay");
private final String text;
@@ -1,18 +1,21 @@
package com.moulberry.flashback.combo_options;
import com.moulberry.flashback.Flashback;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import com.moulberry.flashback.exporting.PixelFormatHelper;
import org.bytedeco.ffmpeg.avcodec.AVCodec;
import org.bytedeco.ffmpeg.avcodec.AVCodecContext;
import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig;
import org.bytedeco.ffmpeg.avutil.AVDictionary;
import org.bytedeco.ffmpeg.avutil.AVRational;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.javacpp.IntPointer;
import org.bytedeco.javacpp.Pointer;
import java.util.*;
import static org.bytedeco.ffmpeg.global.avcodec.*;
import static org.bytedeco.ffmpeg.global.avutil.*;
import static org.bytedeco.ffmpeg.global.avutil.av_find_nearest_q_idx;
public enum VideoCodec implements ComboOption {
H264("H264 (AVC)", avcodec.AV_CODEC_ID_H264),
@@ -50,9 +53,20 @@ public enum VideoCodec implements ComboOption {
try (Pointer pointer = new Pointer()) {
while (true) {
try (AVCodec codec = avcodec.av_codec_iterate(pointer)) {
if (codec == null) {
break;
} else if (codec.id() == this.codecId && avcodec.av_codec_is_encoder(codec) != 0) {
try {
if (codec == null) {
break;
}
if (codec.id() != this.codecId) {
continue;
}
if (avcodec.av_codec_is_encoder(codec) == 0) {
continue;
}
if (!doesEncoderWork(codec)) {
continue;
}
int capabilities = codec.capabilities();
String name = codec.name().getString();
@@ -65,6 +79,10 @@ public enum VideoCodec implements ComboOption {
} else {
encodersSoftware.add(name);
}
} finally {
if (codec != null) {
codec.close();
}
}
}
}
@@ -82,12 +100,58 @@ public enum VideoCodec implements ComboOption {
return this.encoders;
}
private static boolean doesEncoderWork(AVCodec codec) {
AVCodecContext codecContext = null;
AVDictionary options = new AVDictionary(null);
try {
if ((codecContext = avcodec.avcodec_alloc_context3(codec)) == null) {
return false;
}
// Setup dummy parameters
codecContext.codec_id(codec.id());
codecContext.codec_type(AVMEDIA_TYPE_VIDEO);
codecContext.bit_rate(400000);
codecContext.width(1920);
codecContext.height(1080);
AVRational frameRate = av_d2q(60.0, 1001000);
AVRational supportedFramerates = codec.supported_framerates();
if (supportedFramerates != null) {
int idx = av_find_nearest_q_idx(frameRate, supportedFramerates);
frameRate = supportedFramerates.position(idx);
}
AVRational time_base = av_inv_q(frameRate);
codecContext.time_base(time_base);
int pixelFormat = PixelFormatHelper.getBestPixelFormat(codec.name().getString());
codecContext.pix_fmt(pixelFormat);
if ((codec.capabilities() & AV_CODEC_CAP_EXPERIMENTAL) != 0) {
codecContext.strict_std_compliance(FF_COMPLIANCE_EXPERIMENTAL);
}
return avcodec.avcodec_open2(codecContext, codec, options) >= 0;
} finally {
if (codecContext != null) {
avcodec.avcodec_close(codecContext);
codecContext.close();
}
avutil.av_dict_free(options);
}
}
private static boolean codecHasHwConfig(AVCodec codec) {
try (AVCodecHWConfig config = avcodec.avcodec_get_hw_config(codec, 0)) {
return config != null;
} catch (Throwable t) {
return false;
}
if (config != null) {
config.close();
return true;
}
} catch (Exception ignored) {}
return false;
}
}
@@ -16,7 +16,8 @@ public enum VideoContainer implements ComboOption {
private final String text;
private final String extension;
private VideoCodec[] supportedCodecs = null;
private VideoCodec[] supportedVideoCodecs = null;
private AudioCodec[] supportedAudioCodecs = null;
VideoContainer(String text, String extension) {
this.text = text;
@@ -32,8 +33,8 @@ public enum VideoContainer implements ComboOption {
return extension;
}
public VideoCodec[] getSupportedCodecs() {
if (this.supportedCodecs == null) {
public VideoCodec[] getSupportedVideoCodecs() {
if (this.supportedVideoCodecs == null) {
List<VideoCodec> supportedCodecs = new ArrayList<>();
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (VideoCodec codec : VideoCodec.values()) {
@@ -51,9 +52,30 @@ public enum VideoContainer implements ComboOption {
}
}
this.supportedCodecs = supportedCodecs.toArray(new VideoCodec[0]);
this.supportedVideoCodecs = supportedCodecs.toArray(new VideoCodec[0]);
}
return this.supportedCodecs;
return this.supportedVideoCodecs;
}
public AudioCodec[] getSupportedAudioCodecs() {
if (this.supportedAudioCodecs == null) {
List<AudioCodec> supportedCodecs = new ArrayList<>();
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (AudioCodec codec : AudioCodec.values()) {
if (codec.getEncoders().length == 0) {
continue;
}
int ret = avformat.avformat_query_codec(outputFormat, codec.codecId(), avcodec.FF_COMPLIANCE_NORMAL);
if (ret == 1) {
supportedCodecs.add(codec);
}
}
}
this.supportedAudioCodecs = supportedCodecs.toArray(new AudioCodec[0]);
}
return this.supportedAudioCodecs;
}
}
@@ -1,31 +0,0 @@
package com.moulberry.flashback.combo_options;
public enum VideoPreset implements ComboOption {
ULTRAFAST("Ultra Fast", "ultrafast"),
SUPERFAST("Super Fast", "superfast"),
VERYFAST("Very Fast", "veryfast"),
FASTER("Faster", "faster"),
FAST("Fast", "fast"),
MEDIUM("Medium", "medium"),
SLOW("Slow", "slow"),
SLOWER("Slower", "slower"),
VERYSLOW("Very Slow", "veryslow");
private final String text;
private final String presetId;
VideoPreset(String text, String presetId) {
this.text = text;
this.presetId = presetId;
}
@Override
public String text() {
return this.text;
}
public String presetId() {
return this.presetId;
}
}
@@ -0,0 +1,18 @@
package com.moulberry.flashback.compat;
import net.fabricmc.loader.api.FabricLoader;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.api.v0.IrisApi;
import org.jetbrains.annotations.Nullable;
public class IrisApiWrapper {
public static boolean isIrisAvailable() {
return FabricLoader.getInstance().isModLoaded("iris");
}
public static boolean isShaderPackInUse() {
return IrisApi.getInstance().isShaderPackInUse();
}
}
@@ -1,14 +1,23 @@
package com.moulberry.flashback.configuration;
import com.google.common.reflect.Reflection;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.SneakyThrow;
import net.minecraft.ChatFormatting;
import net.minecraft.client.OptionInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import org.apache.logging.log4j.core.util.ReflectionUtil;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
@@ -16,24 +25,32 @@ public class FlashbackConfig {
@OptionCaption("flashback.option.automatically_start")
@OptionDescription("flashback.option.automatically_start.description")
public static boolean automaticallyStart = false;
public boolean automaticallyStart = false;
@OptionCaption("flashback.option.automatically_finish")
@OptionDescription("flashback.option.automatically_finish.description")
public static boolean automaticallyFinish = true;
public boolean automaticallyFinish = true;
@OptionCaption("flashback.option.show_recording_toasts")
@OptionDescription("flashback.option.show_recording_toasts.description")
public static boolean showRecordingToasts = true;
public boolean showRecordingToasts = true;
@OptionCaption("flashback.option.quicksave")
@OptionDescription("flashback.option.quicksave.description")
public boolean quicksave = false;
@OptionCaption("flashback.option.hide_pause_menu_controls")
@OptionDescription("flashback.option.hide_pause_menu_controls.description")
public boolean hidePauseMenuControls = false;
@SuppressWarnings("unchecked")
public static OptionInstance<?>[] createOptionInstances() {
public OptionInstance<?>[] createOptionInstances() {
List<OptionInstance<?>> options = new ArrayList<>();
for (Field field : FlashbackConfig.class.getDeclaredFields()) {
try {
// Ignore non-static fields
if ((field.getModifiers() & Modifier.STATIC) == 0) {
// Ignore static & transient fields
if ((field.getModifiers() & Modifier.STATIC) != 0 || (field.getModifiers() & Modifier.TRANSIENT) != 0) {
continue;
}
@@ -54,9 +71,9 @@ public class FlashbackConfig {
}
if (field.getType() == boolean.class) {
options.add(OptionInstance.createBoolean(caption.value(), tooltipSupplier, field.getBoolean(null), value -> {
options.add(OptionInstance.createBoolean(caption.value(), tooltipSupplier, field.getBoolean(this), value -> {
try {
field.set(null, value);
field.set(this, value);
} catch (Exception e) {
throw SneakyThrow.sneakyThrow(e);
}
@@ -70,4 +87,58 @@ public class FlashbackConfig {
return options.toArray(new OptionInstance[0]);
}
public static FlashbackConfig tryLoadFromFolder(Path configFolder) {
Path primary = configFolder.resolve("flashback.json");
Path backup = configFolder.resolve(".flashback.json.backup");
if (Files.exists(primary)) {
try {
return load(primary);
} catch (Exception e) {
Flashback.LOGGER.error("Failed to load config from {}", primary, e);
}
}
if (Files.exists(backup)) {
try {
return load(backup);
} catch (Exception e) {
Flashback.LOGGER.error("Failed to load config from {}", backup, e);
}
}
return new FlashbackConfig();
}
public void saveToFolder(Path configFolder) {
Path primary = configFolder.resolve("flashback.json");
Path backup = configFolder.resolve(".flashback.json.backup");
if (Files.exists(primary)) {
try {
Files.move(primary, backup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to backup config", e);
}
}
this.save(primary);
}
private static FlashbackConfig load(Path path) throws IOException {
String serialized = Files.readString(path);
return FlashbackGson.PRETTY.fromJson(serialized, FlashbackConfig.class);
}
private void save(Path path) {
String serialized = FlashbackGson.PRETTY.toJson(this, FlashbackConfig.class);
try {
Files.writeString(path, serialized, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.CREATE, StandardOpenOption.DSYNC);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to save config", e);
}
}
}
@@ -3,53 +3,72 @@ package com.moulberry.flashback.editor;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateHistoryAction;
import com.moulberry.flashback.state.EditorStateHistoryEntry;
import com.moulberry.flashback.state.KeyframeTrack;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public record SavedTrack(KeyframeType type, int track, boolean copiedFromDisabled,
TreeMap<Integer, Keyframe<?>> keyframes) {
TreeMap<Integer, Keyframe> keyframes) {
public int applyToEditorState(EditorState editorState, int cursorTicks, int totalTicks) {
if (this.keyframes == null || this.keyframes.isEmpty()) {
return 0;
}
editorState.dirty = true;
// Try to apply directly to copied track
if (this.track >= 0 && this.track < editorState.keyframeTracks.size()) {
KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.track);
if ((keyframeTrack.enabled || this.copiedFromDisabled) && keyframeTrack.keyframeType == this.type) {
return this.applyTo(keyframeTrack, cursorTicks, totalTicks);
return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks);
}
}
// Try to find first eligible enabled track
for (KeyframeTrack keyframeTrack : editorState.keyframeTracks) {
if (keyframeTrack.enabled && keyframeTrack.keyframeType == this.type) {
return this.applyTo(keyframeTrack, cursorTicks, totalTicks);
return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks);
}
}
// Create new track
KeyframeTrack keyframeTrack = new KeyframeTrack(this.type);
int count = this.applyTo(keyframeTrack, cursorTicks, totalTicks);
if (!keyframeTrack.keyframesByTick.isEmpty()) {
editorState.keyframeTracks.add(keyframeTrack);
}
return count;
return this.applyTo(editorState, this.type, null, this.track, cursorTicks, totalTicks);
}
public int applyTo(KeyframeTrack keyframeTrack, int cursorTicks, int totalTicks) {
private int applyTo(EditorState editorState, KeyframeType type, @Nullable KeyframeTrack existing, int trackIndex, int cursorTicks, int totalTicks) {
List<EditorStateHistoryAction> undo = new ArrayList<>();
List<EditorStateHistoryAction> redo = new ArrayList<>();
if (existing == null) {
undo.add(new EditorStateHistoryAction.RemoveTrack(type, trackIndex));
redo.add(new EditorStateHistoryAction.AddTrack(type, trackIndex));
}
int count = 0;
for (Map.Entry<Integer, Keyframe<?>> entry : this.keyframes.entrySet()) {
for (Map.Entry<Integer, Keyframe> entry : this.keyframes.entrySet()) {
int newTick = entry.getKey() + cursorTicks;
if (newTick >= 0 && newTick <= totalTicks) {
keyframeTrack.keyframesByTick.put(newTick, entry.getValue());
if (existing != null) {
Keyframe old = existing.keyframesByTick.get(newTick);
if (old != null) {
undo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, old.copy()));
} else {
undo.add(new EditorStateHistoryAction.RemoveKeyframe(type, trackIndex, newTick));
}
}
redo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, entry.getValue().copy()));
count += 1;
}
}
editorState.push(new EditorStateHistoryEntry(undo, redo, "Pasted " + count + " keyframe(s)"));
return count;
}
}
@@ -307,7 +307,7 @@ public class CustomImGuiImplGlfw {
if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE;
// Don't allow key presses during export
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) {
if (Flashback.isExporting()) {
if (action == GLFW_RELEASE && keyInBoundsForGame && this.keyPressedGame[minecraftKey]) {
this.keyPressedGame[minecraftKey] = false;
} else {
@@ -42,87 +42,6 @@ public class ImGuiHelper {
return imString;
}
public static int elementList(String name, List<String> elements, float width, int minLines, int maxLines, boolean framed, IntConsumer buttonConsumer) {
if (minLines > maxLines) throw new IllegalArgumentException();
if (width <= 0) {
width = Math.max(ImGui.getContentRegionAvailX() + width, 4.0f);
}
float itemSpacingX = ImGui.getStyle().getItemSpacingX();
float framePaddingX = ImGui.getStyle().getFramePaddingX();
float availableSpace = width;
if (framed) availableSpace -= framePaddingX*2f;
int lines = 0;
boolean scrollbar = false;
if (minLines == maxLines) {
lines = minLines;
scrollbar = true; // assume there is a scrollbar
} else {
float consumedWidth = 0;
for (String element : elements) {
float elementWidth = framePaddingX*2f + ImGuiHelper.calcTextWidth(element);
if (consumedWidth+elementWidth < availableSpace && consumedWidth > 0) {
consumedWidth += elementWidth + itemSpacingX;
} else {
consumedWidth = elementWidth + itemSpacingX;
lines += 1;
if (lines > maxLines) {
lines = maxLines;
scrollbar = true;
break;
}
}
}
if (lines < minLines) lines = minLines;
}
float lineHeight = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2 + ImGui.getStyle().getItemSpacingY();
boolean visible;
if (framed) {
visible = ImGui.beginChildFrame(ImGui.getID(name), width, lineHeight*lines + ImGui.getStyle().getFramePaddingY()*2 - ImGui.getStyle().getItemSpacingY());
} else {
visible = ImGui.beginChild(name, width, lineHeight*lines - ImGui.getStyle().getItemSpacingY());
}
int ret = -1;
if (visible) {
if (scrollbar) {
availableSpace -= ImGui.getStyle().getScrollbarSize();
}
float consumedWidth = 0;
for (int i=0; i<elements.size(); i++) {
String element = elements.get(i);
float elementWidth = framePaddingX*2f + ImGuiHelper.calcTextWidth(element);
if (consumedWidth+elementWidth < availableSpace && consumedWidth > 0) {
ImGui.sameLine();
consumedWidth += elementWidth + itemSpacingX;
} else {
consumedWidth = elementWidth + itemSpacingX;
}
ImGui.pushID(i);
if (ImGui.button(element)) {
ret = i;
}
if (buttonConsumer != null) {
buttonConsumer.accept(i);
}
ImGui.popID();
}
}
if (framed) {
ImGui.endChildFrame();
} else {
ImGui.endChild();
}
return ret;
}
private static final int[] enumComboSharedArray = new int[]{0};
private static final Map<Class<?>, Object[]> enumComboCachedValues = new HashMap<>();
private static final Map<Class<?>, String[]> enumComboCachedText = new HashMap<>();
@@ -207,28 +126,18 @@ public class ImGuiHelper {
private static boolean closeableModalOnTopLast = false;
private static boolean closeableModalOnTop = false;
private static boolean inputIntScrolledLastFrame = false;
private static boolean inputIntScrolledThisFrame = false;
private static boolean wantSpecialInputLastFrame = false;
private static boolean wantSpecialInputThisFrame = false;
private static StringBuilder specialInput = new StringBuilder();
private static int backspaceCount = 0;
private static boolean handledFocusNext = false;
private static boolean focusNext = false;
public static void endFrame() {
closeableModalOnTopLast = closeableModalOnTop;
inputIntScrolledLastFrame = inputIntScrolledThisFrame;
inputIntScrolledThisFrame = false;
wantSpecialInputLastFrame = wantSpecialInputThisFrame;
wantSpecialInputThisFrame = false;
handledFocusNext = false;
focusNext = false;
if (!wantSpecialInputLastFrame) specialInput.setLength(0);
}
@@ -4,7 +4,9 @@ import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.TextureUtil;
import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.editor.ui.windows.ExportQueueWindow;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.windows.MainMenuBar;
import com.moulberry.flashback.editor.ui.windows.StartExportWindow;
@@ -21,11 +23,9 @@ import net.minecraft.client.gui.screens.ProgressScreen;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.level.ClipContext;
@@ -54,10 +54,10 @@ public class ReplayUI {
private static boolean initialized = false;
private static boolean isFrameHovered = false;
private static int frameX = 0;
private static int frameY = 0;
private static int frameWidth = 1;
private static int frameHeight = 1;
public static int frameX = 0;
public static int frameY = 0;
public static int frameWidth = 1;
public static int frameHeight = 1;
private static boolean activeLastFrame = false;
public static Matrix4f lastProjectionMatrix = null;
@@ -84,7 +84,7 @@ public class ReplayUI {
private static boolean popupOpenLastFrame = false;
private static String infoOverlayText = null;
private static long infoOverlayStartMillis = 0;
private static long infoOverlayEndMillis = 0;
private static int selectedEntity = Integer.MIN_VALUE;
private static boolean openSelectedEntityPopup = false;
@@ -105,6 +105,14 @@ public class ReplayUI {
try {
Files.writeString(path, ReplayUIDefaults.LAYOUT);
} catch(IOException ignored) {}
} else {
try {
String imguiIni = Files.readString(path);
if (imguiIni.contains("[Window][Timeline]")) {
imguiIni = imguiIni.replace("[Window][Timeline]", "[Window][###Timeline]");
Files.writeString(path, imguiIni);
}
} catch (IOException ignored) {}
}
long oldImGuiContext = ImGui.getCurrentContext().ptr;
@@ -305,7 +313,12 @@ public class ReplayUI {
public static void setInfoOverlay(String text) {
infoOverlayText = text;
infoOverlayStartMillis = System.currentTimeMillis();
infoOverlayEndMillis = System.currentTimeMillis() + 5000;
}
public synchronized static void setInfoOverlayShort(String text) {
infoOverlayText = text;
infoOverlayEndMillis = System.currentTimeMillis() + 1000;
}
public static void setupMainViewport() {
@@ -382,6 +395,11 @@ public class ReplayUI {
return activeLastFrame;
}
public static boolean shouldModifyViewport() {
EditorState editorState = EditorStateManager.getCurrent();
return isActive() && editorState != null && editorState.replayVisuals.sizing != Sizing.UNDERLAY;
}
private static void transitionActiveState(boolean active) {
if (activeLastFrame == active) return;
activeLastFrame = active;
@@ -538,12 +556,15 @@ public class ReplayUI {
frameWidth = (int) Math.max(1, maxX - minX);
frameHeight = (int) Math.max(1, maxY - minY);
if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO || ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) {
EditorState editorState = EditorStateManager.getCurrent();
Sizing sizing = editorState == null ? Sizing.KEEP_ASPECT_RATIO : editorState.replayVisuals.sizing;
if (sizing == Sizing.KEEP_ASPECT_RATIO || sizing == Sizing.CHANGE_ASPECT_RATIO) {
float aspectRatio;
if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO) {
if (sizing == Sizing.KEEP_ASPECT_RATIO) {
aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY();
} else {
aspectRatio = ReplayVisuals.changeAspectRatio.aspectRatio();
aspectRatio = editorState.replayVisuals.changeAspectRatio.aspectRatio();
}
float currentAspectRatio = frameWidth / (float) frameHeight;
@@ -561,8 +582,9 @@ public class ReplayUI {
if (infoOverlayText != null) {
long currentMillis = System.currentTimeMillis();
if (currentMillis < infoOverlayStartMillis || currentMillis > infoOverlayStartMillis + 5000) {
if (currentMillis < infoOverlayEndMillis - 30000 || currentMillis > infoOverlayEndMillis) {
infoOverlayText = null;
infoOverlayEndMillis = 0;
} else {
ImGui.setNextWindowPos(frameX + frameWidth*0.5f, frameY + frameHeight*0.75f, ImGuiCond.Always, 0.5f, 0.5f);
ImGui.setNextWindowSizeConstraints(0, 0, 550, frameHeight*0.45f);
@@ -583,7 +605,7 @@ public class ReplayUI {
}
}
if (ReplayVisuals.sizing == Sizing.UNDERLAY) {
if (sizing == Sizing.UNDERLAY) {
frameX = 0;
frameY = 0;
frameWidth = Minecraft.getInstance().getWindow().getScreenWidth();
@@ -594,27 +616,33 @@ public class ReplayUI {
Minecraft.getInstance().resizeDisplay();
}
if (ReplayVisuals.ruleOfThirdsGuide) {
ImDrawList drawList = ImGui.getForegroundDrawList();
drawList.addLine(frameX + frameWidth/3, frameY, frameX + frameWidth/3, frameY+frameHeight, -1, 2);
drawList.addLine(frameX + frameWidth*2/3, frameY, frameX + frameWidth*2/3, frameY+frameHeight, -1, 2);
drawList.addLine(frameX, frameY + frameHeight/3, frameX + frameWidth, frameY + frameHeight/3, -1, 2);
drawList.addLine(frameX, frameY + frameHeight*2/3, frameX + frameWidth, frameY + frameHeight*2/3, -1, 2);
}
if (Minecraft.getInstance().screen == null && Minecraft.getInstance().getOverlay() == null) {
if (editorState != null && editorState.replayVisuals.ruleOfThirdsGuide) {
ImDrawList drawList = ImGui.getBackgroundDrawList();
drawList.removeImDrawListFlags(ImDrawListFlags.AntiAliasedLines);
drawList.addLine(frameX + frameWidth/3, frameY, frameX + frameWidth/3, frameY+frameHeight, 0xAAFFFFFF, 2);
drawList.addLine(frameX + frameWidth*2/3, frameY, frameX + frameWidth*2/3, frameY+frameHeight, 0xAAFFFFFF, 2);
drawList.addLine(frameX, frameY + frameHeight/3, frameX + frameWidth, frameY + frameHeight/3, 0xAAFFFFFF, 2);
drawList.addLine(frameX, frameY + frameHeight*2/3, frameX + frameWidth, frameY + frameHeight*2/3, 0xAAFFFFFF, 2);
drawList.addImDrawListFlags(ImDrawListFlags.AntiAliasedLines);
}
if (ReplayVisuals.centerGuide) {
ImDrawList drawList = ImGui.getForegroundDrawList();
drawList.addLine(frameX + frameWidth/2, frameY, frameX + frameWidth/2, frameY+frameHeight, -1, 2);
drawList.addLine(frameX, frameY + frameHeight/2, frameX + frameWidth, frameY + frameHeight/2, -1, 2);
if (editorState != null && editorState.replayVisuals.centerGuide) {
ImDrawList drawList = ImGui.getBackgroundDrawList();
drawList.removeImDrawListFlags(ImDrawListFlags.AntiAliasedLines);
drawList.addLine(frameX + frameWidth/2, frameY, frameX + frameWidth/2, frameY+frameHeight, 0xAAFFFFFF, 2);
drawList.addLine(frameX, frameY + frameHeight/2, frameX + frameWidth, frameY + frameHeight/2, 0xAAFFFFFF, 2);
drawList.addImDrawListFlags(ImDrawListFlags.AntiAliasedLines);
}
}
if (selectedEntity != Integer.MIN_VALUE) {
Entity entity = Minecraft.getInstance().level.getEntity(selectedEntity);
if (entity == null) {
selectedEntity = Integer.MIN_VALUE;
} else if (entity instanceof Player && !ReplayVisuals.renderPlayers) {
} else if (entity instanceof Player && editorState != null && !editorState.replayVisuals.renderPlayers) {
selectedEntity = Integer.MIN_VALUE;
} else if (!(entity instanceof Player) && !ReplayVisuals.renderEntities) {
} else if (!(entity instanceof Player) && editorState != null && !editorState.replayVisuals.renderEntities) {
selectedEntity = Integer.MIN_VALUE;
} else {
if (openSelectedEntityPopup) {
@@ -629,10 +657,10 @@ public class ReplayUI {
if (ImGui.button("Look At")) {
Minecraft.getInstance().cameraEntity.lookAt(EntityAnchorArgument.Anchor.EYES, entity.getEyePosition());
}
// todo: need to remember spectate target when a snapshot is played
// if (ImGui.button("Spectate")) {
// Minecraft.getInstance().player.connection.sendUnsignedCommand("spectate " + entity.getUUID());
// }
if (ImGui.button("Spectate")) {
Minecraft.getInstance().player.connection.sendUnsignedCommand("spectate " + entity.getUUID());
ImGui.closeCurrentPopup();
}
// ImGui.sameLine();
// ImGui.button("Track Entity");
//
@@ -676,7 +704,7 @@ public class ReplayUI {
if (wheelY != 0) {
final float defaultFlyingSpeed = 0.05f;
float flyingSpeed = Mth.clamp(player.getAbilities().getFlyingSpeed() + (float)wheelY * defaultFlyingSpeed / 10f,
defaultFlyingSpeed / 10f, defaultFlyingSpeed * 5.0f);
defaultFlyingSpeed / 10f, defaultFlyingSpeed * 10.0f);
setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed));
player.getAbilities().setFlyingSpeed(flyingSpeed);
}
@@ -693,6 +721,7 @@ public class ReplayUI {
VisualsWindow.render();
TimelineWindow.render();
StartExportWindow.render();
ExportQueueWindow.render();
popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup);
@@ -824,7 +853,9 @@ public class ReplayUI {
BlockHitResult blockResult = null;
EntityHitResult entityResult = null;
if (ReplayVisuals.renderBlocks) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState == null || editorState.replayVisuals.renderBlocks) {
ClipContext clipContext = new ClipContext(from, to, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, CollisionContext.empty());
blockResult = Minecraft.getInstance().level.clip(clipContext);
@@ -833,16 +864,16 @@ public class ReplayUI {
}
}
if (ReplayVisuals.renderEntities || ReplayVisuals.renderPlayers) {
if (editorState == null || editorState.replayVisuals.renderEntities || editorState.replayVisuals.renderPlayers) {
AABB boundingBox = new AABB(from.subtract(0.5f, 0.5f, 0.5f), from.add(0.5f, 0.5f, 0.5f));
boundingBox = boundingBox.expandTowards(look.scale(distance));
Predicate<Entity> predicate;
if (ReplayVisuals.renderEntities && ReplayVisuals.renderPlayers) {
if (editorState.replayVisuals.renderEntities && editorState.replayVisuals.renderPlayers) {
predicate = entity -> true;
} else if (ReplayVisuals.renderPlayers) {
} else if (editorState.replayVisuals.renderPlayers) {
predicate = entity -> entity instanceof Player;
} else if (ReplayVisuals.renderEntities) {
} else if (editorState.replayVisuals.renderEntities) {
predicate = entity -> !(entity instanceof Player);
} else {
throw new IllegalStateException();
@@ -10,18 +10,18 @@ import org.lwjgl.glfw.GLFW;
public class ReplayUIDefaults {
public static final String LAYOUT = """
[Window][Timeline]
[Window][###Timeline]
Pos=0,830
Size=1920,250
Collapsed=0
DockId=0x00000002,0
[Window][Visuals]
Pos=1670,0
Size=250,830
Collapsed=0
DockId=0x00000004,0
[Docking][Data]
DockSpace ID=0x8B93E3BD Window=0xA787BDB4 Pos=0,22 Size=1920,1080 Split=Y Selected=0x1F1A625A
DockNode ID=0x00000001 Parent=0x8B93E3BD SizeRef=1920,830 Split=X Selected=0x1F1A625A
@@ -0,0 +1,91 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.exporting.ExportSettings;
import imgui.ImGui;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiTableColumnFlags;
import imgui.flag.ImGuiTableFlags;
import imgui.flag.ImGuiWindowFlags;
public class ExportQueueWindow {
private static boolean open = false;
public static void open() {
open = true;
}
public static void render() {
if (open) {
ImGui.openPopup("###ExportQueue");
open = false;
}
if (ImGuiHelper.beginPopupModalCloseable("Export Queue###ExportQueue", ImGuiWindowFlags.AlwaysAutoResize)) {
ImGuiHelper.pushStyleColor(ImGuiCol.Border, 0xFF808080);
boolean canStartJob = !ExportJobQueue.queuedJobs.isEmpty() && Flashback.EXPORT_JOB == null;
boolean canRemoveJob = !ExportJobQueue.queuedJobs.isEmpty();
ImGui.text("Jobs");
if (ImGui.beginChild("##Jobs", 300, 150, true)) {
if (ImGui.beginTable("##JobTable", 3, ImGuiTableFlags.SizingFixedFit)) {
ImGui.tableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch);
int startJob = -1;
int removeJob = -1;
for (int i = 0; i < ExportJobQueue.queuedJobs.size(); i++) {
ExportSettings queuedJob = ExportJobQueue.queuedJobs.get(i);
String name = queuedJob.name() == null ? "Job #" + (i+1) : queuedJob.name();
ImGui.tableNextColumn();
ImGui.text(name);
ImGui.tableNextColumn();
if (ImGui.smallButton("Start")) {
startJob = i;
}
ImGui.tableNextColumn();
if (ImGui.smallButton("Remove")) {
removeJob = i;
}
}
if (startJob >= 0 && canStartJob) {
ExportSettings settings = ExportJobQueue.queuedJobs.remove(startJob);
Flashback.EXPORT_JOB = new ExportJob(settings);
} else if (removeJob >= 0 && canRemoveJob) {
ExportJobQueue.queuedJobs.remove(removeJob);
}
ImGui.endTable();
}
ImGui.endChild();
}
ImGuiHelper.popStyleColor();
if (!canStartJob) ImGui.beginDisabled();
if (ImGui.button("Start All") && canStartJob) {
ExportJobQueue.drainingQueue = true;
}
if (!canStartJob) ImGui.endDisabled();
ImGui.sameLine();
if (!canRemoveJob) ImGui.beginDisabled();
if (ImGui.button("Remove All") && canRemoveJob) {
ExportJobQueue.queuedJobs.clear();
}
if (!canRemoveJob) ImGui.endDisabled();
ImGuiHelper.endPopupModalCloseable();
}
}
}
@@ -1,6 +1,8 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.exporting.ExportJobQueue;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
public class MainMenuBar {
@@ -10,6 +12,17 @@ public class MainMenuBar {
StartExportWindow.open();
}
if (!ExportJobQueue.queuedJobs.isEmpty()) {
String name = "Export Queue (" + ExportJobQueue.count() + ")";
if (ImGui.menuItem(name + "###QueuedJobs")) {
ExportQueueWindow.open();
}
}
if (ImGui.menuItem("Hide (F1)")) {
Minecraft.getInstance().options.hideGui = true;
}
ImGui.endMainMenuBar();
}
}
@@ -2,42 +2,56 @@ package com.moulberry.flashback.editor.ui.windows;
import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.combo_options.AudioCodec;
import com.moulberry.flashback.combo_options.VideoCodec;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.combo_options.VideoPreset;
import com.moulberry.flashback.compat.IrisApiWrapper;
import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
import com.moulberry.flashback.state.EditorStateManager;
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.playback.ReplayServer;
import imgui.ImGui;
import imgui.flag.ImGuiPopupFlags;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImFloat;
import imgui.type.ImString;
import net.fabricmc.loader.api.FabricLoader;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.FileUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class StartExportWindow {
private static boolean open = false;
private static boolean close = false;
private static final int[] lastFramebufferSize = new int[]{0, 0};
private static final int[] resolution = new int[]{1920, 1080};
private static final int[] startEndTick = new int[]{0, 100};
private static final ImFloat framerate = new ImFloat(60);
private static boolean resetRng = false;
private static VideoContainer container = VideoContainer.MP4;
private static VideoCodec codec = VideoCodec.H264;
private static VideoPreset preset = VideoPreset.MEDIUM;
private static int[] selectedEncoder = new int[]{0};
private static VideoCodec videoCodec = VideoCodec.H264;
private static int[] selectedVideoEncoder = new int[]{0};
private static boolean useMaximumBitrate = false;
private static final ImString bitrate = ImGuiHelper.createResizableImString("20m");
private static boolean recordAudio = false;
private static AudioCodec audioCodec = AudioCodec.AAC;
private static final ImString jobName = ImGuiHelper.createResizableImString("");
static {
bitrate.inputData.allowedChars = "0123456789kmb";
}
@@ -60,11 +74,23 @@ public class StartExportWindow {
}
if (ImGuiHelper.beginPopupModalCloseable("Export to video###StartExport", ImGuiWindowFlags.AlwaysAutoResize)) {
if (close) {
close = false;
ImGui.closeCurrentPopup();
ImGuiHelper.endPopupModalCloseable();
return;
}
ImGuiHelper.separatorWithText("Capture Options");
ImGui.inputInt2("Resolution", resolution);
if (resolution[0] < 16) resolution[0] = 16;
if (resolution[1] < 16) resolution[1] = 16;
if (resolution[0] % 2 != 0) resolution[0] += 1;
if (resolution[1] % 2 != 0) resolution[1] += 1;
if (ImGui.inputInt2("Start/end tick", startEndTick)) {
EditorState editorState = EditorStateCache.getCurrent();
EditorState editorState = EditorStateManager.getCurrent();
ReplayServer replayServer = Flashback.getReplayServer();
if (editorState != null && replayServer != null) {
editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks());
@@ -72,6 +98,11 @@ public class StartExportWindow {
}
ImGui.inputFloat("Framerate", framerate);
if (ImGui.checkbox("Reset RNG", resetRng)) {
resetRng = !resetRng;
}
ImGuiHelper.tooltip("Attempts to remove randomness from the replay in order to produce more consistent outputs when recording the same scene multiple times");
ImGuiHelper.separatorWithText("Video Options");
VideoContainer newContainer = ImGuiHelper.enumCombo("Container", container);
@@ -79,43 +110,29 @@ public class StartExportWindow {
container = newContainer;
boolean supported = false;
for (VideoCodec supportedCodec : container.getSupportedCodecs()) {
if (codec == supportedCodec) {
for (VideoCodec supportedCodec : container.getSupportedVideoCodecs()) {
if (videoCodec == supportedCodec) {
supported = true;
break;
}
}
if (!supported) {
codec = container.getSupportedCodecs()[0];
videoCodec = container.getSupportedVideoCodecs()[0];
}
}
VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", codec, container.getSupportedCodecs());
if (newCodec != codec) {
codec = newCodec;
selectedEncoder[0] = 0;
VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", videoCodec, container.getSupportedVideoCodecs());
if (newCodec != videoCodec) {
videoCodec = newCodec;
selectedVideoEncoder[0] = 0;
}
String[] encoders = codec.getEncoders();
String[] encoders = videoCodec.getEncoders();
if (encoders.length > 1) {
ImGuiHelper.combo("Encoder", selectedEncoder, encoders);
ImGuiHelper.combo("Encoder", selectedVideoEncoder, encoders);
}
// VideoPreset newPreset = ImGuiHelper.enumCombo("Preset", preset);
// if (newPreset != preset) {
// preset = newPreset;
//
// useMaximumBitrate = false;
// if (preset.ordinal() <= VideoPreset.SUPERFAST.ordinal()) {
// bitrate.set("5m");
// } else if (preset.ordinal() <= VideoPreset.MEDIUM.ordinal()) {
// bitrate.set("10m");
// } else {
// bitrate.set("20m");
// }
// }
if (ImGui.checkbox("Use Maximum Bitrate", useMaximumBitrate)) {
useMaximumBitrate = !useMaximumBitrate;
}
@@ -127,43 +144,121 @@ public class StartExportWindow {
}
}
if (ImGui.button("Begin")) {
int numBitrate;
if (useMaximumBitrate) {
numBitrate = 0;
} else {
numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
AudioCodec[] supportedAudioCodecs = container.getSupportedAudioCodecs();
if (supportedAudioCodecs.length > 0) {
ImGuiHelper.separatorWithText("Audio Options");
if (ImGui.checkbox("Record Audio", recordAudio)) {
recordAudio = !recordAudio;
}
String encoder = codec.getEncoders()[selectedEncoder[0]];
if (recordAudio) {
AudioCodec newAudioCodec = ImGuiHelper.enumCombo("Audio Codec", audioCodec, supportedAudioCodecs);
if (newAudioCodec != audioCodec) {
audioCodec = newAudioCodec;
}
}
} else {
recordAudio = false;
}
Path defaultExportPath = FabricLoader.getInstance().getGameDir();
String defaultExportPathString = defaultExportPath.toString();
AsyncFileDialogs.saveFileDialog(defaultExportPathString, "output." + container.extension(),
container.extension(), container.extension()).thenAccept(pathStr -> {
if (pathStr != null) {
int start = Math.max(0, startEndTick[0]);
int end = Math.max(start, startEndTick[1]);
ImGui.dummy(0, 10);
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
int totalTicks = replayServer.getTotalReplayTicks();
start = Math.min(start, totalTicks);
end = Math.min(end, totalTicks);
}
Path path = Path.of(pathStr);
ExportSettings settings = new ExportSettings(resolution[0], resolution[1], start, end,
Math.max(1, framerate.get()), container, codec, encoder, numBitrate, path);
float buttonSize = (ImGui.getContentRegionAvailX() - ImGui.getStyle().getItemSpacingX()) / 2f;
if (ImGui.button("Start Export", buttonSize, 25)) {
createExportSettings(null).thenAccept(settings -> {
if (settings != null) {
close = true;
Flashback.EXPORT_JOB = new ExportJob(settings);
}
});
}
ImGui.sameLine();
if (ImGui.button("Add to Queue", buttonSize, 25)) {
jobName.set("Job #" + (ExportJobQueue.count()+1));
ImGui.openPopup("QueuedJobName");
}
ImGui.closeCurrentPopup();
if (ImGui.beginPopup("QueuedJobName")) {
ImGui.setNextItemWidth(100);
ImGui.inputText("Job Name", jobName);
if (ImGui.button("Queue Job")) {
createExportSettings(ImGuiHelper.getString(jobName)).thenAccept(settings -> {
if (settings != null) {
close = true;
ExportJobQueue.queuedJobs.add(settings);
}
});
}
ImGui.sameLine();
if (ImGui.button("Back")) {
ImGui.closeCurrentPopup();
}
ImGui.endPopup();
}
ImGuiHelper.endPopupModalCloseable();
}
close = false;
}
private static CompletableFuture<ExportSettings> createExportSettings(@Nullable String name) {
int numBitrate;
if (useMaximumBitrate) {
numBitrate = 0;
} else {
numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
}
String encoder = videoCodec.getEncoders()[selectedVideoEncoder[0]];
Path defaultExportPath = FabricLoader.getInstance().getGameDir();
String defaultName = null;
if (name != null) {
try {
defaultName = FileUtil.findAvailableName(defaultExportPath, name, "." + container.extension());
} catch (Exception ignored) {}
}
if (defaultName == null) {
defaultName = "output." + container.extension();
}
String defaultExportPathString = defaultExportPath.toString();
return AsyncFileDialogs.saveFileDialog(defaultExportPathString, defaultName,
container.extension(), container.extension()).thenApply(pathStr -> {
if (pathStr != null) {
int start = Math.max(0, startEndTick[0]);
int end = Math.max(start, startEndTick[1]);
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
int totalTicks = replayServer.getTotalReplayTicks();
start = Math.min(start, totalTicks);
end = Math.min(end, totalTicks);
}
EditorState editorState = EditorStateManager.getCurrent();
if (editorState == null) {
return null;
}
LocalPlayer player = Minecraft.getInstance().player;
if (player == null) {
return null;
}
Path path = Path.of(pathStr);
return new ExportSettings(name, editorState.copy(),
player.position(), player.getYRot(), player.getXRot(),
resolution[0], resolution[1], start, end,
Math.max(1, framerate.get()), resetRng, container, videoCodec, encoder, numBitrate, recordAudio, path);
}
return null;
});
}
private static int stringToBitrate(String string) {
@@ -210,7 +305,7 @@ public class StartExportWindow {
public static void open() {
open = true;
EditorState editorState = EditorStateCache.getCurrent();
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.exportStartTicks >= 0) {
startEndTick[0] = editorState.exportStartTicks;
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,11 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.visuals.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import imgui.ImGui;
@@ -12,108 +17,217 @@ public class VisualsWindow {
private static final int[] intBuffer = new int[]{0};
public static void render() {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
return;
}
FlashbackMeta metadata = replayServer.getMetadata();
EditorState editorState = EditorStateManager.get(metadata.replayIdentifier);
ReplayVisuals visuals = editorState.replayVisuals;
if (ImGui.begin("Visuals")) {
ImGuiHelper.separatorWithText("GUI");
if (ImGui.checkbox("Chat", ReplayVisuals.showChat)) {
ReplayVisuals.showChat = !ReplayVisuals.showChat;
if (ImGui.checkbox("Chat", visuals.showChat)) {
visuals.showChat = !visuals.showChat;
editorState.markDirty();
}
if (ImGui.checkbox("Boss Bar", ReplayVisuals.showBossBar)) {
ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar;
if (ImGui.checkbox("Boss Bar", visuals.showBossBar)) {
visuals.showBossBar = !visuals.showBossBar;
editorState.markDirty();
}
if (ImGui.checkbox("Title Text", ReplayVisuals.showTitleText)) {
ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText;
if (ImGui.checkbox("Title Text", visuals.showTitleText)) {
visuals.showTitleText = !visuals.showTitleText;
editorState.markDirty();
}
if (ImGui.checkbox("Scoreboard", ReplayVisuals.showScoreboard)) {
ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard;
if (ImGui.checkbox("Scoreboard", visuals.showScoreboard)) {
visuals.showScoreboard = !visuals.showScoreboard;
editorState.markDirty();
}
if (ImGui.checkbox("Action Bar", ReplayVisuals.showActionBar)) {
ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar;
if (ImGui.checkbox("Action Bar", visuals.showActionBar)) {
visuals.showActionBar = !visuals.showActionBar;
editorState.markDirty();
}
ImGuiHelper.separatorWithText("World");
if (ImGui.checkbox("Render Blocks", ReplayVisuals.renderBlocks)) {
ReplayVisuals.renderBlocks = !ReplayVisuals.renderBlocks;
if (ImGui.checkbox("Render Blocks", visuals.renderBlocks)) {
visuals.renderBlocks = !visuals.renderBlocks;
editorState.markDirty();
}
if (ImGui.checkbox("Render Entities", ReplayVisuals.renderEntities)) {
ReplayVisuals.renderEntities = !ReplayVisuals.renderEntities;
if (ImGui.checkbox("Render Entities", visuals.renderEntities)) {
visuals.renderEntities = !visuals.renderEntities;
editorState.markDirty();
}
if (ImGui.checkbox("Render Players", ReplayVisuals.renderPlayers)) {
ReplayVisuals.renderPlayers = !ReplayVisuals.renderPlayers;
if (ImGui.checkbox("Render Players", visuals.renderPlayers)) {
visuals.renderPlayers = !visuals.renderPlayers;
editorState.markDirty();
}
if (ImGui.checkbox("Render Particles", ReplayVisuals.renderParticles)) {
ReplayVisuals.renderParticles = !ReplayVisuals.renderParticles;
if (ImGui.checkbox("Render Particles", visuals.renderParticles)) {
visuals.renderParticles = !visuals.renderParticles;
editorState.markDirty();
}
if (ImGui.checkbox("Render Sky", ReplayVisuals.renderSky)) {
ReplayVisuals.renderSky = !ReplayVisuals.renderSky;
if (ImGui.checkbox("Render Sky", visuals.renderSky)) {
visuals.renderSky = !visuals.renderSky;
editorState.markDirty();
}
if (ImGui.checkbox("Render Nametags", ReplayVisuals.renderNametags)) {
ReplayVisuals.renderNametags = !ReplayVisuals.renderNametags;
if (ImGui.checkbox("Render Nametags", visuals.renderNametags)) {
visuals.renderNametags = !visuals.renderNametags;
editorState.markDirty();
}
ImGuiHelper.separatorWithText("Overrides");
// Fog distance
if (ImGui.checkbox("Override Fog", ReplayVisuals.overrideFog)) {
ReplayVisuals.overrideFog = !ReplayVisuals.overrideFog;
if (ImGui.checkbox("Override Fog", visuals.overrideFog)) {
visuals.overrideFog = !visuals.overrideFog;
editorState.markDirty();
}
if (ReplayVisuals.overrideFog) {
floatBuffer[0] = ReplayVisuals.overrideFogStart;
if (visuals.overrideFog) {
floatBuffer[0] = visuals.overrideFogStart;
if (ImGui.sliderFloat("Start", floatBuffer, 0.0f, 512.0f)) {
ReplayVisuals.overrideFogStart = floatBuffer[0];
visuals.overrideFogStart = floatBuffer[0];
editorState.markDirty();
}
floatBuffer[0] = ReplayVisuals.overrideFogEnd;
floatBuffer[0] = visuals.overrideFogEnd;
if (ImGui.sliderFloat("End", floatBuffer, 0.0f, 512.0f)) {
ReplayVisuals.overrideFogEnd = floatBuffer[0];
visuals.overrideFogEnd = floatBuffer[0];
editorState.markDirty();
}
}
// FOV
if (ImGui.checkbox("Override FOV", ReplayVisuals.overrideFov)) {
ReplayVisuals.overrideFov = !ReplayVisuals.overrideFov;
if (ImGui.checkbox("Override FOV", visuals.overrideFov)) {
visuals.overrideFov = !visuals.overrideFov;
Minecraft.getInstance().levelRenderer.needsUpdate();
editorState.markDirty();
}
if (ReplayVisuals.overrideFov) {
floatBuffer[0] = ReplayVisuals.overrideFovAmount;
if (ImGui.sliderFloat("FOV", floatBuffer, 0.1f, 110.0f, "%.1f")) {
ReplayVisuals.setFov(floatBuffer[0]);
if (visuals.overrideFov) {
floatBuffer[0] = visuals.overrideFovAmount;
if (ImGui.sliderFloat("FOV", floatBuffer, 1.0f, 110.0f, "%.1f")) {
visuals.setFov(floatBuffer[0]);
editorState.markDirty();
}
}
// Time
if (ImGui.checkbox("Override Time", ReplayVisuals.overrideTimeOfDay >= 0)) {
if (ReplayVisuals.overrideTimeOfDay >= 0) {
ReplayVisuals.overrideTimeOfDay = -1;
if (ImGui.checkbox("Override Time", visuals.overrideTimeOfDay >= 0)) {
if (visuals.overrideTimeOfDay >= 0) {
visuals.overrideTimeOfDay = -1;
} else {
ReplayVisuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000);
visuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000);
}
editorState.markDirty();
}
if (visuals.overrideTimeOfDay >= 0) {
intBuffer[0] = (int) visuals.overrideTimeOfDay;
if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) {
visuals.overrideTimeOfDay = intBuffer[0];
editorState.markDirty();
}
}
if (ReplayVisuals.overrideTimeOfDay >= 0) {
intBuffer[0] = (int) ReplayVisuals.overrideTimeOfDay;
if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) {
ReplayVisuals.overrideTimeOfDay = intBuffer[0];
// Camera shake
if (ImGui.checkbox("Camera Shake", visuals.overrideCameraShake)) {
visuals.overrideCameraShake = !visuals.overrideCameraShake;
editorState.markDirty();
}
if (visuals.overrideCameraShake) {
if (ImGui.checkbox("Split Y/X", visuals.cameraShakeSplitParams)) {
visuals.cameraShakeSplitParams = !visuals.cameraShakeSplitParams;
editorState.markDirty();
}
if (visuals.cameraShakeSplitParams) {
ImGui.setNextItemWidth(100);
floatBuffer[0] = visuals.cameraShakeXFrequency;
if (ImGui.sliderFloat("Frequency X", floatBuffer, 0.1f, 10.0f, "%.1f")) {
visuals.cameraShakeXFrequency = floatBuffer[0];
editorState.markDirty();
}
ImGui.setNextItemWidth(100);
floatBuffer[0] = visuals.cameraShakeXAmplitude;
if (ImGui.sliderFloat("Amplitude X", floatBuffer, 0.0f, 10.0f, "%.1f")) {
visuals.cameraShakeXAmplitude = floatBuffer[0];
editorState.markDirty();
}
ImGui.setNextItemWidth(100);
floatBuffer[0] = visuals.cameraShakeYFrequency;
if (ImGui.sliderFloat("Frequency Y", floatBuffer, 0.1f, 10.0f, "%.1f")) {
visuals.cameraShakeYFrequency = floatBuffer[0];
editorState.markDirty();
}
ImGui.setNextItemWidth(100);
floatBuffer[0] = visuals.cameraShakeYAmplitude;
if (ImGui.sliderFloat("Amplitude Y", floatBuffer, 0.0f, 10.0f, "%.1f")) {
visuals.cameraShakeYAmplitude = floatBuffer[0];
editorState.markDirty();
}
} else {
ImGui.setNextItemWidth(100);
floatBuffer[0] = (visuals.cameraShakeXFrequency + visuals.cameraShakeYFrequency)/2.0f;
if (ImGui.sliderFloat("Frequency", floatBuffer, 0.1f, 10.0f, "%.1f")) {
visuals.cameraShakeXFrequency = floatBuffer[0];
visuals.cameraShakeYFrequency = floatBuffer[0];
editorState.markDirty();
}
ImGui.setNextItemWidth(100);
floatBuffer[0] = (visuals.cameraShakeXAmplitude + visuals.cameraShakeYAmplitude)/2.0f;
if (ImGui.sliderFloat("Amplitude", floatBuffer, 0.0f, 10.0f, "%.1f")) {
visuals.cameraShakeXAmplitude = floatBuffer[0];
visuals.cameraShakeYAmplitude = floatBuffer[0];
editorState.markDirty();
}
}
}
// Camera Roll
if (ImGui.checkbox("Camera Roll", visuals.overrideRoll)) {
visuals.overrideRoll = !visuals.overrideRoll;
Minecraft.getInstance().levelRenderer.needsUpdate();
editorState.markDirty();
}
if (visuals.overrideRoll) {
floatBuffer[0] = visuals.overrideRollAmount;
if (ImGui.sliderFloat("Roll", floatBuffer, -180.0f, 180.0f, "%.1f")) {
visuals.overrideRollAmount = floatBuffer[0];
Minecraft.getInstance().levelRenderer.needsUpdate();
editorState.markDirty();
}
}
ImGuiHelper.separatorWithText("Other");
if (ImGui.checkbox("Rule of Thirds Guide", ReplayVisuals.ruleOfThirdsGuide)) {
ReplayVisuals.ruleOfThirdsGuide = !ReplayVisuals.ruleOfThirdsGuide;
if (ImGui.checkbox("Rule of Thirds Guide", visuals.ruleOfThirdsGuide)) {
visuals.ruleOfThirdsGuide = !visuals.ruleOfThirdsGuide;
editorState.markDirty();
}
if (ImGui.checkbox("Center Guide", ReplayVisuals.centerGuide)) {
ReplayVisuals.centerGuide = !ReplayVisuals.centerGuide;
if (ImGui.checkbox("Center Guide", visuals.centerGuide)) {
visuals.centerGuide = !visuals.centerGuide;
editorState.markDirty();
}
ReplayVisuals.sizing = ImGuiHelper.enumCombo("Sizing", ReplayVisuals.sizing);
if (ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) {
ReplayVisuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", ReplayVisuals.changeAspectRatio);
if (ImGui.checkbox("Camera Path", visuals.cameraPath)) {
visuals.cameraPath = !visuals.cameraPath;
editorState.markDirty();
}
visuals.sizing = ImGuiHelper.enumCombo("Sizing", visuals.sizing);
if (visuals.sizing == Sizing.CHANGE_ASPECT_RATIO) {
visuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", visuals.changeAspectRatio);
editorState.markDirty();
}
}
ImGui.end();
@@ -8,6 +8,7 @@ import net.fabricmc.loader.api.FabricLoader;
import org.bytedeco.ffmpeg.avutil.AVComponentDescriptor;
import org.bytedeco.ffmpeg.avutil.AVFrame;
import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.ffmpeg.global.swscale;
import org.bytedeco.ffmpeg.swscale.SwsContext;
@@ -24,6 +25,7 @@ import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -51,7 +53,8 @@ public class AsyncVideoEncoder implements AutoCloseable {
private static final int SRC_PIXEL_FORMAT = avutil.AV_PIX_FMT_RGBA;
private record ImageFrame(long pointer, int size, int width, int height, int channels, int imageDepth, int stride, int pixelFormat) implements AutoCloseable {
private record ImageFrame(long pointer, int size, int width, int height, int channels, int imageDepth, int stride, int pixelFormat,
@Nullable FloatBuffer audioBuffer) implements AutoCloseable {
public void close() {
MemoryUtil.nmemFree(this.pointer);
}
@@ -70,6 +73,11 @@ public class AsyncVideoEncoder implements AutoCloseable {
}
int maxBitrate = Math.min(288_000_000, 5000 + (int) Math.ceil(width * height * settings.framerate()));
if (settings.encoder().equals("libsvtav1")) {
maxBitrate = Math.min(100_000_000, maxBitrate);
}
int bitrate;
if (settings.bitrate() <= 0) {
bitrate = maxBitrate;
@@ -89,7 +97,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat;
final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
filename, width, height, 0);
filename, width, height, settings.recordAudio() ? 1 : 0);
recorder.setVideoBitrate(bitrate);
recorder.setVideoCodec(settings.codec().codecId());
@@ -97,7 +105,14 @@ public class AsyncVideoEncoder implements AutoCloseable {
recorder.setFormat(extension);
recorder.setFrameRate(fps);
recorder.setPixelFormat(dstPixelFormat);
recorder.setGopSize((int) Math.ceil(fps * 2));
recorder.setGopSize((int) Math.max(20, Math.min(240, Math.ceil(fps * 2))));
if (settings.recordAudio()) {
recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
recorder.setSampleFormat(avutil.AV_SAMPLE_FMT_FLTP);
recorder.setSampleRate(44100);
recorder.setAudioBitrate(320000);
}
recorder.start();
@@ -144,6 +159,9 @@ public class AsyncVideoEncoder implements AutoCloseable {
recorder.recordImage(src.width, src.height, src.imageDepth, src.channels,
src.stride, src.pixelFormat, buffer);
if (src.audioBuffer != null) {
recorder.recordSamples(src.audioBuffer);
}
if (this.reusePictureData != null) {
if (this.reusePictureData.offer(src.pointer)) { // try adding to the reuse queue, ignore if full
@@ -259,7 +277,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
0, src.height, picture_ptr, picture.linesize());
this.encodeQueue.put(new ImageFrame(tempPointerAddress, dstSize, dstWidth, dstHeight, dstChannels, dstDepth,
dstWidth, dstPixelFormat));
dstWidth, dstPixelFormat, src.audioBuffer));
} catch (Throwable t) {
try {
av_frame_free(picture);
@@ -299,7 +317,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
}
}
public void encode(NativeImage src) {
public void encode(NativeImage src, @Nullable FloatBuffer audioBuffer) {
checkEncodeError(src);
if (this.finishRescaleThread.get() || this.finishEncodeThread.get() || this.finishedWriting.get()) {
@@ -310,7 +328,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
while (true) {
try {
ImageFrame imageFrame = new ImageFrame(src.pixels, (int) src.size, src.getWidth(), src.getHeight(),
4, Frame.DEPTH_INT, src.getWidth(), SRC_PIXEL_FORMAT);
4, Frame.DEPTH_INT, src.getWidth(), SRC_PIXEL_FORMAT, audioBuffer);
if (this.rescaleQueue != null) {
this.rescaleQueue.put(imageFrame);
} else {
@@ -368,7 +386,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
if (this.reusePictureData != null) {
for (Long address : this.reusePictureData) {
if (address != 0) {
if (address != null && address != 0) {
MemoryUtil.nmemFree(address);
}
}
@@ -9,25 +9,44 @@ import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import com.moulberry.flashback.FixedDeltaTracker;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.compat.IrisApiWrapper;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.state.KeyframeTrack;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.doubles.DoubleList;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.floats.FloatList;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Screenshot;
import net.minecraft.client.gui.Font;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.FogRenderer;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import org.joml.Matrix4f;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.openal.SOFTLoopback;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
@@ -42,6 +61,8 @@ public class ExportJob {
private long escapeCancelStartMillis = -1;
private long renderStartTime;
private final Random particleRandom;
private boolean showingDebug = false;
private boolean pressedDebugKey = false;
private long serverTickTimeNanos = 0;
@@ -50,10 +71,13 @@ public class ExportJob {
private long encodeTimeNanos = 0;
private long downloadTimeNanos = 0;
private double audioSamples = 0.0;
private final AtomicBoolean finishedServerTick = new AtomicBoolean(false);
public ExportJob(ExportSettings settings) {
this.settings = settings;
this.particleRandom = this.settings.resetRng() ? new Random(2000) : null;
}
public boolean isRunning() {
@@ -76,12 +100,21 @@ public class ExportJob {
return this.settings.resolutionY();
}
public Random getParticleRandom() {
return this.particleRandom;
}
public ExportSettings getSettings() {
return this.settings;
}
public void run() {
ReplayServer replayServer = Flashback.getReplayServer();
if (this.running || replayServer == null) {
throw new IllegalStateException("run() called twice");
}
this.running = true;
Minecraft.getInstance().mouseHandler.releaseMouse();
UUID uuid = UUID.randomUUID();
@@ -108,6 +141,7 @@ public class ExportJob {
} finally {
this.running = false;
this.shouldChangeFramebufferSize = false;
Minecraft.getInstance().resizeDisplay();
try {
@@ -136,23 +170,29 @@ public class ExportJob {
return;
}
Random random = new Random(1000);
Random mathRandom = this.settings.resetRng() ? Utils.getInternalMathRandom() : null;
this.setup(replayServer);
this.updateRandoms(random, mathRandom);
shouldChangeFramebufferSize = true;
Minecraft.getInstance().resizeDisplay();
double framesPerTick = this.settings.framerate() / 20.0;
DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate());
int currentFrame = 0;
int totalFrames = (int) Math.ceil((this.settings.endTick() - this.settings.startTick() + 1) * framesPerTick);
int clientTickCount = 0;
this.renderStartTime = System.currentTimeMillis();
EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier);
EditorState editorState = EditorStateManager.get(replayServer.getMetadata().replayIdentifier);
while (currentFrame <= totalFrames) {
double currentTickDouble = currentFrame / framesPerTick;
double lastTickDouble = 0;
for (int tickIndex = 0; tickIndex < ticks.size(); tickIndex++) {
double 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;
@@ -165,6 +205,7 @@ public class ExportJob {
// Tick client
while (clientTickCount < currentTick) {
start = System.nanoTime();
this.updateRandoms(random, mathRandom);
this.runClientTick();
clientTickTimeNanos += System.nanoTime() - start;
@@ -204,68 +245,132 @@ public class ExportJob {
this.tryUnfreezeClient();
editorState.applyKeyframes(Minecraft.getInstance(), (float)(this.settings.startTick() + currentTickDouble));
KeyframeHandler keyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance());
editorState.applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble));
RenderTarget oldTarget = Minecraft.getInstance().getMainRenderTarget();
SaveableFramebuffer saveable = downloader.take();
RenderTarget renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY());
boolean asyncFrameCapture = !IrisApiWrapper.isIrisAvailable() || !IrisApiWrapper.isShaderPackInUse();
Minecraft.getInstance().mainRenderTarget = renderTarget;
RenderTarget oldTarget = null;
SaveableFramebuffer saveable = null;
RenderTarget renderTarget;
if (asyncFrameCapture) {
oldTarget = Minecraft.getInstance().getMainRenderTarget();
saveable = downloader.take();
renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY());
Minecraft.getInstance().mainRenderTarget = renderTarget;
} else {
renderTarget = Minecraft.getInstance().mainRenderTarget;
}
renderTarget.bindWrite(true);
RenderSystem.clear(16640, Minecraft.ON_OSX);
// Perform rendering
PerfectFrames.waitUntilFrameReady();
FogRenderer.setupNoFog();
RenderSystem.enableCull();
Minecraft.getInstance().timer.deltaTicks = 1 / (float) framesPerTick;
Minecraft.getInstance().timer.realtimeDeltaTicks = 1 / (float) framesPerTick;
Minecraft.getInstance().timer.deltaTicks = deltaTicksFloat;
Minecraft.getInstance().timer.realtimeDeltaTicks = deltaTicksFloat;
Minecraft.getInstance().timer.deltaTickResidual = (float) partialTick;
Minecraft.getInstance().timer.pausedDeltaTickResidual = (float) partialTick;
start = System.nanoTime();
Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(1 / (float) framesPerTick, (float) partialTick), true);
Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(deltaTicksFloat, (float) partialTick), true);
renderTimeNanos += System.nanoTime() - start;
renderTarget.unbindWrite();
Minecraft.getInstance().mainRenderTarget = oldTarget;
boolean cancel;
this.shouldChangeFramebufferSize = false;
boolean cancel = finishFrame(renderTarget, infoRenderTarget, currentFrame, totalFrames);
this.shouldChangeFramebufferSize = true;
// Capture audio if necessary
FloatBuffer audioBuffer = null;
if (this.settings.recordAudio()) {
long device = Minecraft.getInstance().getSoundManager().soundEngine.library.currentDevice;
submitDownloadedFrames(encoder, downloader, false);
audioSamples += 44100 / this.settings.framerate();
int renderSamples = (int) audioSamples;
audioSamples -= renderSamples;
downloader.startDownload(saveable);
if (cancel) {
break;
audioBuffer = ByteBuffer.allocateDirect(renderSamples * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
SOFTLoopback.alcRenderSamplesSOFT(device, audioBuffer, renderSamples);
}
currentFrame += 1;
if (asyncFrameCapture) {
Minecraft.getInstance().mainRenderTarget = oldTarget;
this.shouldChangeFramebufferSize = false;
cancel = finishFrame(renderTarget, infoRenderTarget, tickIndex, ticks.size());
this.shouldChangeFramebufferSize = true;
submitDownloadedFrames(encoder, downloader, false);
saveable.audioBuffer = audioBuffer;
downloader.startDownload(saveable);
} else {
this.shouldChangeFramebufferSize = false;
cancel = finishFrame(renderTarget, infoRenderTarget, tickIndex, ticks.size());
this.shouldChangeFramebufferSize = true;
start = System.nanoTime();
NativeImage image = Screenshot.takeScreenshot(renderTarget);
downloadTimeNanos += System.nanoTime() - start;
start = System.nanoTime();
encoder.encode(image, audioBuffer);
encodeTimeNanos += System.nanoTime() - start;
}
if (cancel) {
ExportJobQueue.drainingQueue = false;
break;
}
}
submitDownloadedFrames(encoder, downloader, true);
encoder.finish();
}
private void updateRandoms(Random random, Random mathRandom) {
if (!this.settings.resetRng()) {
return;
}
Minecraft minecraft = Minecraft.getInstance();
long connectionSeed = random.nextLong();
long levelSeed = random.nextLong();
long entitySeed = random.nextLong();
long mathSeed = random.nextLong();
long particleSeed = random.nextLong();
if (minecraft.getConnection() != null) {
minecraft.getConnection().random.setSeed(connectionSeed);
}
if (minecraft.level != null) {
minecraft.level.random.setSeed(levelSeed);
for (Entity entity : minecraft.level.entitiesForRendering()) {
if (entity == null) {
continue;
}
entity.getRandom().setSeed(entitySeed ^ entity.getUUID().getMostSignificantBits());
}
}
if (mathRandom != null) {
mathRandom.setSeed(mathSeed);
}
this.particleRandom.setSeed(particleSeed);
}
private void setup(ReplayServer replayServer) {
Minecraft minecraft = Minecraft.getInstance();
// Clear particles
minecraft.particleEngine.clearParticles();
// Apply keyframes at start tick
EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier);
editorState.applyKeyframes(Minecraft.getInstance(), this.settings.startTick());
// Ensure position is updated before doing anything else
this.runClientTick();
this.setServerTickAndWait(replayServer, replayServer.getReplayTick(), true);
int currentTick = Math.max(0, this.settings.startTick() - 20);
// Ensure replay server is paused at currentTick
@@ -279,6 +384,17 @@ public class ExportJob {
currentTick += 1;
}
// Apply initial position and keyframes at start tick
LocalPlayer player = minecraft.player;
if (player != null) {
Vec3 position = this.settings.initialCameraPosition();
player.moveTo(position.x, position.y, position.z, this.settings.initialCameraYaw(), this.settings.initialCameraPitch());
player.setDeltaMovement(Vec3.ZERO);
}
EditorState editorState = EditorStateManager.get(replayServer.getMetadata().replayIdentifier);
editorState.applyKeyframes(new MinecraftKeyframeHandler(Minecraft.getInstance()), this.settings.startTick());
this.runClientTick();
// Ensured replay server is paused at startTick
this.setServerTickAndWait(replayServer, this.settings.startTick(), true);
this.runClientTick();
@@ -306,6 +422,7 @@ public class ExportJob {
while (Minecraft.getInstance().pollTask()) {}
Minecraft.getInstance().tick();
Minecraft.getInstance().getSoundManager().updateSource(Minecraft.getInstance().gameRenderer.getMainCamera());
this.tryUnfreezeClient();
}
@@ -317,18 +434,18 @@ public class ExportJob {
}
private void submitDownloadedFrames(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, boolean drain) {
NativeImage image;
SaveableFramebufferQueue.DownloadedFrame frame;
while (true) {
long start = System.nanoTime();
image = downloader.finishDownload(drain);
frame = downloader.finishDownload(drain);
downloadTimeNanos += System.nanoTime() - start;
if (image == null) {
if (frame == null) {
break;
}
start = System.nanoTime();
encoder.encode(image);
encoder.encode(frame.image(), frame.audioBuffer());
encodeTimeNanos += System.nanoTime() - start;
}
}
@@ -373,7 +490,7 @@ public class ExportJob {
RenderSystem.clear(16640, Minecraft.ON_OSX);
int guiScale = 4;
float guiScale = 4f;
int scaledWidth = (int) Math.ceil(infoRenderTarget.width / guiScale);
int scaledHeight = (int) Math.ceil(infoRenderTarget.height / guiScale);
@@ -387,6 +504,11 @@ public class ExportJob {
List<String> lines = new ArrayList<>();
if (this.settings.name() != null) {
lines.add(this.settings.name());
lines.add("");
}
lines.add("Exported Frames: " + currentFrame + "/" + totalFrames);
long elapsed = currentTime - this.renderStartTime;
@@ -476,4 +598,54 @@ public class ExportJob {
}
}
private static class TickrateKeyframeCapture implements KeyframeHandler {
private float tickrate = 20.0f;
@Override
public EnumSet<KeyframeType> supportedKeyframes() {
return EnumSet.of(KeyframeType.SPEED, KeyframeType.TIMELAPSE);
}
@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);
double residual = 0;
int currentTick = 0;
TickrateKeyframeCapture capture = new TickrateKeyframeCapture();
int count = endTick - startTick;
while (currentTick <= count) {
capture.tickrate = 20.0f;
editorState.applyKeyframes(capture, startTick + currentTick + (float) residual);
residual += capture.tickrate / fps;
int roundedResidual = (int) residual;
residual -= roundedResidual;
currentTick += roundedResidual;
if (currentTick > count) {
break;
}
ticks.add(currentTick + residual);
}
return ticks;
}
}
@@ -0,0 +1,16 @@
package com.moulberry.flashback.exporting;
import java.util.ArrayList;
import java.util.List;
public class ExportJobQueue {
public static List<ExportSettings> queuedJobs = new ArrayList<>();
public static boolean drainingQueue = false;
public static int count() {
return queuedJobs.size();
}
}
@@ -2,10 +2,24 @@ package com.moulberry.flashback.exporting;
import com.moulberry.flashback.combo_options.VideoCodec;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.visuals.ReplayVisuals;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
public record ExportSettings(int resolutionX, int resolutionY, int startTick, int endTick, double framerate, VideoContainer container,
VideoCodec codec, String encoder, int bitrate, Path output) {
public record ExportSettings(@Nullable String name, EditorState editorState,
// Initial state
Vec3 initialCameraPosition, float initialCameraYaw, float initialCameraPitch,
// Capture
int resolutionX, int resolutionY, int startTick, int endTick, double framerate,
boolean resetRng,
// Video
VideoContainer container, VideoCodec codec, String encoder, int bitrate,
// Audio
boolean recordAudio,
// Output
Path output) {
}
@@ -40,6 +40,10 @@ public class PixelFormatHelper {
IntPointer pixFmts = codec.pix_fmts();
if (pixFmts == null) {
return avutil.AV_PIX_FMT_YUV420P;
}
int index = 0;
while (true) {
int pixFmt = pixFmts.get(index);
@@ -2,15 +2,18 @@ package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.pipeline.MainTarget;
import com.mojang.blaze3d.platform.NativeImage;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryUtil;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
public class SaveableFramebuffer implements AutoCloseable {
private MainTarget framebuffer;
private int pboId;
public @Nullable FloatBuffer audioBuffer;
private boolean isDownloading = false;
@@ -3,6 +3,8 @@ package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import org.jetbrains.annotations.Nullable;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
@@ -37,7 +39,9 @@ public class SaveableFramebufferQueue implements AutoCloseable {
this.waiting.add(texture);
}
public @Nullable NativeImage finishDownload(boolean drain) {
record DownloadedFrame(NativeImage image, @Nullable FloatBuffer audioBuffer) {}
public @Nullable DownloadedFrame finishDownload(boolean drain) {
if (this.waiting.isEmpty()) {
return null;
}
@@ -47,9 +51,13 @@ public class SaveableFramebufferQueue implements AutoCloseable {
}
SaveableFramebuffer texture = this.waiting.removeFirst();
NativeImage nativeImage = texture.finishDownload(this.width, this.height);
FloatBuffer audioBuffer = texture.audioBuffer;
texture.audioBuffer = null;
this.available.add(texture);
return nativeImage;
return new DownloadedFrame(nativeImage, audioBuffer);
}
@Override
@@ -0,0 +1,12 @@
package com.moulberry.flashback.ext;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.state.BlockState;
public interface LevelChunkExt {
void flashback$setBlockStateWithoutUpdates(BlockPos blockPos, BlockState blockState);
int flashback$getCachedChunkId();
void flashback$setCachedChunkId(int id);
}
@@ -1,8 +0,0 @@
package com.moulberry.flashback.ext;
public interface LevelChunkSectionExt {
int flashback$getCachedChunkId();
void flashback$setCachedChunkId(int id);
}
@@ -9,8 +9,8 @@ import java.util.UUID;
public interface MinecraftExt {
void flashback$forceClientTick();
void flashback$applyKeyframes();
void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem, UUID playbackUUID, Path path);
float flashback$getLocalPlayerPartialTick();
float flashback$getLocalPlayerPartialTick(float originalPartialTick);
}
@@ -0,0 +1,7 @@
package com.moulberry.flashback.ext;
public interface OptionsExt {
int flashback$getOriginalFov();
}
@@ -44,7 +44,7 @@ import java.util.function.Consumer;
public class AsyncReplaySaver {
private final ArrayBlockingQueue<Consumer<ReplayWriter>> tasks = new ArrayBlockingQueue<>(256);
private final ArrayBlockingQueue<Consumer<ReplayWriter>> tasks = new ArrayBlockingQueue<>(1024);
private final AtomicReference<Throwable> error = new AtomicReference<>(null);
private final AtomicBoolean shouldStop = new AtomicBoolean(false);
private final AtomicBoolean hasStopped = new AtomicBoolean(false);
@@ -1,69 +1,105 @@
package com.moulberry.flashback.keyframe;
import com.google.gson.*;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
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.TickrateKeyframe;
import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe;
import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import java.lang.reflect.Type;
import java.util.Objects;
import java.util.function.Consumer;
public abstract class Keyframe<T> {
public abstract class Keyframe {
public final Class<T> operandClass;
private InterpolationType interpolationType = InterpolationType.SMOOTH;
public Keyframe(Class<T> operandClass) {
this.operandClass = operandClass;
}
private InterpolationType interpolationType = InterpolationType.DEFAULT;
public InterpolationType interpolationType() {
return interpolationType;
}
public void interpolationType(InterpolationType interpolationType) {
this.interpolationType = interpolationType;
this.interpolationType = Objects.requireNonNullElse(interpolationType, InterpolationType.DEFAULT);
}
public abstract void apply(T t);
public abstract void applyInterpolated(T t, Keyframe other, float amount);
public abstract void applyInterpolatedSmooth(T t, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount,
public abstract Keyframe copy();
public abstract void apply(KeyframeHandler t);
public abstract void applyInterpolated(KeyframeHandler t, Keyframe other, float amount);
public abstract void applyInterpolatedSmooth(KeyframeHandler t, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount,
float lerpAmount, boolean lerpFromRight);
public static class TypeAdapter implements JsonSerializer<Keyframe<?>>, JsonDeserializer<Keyframe<?>> {
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {}
public static class TypeAdapter implements JsonSerializer<Keyframe>, JsonDeserializer<Keyframe> {
@Override
public Keyframe<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
public Keyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("type").getAsString();
Keyframe<?> keyframe = switch (type) {
String type;
if (jsonObject.has("type")) {
type = jsonObject.get("type").getAsString();
} else if (jsonObject.has("position") && jsonObject.has("rotation")) {
type = "camera";
} else if (jsonObject.has("center") && jsonObject.has("distance")) {
type = "camera_orbit";
} else if (jsonObject.has("frequencyX") && jsonObject.has("amplitudeX")) {
type = "camera_shake";
} else if (jsonObject.has("fov")) {
type = "fov";
} else if (jsonObject.has("tickrate")) {
type = "tickrate";
} else if (jsonObject.has("time")) {
type = "time";
} else {
throw new RuntimeException("Unable to determine type of keyframe for: " + jsonObject);
}
Keyframe keyframe = switch (type) {
case "camera" -> context.deserialize(json, CameraKeyframe.class);
case "camera_orbit" -> context.deserialize(json, CameraOrbitKeyframe.class);
case "fov" -> context.deserialize(json, FOVKeyframe.class);
case "tickrate" -> context.deserialize(json, TickrateKeyframe.class);
case "timelapse" -> context.deserialize(json, TimelapseKeyframe.class);
case "time" -> context.deserialize(json, TimeOfDayKeyframe.class);
case "camera_shake" -> context.deserialize(json, CameraShakeKeyframe.class);
default -> throw new IllegalStateException("Unknown keyframe type: " + type);
};
keyframe.interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
keyframe.interpolationType(context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class));
return keyframe;
}
@Override
public JsonElement serialize(Keyframe<?> src, Type typeOfSrc, JsonSerializationContext context) {
public JsonElement serialize(Keyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject;
if (src instanceof CameraKeyframe cameraKeyframe) {
jsonObject = (JsonObject) context.serialize(cameraKeyframe);
jsonObject.addProperty("type", "camera");
} else if (src instanceof FOVKeyframe fovKeyframe) {
jsonObject = (JsonObject) context.serialize(fovKeyframe);
jsonObject.addProperty("type", "fov");
} else if (src instanceof TickrateKeyframe tickrateKeyframe) {
jsonObject = (JsonObject) context.serialize(tickrateKeyframe);
jsonObject.addProperty("type", "tickrate");
} else if (src instanceof TimeOfDayKeyframe timeOfDayKeyframe) {
jsonObject = (JsonObject) context.serialize(timeOfDayKeyframe);
jsonObject.addProperty("type", "time");
} else {
throw new IllegalStateException("Unknown keyframe type: " + src.getClass());
switch (src) {
case CameraKeyframe cameraKeyframe -> {
jsonObject = (JsonObject) context.serialize(cameraKeyframe);
jsonObject.addProperty("type", "camera");
}
case CameraOrbitKeyframe cameraOrbitKeyframe -> {
jsonObject = (JsonObject) context.serialize(cameraOrbitKeyframe);
jsonObject.addProperty("type", "camera_orbit");
}
case FOVKeyframe fovKeyframe -> {
jsonObject = (JsonObject) context.serialize(fovKeyframe);
jsonObject.addProperty("type", "fov");
}
case TickrateKeyframe tickrateKeyframe -> {
jsonObject = (JsonObject) context.serialize(tickrateKeyframe);
jsonObject.addProperty("type", "tickrate");
}
case TimeOfDayKeyframe timeOfDayKeyframe -> {
jsonObject = (JsonObject) context.serialize(timeOfDayKeyframe);
jsonObject.addProperty("type", "time");
}
case CameraShakeKeyframe cameraShakeKeyframe -> {
jsonObject = (JsonObject) context.serialize(cameraShakeKeyframe);
jsonObject.addProperty("type", "camera_shake");
}
default -> throw new IllegalStateException("Unknown keyframe type: " + src.getClass());
}
jsonObject.add("interpolation_type", context.serialize(src.interpolationType));
return jsonObject;
@@ -3,9 +3,12 @@ package com.moulberry.flashback.keyframe;
public enum KeyframeType {
CAMERA("Camera"),
CAMERA_ORBIT("Camera Orbit"),
FOV("FOV"),
SPEED("Speed"),
TIME_OF_DAY("Time of day");
TIMELAPSE("Timelapse"),
TIME_OF_DAY("Time of day"),
CAMERA_SHAKE("Camera Shake");
public static final KeyframeType[] KEYFRAME_TYPES = values();
@@ -0,0 +1,42 @@
package com.moulberry.flashback.keyframe.handler;
import com.moulberry.flashback.keyframe.KeyframeType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.util.EnumSet;
public interface KeyframeHandler {
EnumSet<KeyframeType> supportedKeyframes();
default boolean alwaysApplyLastKeyframe() {
return false;
}
default void applyCameraPosition(Vector3f position, float yaw, float pitch, float roll) {
throw new UnsupportedOperationException();
}
default void applyFov(float fov) {
throw new UnsupportedOperationException();
}
default void applyTickrate(float tickrate) {
throw new UnsupportedOperationException();
}
default void applyTimeOfDay(int timeOfDay) {
throw new UnsupportedOperationException();
}
default void applyCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,80 @@
package com.moulberry.flashback.keyframe.handler;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.keyframe.KeyframeType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.phys.Vec3;
import org.joml.Vector3f;
import java.util.EnumSet;
public class MinecraftKeyframeHandler implements KeyframeHandler {
private final Minecraft minecraft;
public MinecraftKeyframeHandler(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public EnumSet<KeyframeType> supportedKeyframes() {
return EnumSet.of(KeyframeType.CAMERA, KeyframeType.CAMERA_ORBIT, KeyframeType.FOV, KeyframeType.TIME_OF_DAY, KeyframeType.CAMERA_SHAKE);
}
@Override
public void applyCameraPosition(Vector3f position, float yaw, float pitch, float roll) {
LocalPlayer player = this.minecraft.player;
if (player != null) {
player.moveTo(position.x, position.y, position.z, yaw, pitch);
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
if (roll > -0.1 && roll < 0.1) {
editorState.replayVisuals.overrideRoll = false;
editorState.replayVisuals.overrideRollAmount = 0.0f;
} else {
editorState.replayVisuals.overrideRoll = true;
editorState.replayVisuals.overrideRollAmount = roll;
}
}
player.setDeltaMovement(Vec3.ZERO);
}
}
@Override
public void applyFov(float fov) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
editorState.replayVisuals.setFov(fov);
}
}
@Override
public void applyTickrate(float tickrate) {
throw new UnsupportedOperationException();
}
@Override
public void applyTimeOfDay(int timeOfDay) {
timeOfDay = timeOfDay % 24000;
if (timeOfDay < 0) {
timeOfDay += 24000;
}
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
editorState.replayVisuals.overrideTimeOfDay = timeOfDay;
}
}
@Override
public void applyCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
editorState.replayVisuals.setCameraShake(frequencyX, amplitudeX, frequencyY, amplitudeY);
}
}
}
@@ -0,0 +1,45 @@
package com.moulberry.flashback.keyframe.handler;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.playback.ReplayServer;
import java.util.EnumSet;
public class ReplayServerKeyframeHandler implements KeyframeHandler {
private final ReplayServer replayServer;
public ReplayServerKeyframeHandler(ReplayServer replayServer) {
this.replayServer = replayServer;
}
@Override
public boolean alwaysApplyLastKeyframe() {
return true;
}
@Override
public EnumSet<KeyframeType> supportedKeyframes() {
return EnumSet.of(KeyframeType.SPEED, KeyframeType.TIMELAPSE);
}
@Override
public void applyFov(float fov) {
throw new UnsupportedOperationException();
}
@Override
public void applyTickrate(float tickrate) {
this.replayServer.setDesiredTickRate(tickrate, false);
}
@Override
public void applyTimeOfDay(int timeOfDay) {
throw new UnsupportedOperationException();
}
@Override
public void applyCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) {
throw new UnsupportedOperationException();
}
}
@@ -3,68 +3,125 @@ package com.moulberry.flashback.keyframe.impl;
import com.google.gson.*;
import com.moulberry.flashback.Interpolation;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.spline.CatmullRom;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.lang.reflect.Type;
public class CameraKeyframe extends Keyframe<Minecraft> {
public class CameraKeyframe extends Keyframe {
private final Vector3f position;
private final Quaternionf quaternion;
public final Vector3f position;
public final Quaternionf quaternion;
public final boolean hasRoll;
private static Quaternionf getQuaternion(Entity entity) {
Quaternionf quaternionf = new Quaternionf();
float angleZ = 0.0f;
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideRoll) {
angleZ = (float) Math.toRadians(editorState.replayVisuals.overrideRollAmount);
}
quaternionf = quaternionf.rotationYXZ((float) -Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), -angleZ);
return quaternionf;
}
public CameraKeyframe(Entity entity) {
this(entity.position().toVector3f(), new Quaternionf().rotationYXZ((float) Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), 0.0f));
this(entity.position().toVector3f(), getQuaternion(entity), shouldHaveRoll());
}
public CameraKeyframe(Vector3f position, Quaternionf quaternion) {
super(Minecraft.class);
public CameraKeyframe(Vector3f position, Quaternionf quaternion, boolean hasRoll) {
this(position, quaternion, hasRoll, InterpolationType.DEFAULT);
}
public CameraKeyframe(Vector3f position, Quaternionf quaternion, boolean hasRoll, InterpolationType interpolationType) {
this.position = position;
this.quaternion = quaternion;
this.hasRoll = hasRoll;
this.interpolationType(interpolationType);
}
@Override
public void apply(Minecraft minecraft) {
LocalPlayer player = minecraft.player;
if (player != null) {
Vector3f euler = this.quaternion.getEulerAnglesYXZ(new Vector3f());
player.moveTo(this.position.x, this.position.y, this.position.z, (float) Mth.wrapDegrees(Math.toDegrees(euler.y)), (float) Mth.wrapDegrees(Math.toDegrees(euler.x)));
player.setDeltaMovement(Vec3.ZERO);
public Keyframe copy() {
return new CameraKeyframe(new Vector3f(this.position), new Quaternionf(this.quaternion), this.hasRoll, this.interpolationType());
}
private static boolean shouldHaveRoll() {
EditorState editorState = EditorStateManager.getCurrent();
return editorState != null && editorState.replayVisuals.overrideRoll && editorState.replayVisuals.overrideRollAmount != 0.0f;
}
private void apply(KeyframeHandler keyframeHandler, Vector3f position, Quaternionf quaternion, float rollScale) {
Vector3f euler = quaternion.getEulerAnglesYXZ(new Vector3f());
float yaw = (float) Mth.wrapDegrees(Math.toDegrees(euler.y));
float pitch = (float) Mth.wrapDegrees(Math.toDegrees(euler.x));
float roll = (float) Mth.wrapDegrees(Math.toDegrees(euler.z)) * rollScale;
// Handle singularity
double test = (double)quaternion.y * (double)quaternion.z - (double)quaternion.w * (double)quaternion.x;
final double MIN_TEST = 0.49999;
final double MAX_TEST = 0.499999;
if (test > MIN_TEST) {
float fixedYaw = (float) Mth.wrapDegrees(Math.toDegrees(2 * Math.atan2(quaternion.z, quaternion.w)));
if (test >= MAX_TEST) {
yaw = fixedYaw;
} else {
yaw = yaw + (float)(Mth.wrapDegrees(fixedYaw - yaw) * (test - MIN_TEST) / (MAX_TEST - MIN_TEST));
}
} else if (test < -MIN_TEST) {
float fixedYaw = (float) Mth.wrapDegrees(Math.toDegrees(-2 * Math.atan2(quaternion.z, quaternion.w)));
if (test <= -MAX_TEST) {
yaw = fixedYaw;
} else {
yaw = yaw + (float)(Mth.wrapDegrees(fixedYaw - yaw) * (test - -MIN_TEST) / (-MAX_TEST - -MIN_TEST));
}
}
// Apply position
keyframeHandler.applyCameraPosition(position, -yaw, pitch, -roll);
}
private static float calculateRollScale(CameraKeyframe left, CameraKeyframe right, float alpha) {
if (left.hasRoll && right.hasRoll) {
return 1.0f;
} else if (left.hasRoll) {
return 1.0f - alpha;
} else if (right.hasRoll) {
return alpha;
} else {
return 0.0f;
}
}
@Override
public void applyInterpolated(Minecraft minecraft, Keyframe genericOther, float amount) {
public void apply(KeyframeHandler keyframeHandler) {
apply(keyframeHandler, this.position, this.quaternion, this.hasRoll ? 1.0f : 0.0f);
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe genericOther, float amount) {
if (!(genericOther instanceof CameraKeyframe other)) {
this.apply(minecraft);
this.apply(keyframeHandler);
return;
}
LocalPlayer player = minecraft.player;
if (player != null) {
double x = Interpolation.linear(this.position.x, other.position.x, amount);
double y = Interpolation.linear(this.position.y, other.position.y, amount);
double z = Interpolation.linear(this.position.z, other.position.z, amount);
Quaternionf quaternion = Interpolation.linear(this.quaternion, other.quaternion, amount);
Vector3f euler = quaternion.getEulerAnglesYXZ(new Vector3f());
player.moveTo(x, y, z, (float) Mth.wrapDegrees(Math.toDegrees(euler.y)), (float) Mth.wrapDegrees(Math.toDegrees(euler.x)));
player.setDeltaMovement(Vec3.ZERO);
}
double x = Interpolation.linear(this.position.x, other.position.x, amount);
double y = Interpolation.linear(this.position.y, other.position.y, amount);
double z = Interpolation.linear(this.position.z, other.position.z, amount);
Quaternionf quaternion = Interpolation.linear(this.quaternion, other.quaternion, amount);
Vector3f position = new Vector3f((float) x, (float) y, (float) z);
apply(keyframeHandler, position, quaternion, calculateRollScale(this, other, amount));
}
@Override
public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) {
LocalPlayer player = minecraft.player;
if (player == null) {
return;
}
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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
@@ -84,9 +141,9 @@ public class CameraKeyframe extends Keyframe<Minecraft> {
((CameraKeyframe)p3).quaternion, time1, time2, time3, amount);
if (lerpAmount >= 0) {
float linearX = (float) Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount);
float linearY = (float) Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount);
float linearZ = (float) Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount);
float linearX = Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount);
float linearY = Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount);
float linearZ = Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount);
Quaternionf linearQuaternion = Interpolation.linear(((CameraKeyframe)p1).quaternion, ((CameraKeyframe)p2).quaternion, lerpAmount);
@@ -103,12 +160,7 @@ public class CameraKeyframe extends Keyframe<Minecraft> {
}
}
Vector3f euler = rotation.getEulerAnglesYXZ(new Vector3f());
float yaw = (float) Mth.wrapDegrees(Math.toDegrees(euler.y));
float pitch = (float) Mth.wrapDegrees(Math.toDegrees(euler.x));
player.moveTo(x, y, z, yaw, pitch);
player.setDeltaMovement(Vec3.ZERO);
apply(keyframeHandler, new Vector3f(x, y, z), rotation, calculateRollScale((CameraKeyframe) p1, (CameraKeyframe) p2, amount));
}
public static class TypeAdapter implements JsonSerializer<CameraKeyframe>, JsonDeserializer<CameraKeyframe> {
@@ -117,7 +169,9 @@ public class CameraKeyframe extends Keyframe<Minecraft> {
JsonObject jsonObject = json.getAsJsonObject();
Vector3f position = context.deserialize(jsonObject.get("position"), Vector3f.class);
Quaternionf rotation = context.deserialize(jsonObject.get("rotation"), Quaternionf.class);
return new CameraKeyframe(position, rotation);
boolean hasRoll = jsonObject.has("has_roll") && jsonObject.get("has_roll").getAsBoolean();
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new CameraKeyframe(position, rotation, hasRoll, interpolationType);
}
@Override
@@ -125,6 +179,9 @@ public class CameraKeyframe extends Keyframe<Minecraft> {
JsonObject jsonObject = new JsonObject();
jsonObject.add("position", context.serialize(src.position));
jsonObject.add("rotation", context.serialize(src.quaternion));
jsonObject.add("has_roll", context.serialize(src.hasRoll));
jsonObject.addProperty("type", "camera");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
@@ -0,0 +1,202 @@
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.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.spline.CatmullRom;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import imgui.ImGui;
import imgui.type.ImFloat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.lang.reflect.Type;
import java.util.function.Consumer;
public class CameraOrbitKeyframe extends Keyframe {
public final Vector3f center;
public float distance;
public float yaw;
public float pitch;
public CameraOrbitKeyframe(Vector3f center, float distance, float yaw, float pitch) {
this(center, distance, yaw, pitch, InterpolationType.DEFAULT);
}
public CameraOrbitKeyframe(Vector3f center, float distance, float yaw, float pitch, InterpolationType interpolationType) {
this.center = center;
this.distance = distance;
this.yaw = yaw;
this.pitch = pitch;
this.interpolationType(interpolationType);
}
@Override
public Keyframe copy() {
return new CameraOrbitKeyframe(new Vector3f(this.center), this.distance, this.yaw, this.pitch, this.interpolationType());
}
@Override
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {
float[] center = new float[]{this.center.x, this.center.y, this.center.z};
if (ImGui.inputFloat3("Position", center)) {
if (center[0] != this.center.x) {
update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.x = center[0]);
}
if (center[1] != this.center.y) {
update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.y = center[1]);
}
if (center[2] != this.center.z) {
update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.z = center[2]);
}
}
ImFloat input = new ImFloat(this.distance);
if (ImGui.inputFloat("Distance", input)) {
if (input.get() != this.distance) {
update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).distance = input.get());
}
}
input.set(this.yaw);
if (ImGui.inputFloat("Yaw", input)) {
if (input.get() != this.yaw) {
update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).yaw = input.get());
}
}
input.set(this.pitch);
if (ImGui.inputFloat("Pitch", input)) {
if (input.get() != this.pitch) {
update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).pitch = input.get());
}
}
}
private void apply(KeyframeHandler keyframeHandler, Vector3f center, float distance, float yaw, float pitch) {
float pitchRadians = (float) Math.toRadians(pitch);
float yawRadians = (float) Math.toRadians(-yaw);
float cosYaw = Mth.cos(yawRadians);
float sinYaw = Mth.sin(yawRadians);
float cosPitch = Mth.cos(pitchRadians);
float sinPitch = Mth.sin(pitchRadians);
Vector3f look = new Vector3f(sinYaw * cosPitch, -sinPitch, cosYaw * cosPitch);
Vector3f cameraPosition = new Vector3f(center).sub(look.mul(distance));
LocalPlayer player = Minecraft.getInstance().player;
if (player != null) {
cameraPosition.y -= player.getEyeHeight();
}
keyframeHandler.applyCameraPosition(cameraPosition, yaw, pitch, 0.0f);
}
@Override
public void apply(KeyframeHandler keyframeHandler) {
apply(keyframeHandler, this.center, this.distance, this.yaw, this.pitch);
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe genericOther, float amount) {
if (!(genericOther instanceof CameraOrbitKeyframe other)) {
this.apply(keyframeHandler);
return;
}
double x = Interpolation.linear(this.center.x, other.center.x, amount);
double y = Interpolation.linear(this.center.y, other.center.y, amount);
double z = Interpolation.linear(this.center.z, other.center.z, amount);
float distance = Interpolation.linear(this.distance, other.distance, amount);
float yaw = Interpolation.linear(this.yaw, other.yaw, amount);
float pitch = Interpolation.linear(this.pitch, other.pitch, amount);
Vector3f center = new Vector3f((float) x, (float) y, (float) z);
apply(keyframeHandler, center, distance, yaw, pitch);
}
@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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
// Calculate position
Vector3f position = CatmullRom.position(this.center,
((CameraOrbitKeyframe)p1).center, ((CameraOrbitKeyframe)p2).center,
((CameraOrbitKeyframe)p3).center, time1, time2, time3, amount);
float x = position.x;
float y = position.y;
float z = position.z;
float distance = CatmullRom.value(this.distance, ((CameraOrbitKeyframe)p1).distance, ((CameraOrbitKeyframe)p2).distance,
((CameraOrbitKeyframe)p3).distance, time1, time2, time3, amount);
float yaw = CatmullRom.value(this.yaw, ((CameraOrbitKeyframe)p1).yaw, ((CameraOrbitKeyframe)p2).yaw,
((CameraOrbitKeyframe)p3).yaw, time1, time2, time3, amount);
float pitch = CatmullRom.value(this.pitch, ((CameraOrbitKeyframe)p1).pitch, ((CameraOrbitKeyframe)p2).pitch,
((CameraOrbitKeyframe)p3).pitch, time1, time2, time3, amount);
if (lerpAmount >= 0) {
float linearX = Interpolation.linear(((CameraOrbitKeyframe)p1).center.x, ((CameraOrbitKeyframe)p2).center.x, lerpAmount);
float linearY = Interpolation.linear(((CameraOrbitKeyframe)p1).center.y, ((CameraOrbitKeyframe)p2).center.y, lerpAmount);
float linearZ = Interpolation.linear(((CameraOrbitKeyframe)p1).center.z, ((CameraOrbitKeyframe)p2).center.z, lerpAmount);
float linearDistance = Interpolation.linear(((CameraOrbitKeyframe)p1).distance, ((CameraOrbitKeyframe)p2).distance, amount);
float linearYaw = Interpolation.linear(((CameraOrbitKeyframe)p1).yaw, ((CameraOrbitKeyframe)p2).yaw, amount);
float linearPitch = Interpolation.linear(((CameraOrbitKeyframe)p1).pitch, ((CameraOrbitKeyframe)p2).pitch, amount);
if (lerpFromRight) {
x = Interpolation.linear(x, linearX, amount);
y = Interpolation.linear(y, linearY, amount);
z = Interpolation.linear(z, linearZ, amount);
distance = Interpolation.linear(distance, linearDistance, amount);
yaw = Interpolation.linear(yaw, linearYaw, amount);
pitch = Interpolation.linear(pitch, linearPitch, amount);
} else {
x = Interpolation.linear(linearX, x, amount);
y = Interpolation.linear(linearY, y, amount);
z = Interpolation.linear(linearZ, z, amount);
distance = Interpolation.linear(linearDistance, distance, amount);
yaw = Interpolation.linear(linearYaw, yaw, amount);
pitch = Interpolation.linear(linearPitch, pitch, amount);
}
}
apply(keyframeHandler, new Vector3f(x, y, z), distance, yaw, pitch);
}
public static class TypeAdapter implements JsonSerializer<CameraOrbitKeyframe>, JsonDeserializer<CameraOrbitKeyframe> {
@Override
public CameraOrbitKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
Vector3f center = context.deserialize(jsonObject.get("center"), Vector3f.class);
float distance = jsonObject.get("distance").getAsFloat();
float yaw = jsonObject.get("yaw").getAsFloat();
float pitch = jsonObject.get("pitch").getAsFloat();
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new CameraOrbitKeyframe(center, distance, yaw, pitch, interpolationType);
}
@Override
public JsonElement serialize(CameraOrbitKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.add("center", context.serialize(src.center));
jsonObject.addProperty("distance", src.distance);
jsonObject.addProperty("yaw", src.yaw);
jsonObject.addProperty("pitch", src.pitch);
jsonObject.addProperty("type", "camera_orbit");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
}
@@ -0,0 +1,124 @@
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.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.spline.CatmullRom;
import java.lang.reflect.Type;
public class CameraShakeKeyframe extends Keyframe {
private final float frequencyX;
private final float amplitudeX;
private final float frequencyY;
private final float amplitudeY;
public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) {
this(frequencyX, amplitudeX, frequencyY, amplitudeY, InterpolationType.DEFAULT);
}
public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, InterpolationType interpolationType) {
this.frequencyX = frequencyX;
this.amplitudeX = amplitudeX;
this.frequencyY = frequencyY;
this.amplitudeY = amplitudeY;
this.interpolationType(interpolationType);
}
@Override
public Keyframe copy() {
return new CameraShakeKeyframe(this.frequencyX, this.amplitudeX, this.frequencyY, this.amplitudeY, this.interpolationType());
}
@Override
public void apply(KeyframeHandler keyframeHandler) {
keyframeHandler.applyCameraShake(this.frequencyX, this.amplitudeX, this.frequencyY, this.amplitudeY);
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof CameraShakeKeyframe other)) {
this.apply(keyframeHandler);
return;
}
float frequencyX = Interpolation.linear(this.frequencyX, other.frequencyX, amount);
float amplitudeX = Interpolation.linear(this.amplitudeX, other.amplitudeX, amount);
float frequencyY = Interpolation.linear(this.frequencyY, other.frequencyY, amount);
float amplitudeY = Interpolation.linear(this.amplitudeY, other.amplitudeY, amount);
keyframeHandler.applyCameraShake(frequencyX, amplitudeX, frequencyY, amplitudeY);
}
@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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
float frequencyX = CatmullRom.value(this.frequencyX, ((CameraShakeKeyframe)p1).frequencyX,
((CameraShakeKeyframe)p2).frequencyX, ((CameraShakeKeyframe)p3).frequencyX, time1, time2, time3, amount);
float amplitudeX = CatmullRom.value(this.amplitudeX, ((CameraShakeKeyframe)p1).amplitudeX,
((CameraShakeKeyframe)p2).amplitudeX, ((CameraShakeKeyframe)p3).amplitudeX, time1, time2, time3, amount);
float frequencyY = CatmullRom.value(this.frequencyY, ((CameraShakeKeyframe)p1).frequencyY,
((CameraShakeKeyframe)p2).frequencyY, ((CameraShakeKeyframe)p3).frequencyY, time1, time2, time3, amount);
float amplitudeY = CatmullRom.value(this.amplitudeY, ((CameraShakeKeyframe)p1).amplitudeY,
((CameraShakeKeyframe)p2).amplitudeY, ((CameraShakeKeyframe)p3).amplitudeY, time1, time2, time3, amount);
if (lerpAmount >= 0) {
float linearFrequencyX = Interpolation.linear(((CameraShakeKeyframe)p1).frequencyX, ((CameraShakeKeyframe)p2).frequencyX, lerpAmount);
float linearAmplitudeX = Interpolation.linear(((CameraShakeKeyframe)p1).amplitudeX, ((CameraShakeKeyframe)p2).amplitudeX, lerpAmount);
float linearFrequencyY = Interpolation.linear(((CameraShakeKeyframe)p1).frequencyY, ((CameraShakeKeyframe)p2).frequencyY, lerpAmount);
float linearAmplitudeY = Interpolation.linear(((CameraShakeKeyframe)p1).amplitudeY, ((CameraShakeKeyframe)p2).amplitudeY, lerpAmount);
if (lerpFromRight) {
frequencyX = Interpolation.linear(frequencyX, linearFrequencyX, amount);
amplitudeX = Interpolation.linear(amplitudeX, linearAmplitudeX, amount);
frequencyY = Interpolation.linear(frequencyY, linearFrequencyY, amount);
amplitudeY = Interpolation.linear(amplitudeY, linearAmplitudeY, amount);
} else {
frequencyX = Interpolation.linear(linearFrequencyX, frequencyX, amount);
amplitudeX = Interpolation.linear(linearAmplitudeX, amplitudeX, amount);
frequencyY = Interpolation.linear(linearFrequencyY, frequencyY, amount);
amplitudeY = Interpolation.linear(linearAmplitudeY, amplitudeY, amount);
}
}
keyframeHandler.applyCameraShake(frequencyX, amplitudeX, frequencyY, amplitudeY);
}
public static class TypeAdapter implements JsonSerializer<CameraShakeKeyframe>, JsonDeserializer<CameraShakeKeyframe> {
@Override
public CameraShakeKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
float frequencyX = jsonObject.get("frequencyX").getAsFloat();
float amplitudeX = jsonObject.get("amplitudeX").getAsFloat();
float frequencyY = jsonObject.get("frequencyY").getAsFloat();
float amplitudeY = jsonObject.get("amplitudeY").getAsFloat();
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new CameraShakeKeyframe(frequencyX, amplitudeX, frequencyY, amplitudeY, interpolationType);
}
@Override
public JsonElement serialize(CameraShakeKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("frequencyX", src.frequencyX);
jsonObject.addProperty("amplitudeX", src.amplitudeX);
jsonObject.addProperty("frequencyY", src.frequencyY);
jsonObject.addProperty("amplitudeY", src.amplitudeY);
jsonObject.addProperty("type", "camera_shake");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
}
@@ -2,79 +2,105 @@ package com.moulberry.flashback.keyframe.impl;
import com.google.gson.*;
import com.moulberry.flashback.Interpolation;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.spline.CatmullRom;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import imgui.ImGui;
import java.lang.reflect.Type;
import java.util.function.Consumer;
public class FOVKeyframe extends Keyframe<Minecraft> {
public class FOVKeyframe extends Keyframe {
private final int fov;
public float fov;
public FOVKeyframe(int fov) {
super(Minecraft.class);
public FOVKeyframe(float fov) {
this(fov, InterpolationType.DEFAULT);
}
public FOVKeyframe(float fov, InterpolationType interpolationType) {
this.fov = fov;
this.interpolationType(interpolationType);
}
@Override
public void apply(Minecraft minecraft) {
ReplayVisuals.setFov(fov);
public Keyframe copy() {
return new FOVKeyframe(this.fov, this.interpolationType());
}
@Override
public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) {
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {
ImGui.setNextItemWidth(160);
float[] input = new float[]{this.fov};
if (ImGui.sliderFloat("FOV", input, 1.0f, 110.0f, "%.1f")) {
if (this.fov != input[0]) {
update.accept(keyframe -> ((FOVKeyframe)keyframe).fov = input[0]);
}
}
}
@Override
public void apply(KeyframeHandler keyframeHandler) {
keyframeHandler.applyFov(this.fov);
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof FOVKeyframe other)) {
this.apply(minecraft);
this.apply(keyframeHandler);
return;
}
float fov = Interpolation.linear(this.fov, other.fov, amount);
ReplayVisuals.setFov(fov);
float thisFocalLength = Utils.fovToFocalLength(this.fov);
float otherFocalLength = Utils.fovToFocalLength(other.fov);
float focalLength = Interpolation.linear(thisFocalLength, otherFocalLength, amount);
keyframeHandler.applyFov(Utils.focalLengthToFov(focalLength));
}
@Override
public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) {
LocalPlayer player = minecraft.player;
if (player == null) {
return;
}
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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
float fov = CatmullRom.value(this.fov,
((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov,
((FOVKeyframe)p3).fov, time1, time2, time3, amount);
float f0 = Utils.fovToFocalLength(this.fov);
float f1 = Utils.fovToFocalLength(((FOVKeyframe)p1).fov);
float f2 = Utils.fovToFocalLength(((FOVKeyframe)p2).fov);
float f3 = Utils.fovToFocalLength(((FOVKeyframe)p3).fov);
float focalLength = CatmullRom.value(f0, f1, f2, f3, time1, time2, time3, amount);
if (lerpAmount >= 0) {
float linearFov = Interpolation.linear(((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov, lerpAmount);
float linearFocalLength = Interpolation.linear(f1, f2, lerpAmount);
if (lerpFromRight) {
fov = Interpolation.linear(fov, linearFov, amount);
focalLength = Interpolation.linear(focalLength, linearFocalLength, amount);
} else {
fov = Interpolation.linear(linearFov, fov, amount);
focalLength = Interpolation.linear(linearFocalLength, focalLength, amount);
}
}
ReplayVisuals.setFov(fov);
keyframeHandler.applyFov(Utils.focalLengthToFov(focalLength));
}
public static class TypeAdapter implements JsonSerializer<FOVKeyframe>, JsonDeserializer<FOVKeyframe> {
@Override
public FOVKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
int fov = jsonObject.get("fov").getAsInt();
return new FOVKeyframe(fov);
float fov = jsonObject.get("fov").getAsFloat();
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new FOVKeyframe(fov, interpolationType);
}
@Override
public JsonElement serialize(FOVKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("fov", src.fov);
jsonObject.addProperty("type", "fov");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
@@ -2,40 +2,63 @@ package com.moulberry.flashback.keyframe.impl;
import com.google.gson.*;
import com.moulberry.flashback.Interpolation;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.spline.CatmullRom;
import imgui.ImGui;
import java.lang.reflect.Type;
import java.util.function.Consumer;
public class TickrateKeyframe extends Keyframe<ReplayServer> {
public class TickrateKeyframe extends Keyframe {
private float tickrate;
public TickrateKeyframe(float tickrate) {
super(ReplayServer.class);
this(tickrate, InterpolationType.DEFAULT);
}
public TickrateKeyframe(float tickrate, InterpolationType interpolationType) {
this.tickrate = tickrate;
this.interpolationType(interpolationType);
}
@Override
public void apply(ReplayServer replayServer) {
replayServer.desiredTickRate = this.tickrate;
public Keyframe copy() {
return new TickrateKeyframe(this.tickrate, this.interpolationType());
}
@Override
public void applyInterpolated(ReplayServer replayServer, Keyframe otherGeneric, float amount) {
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {
ImGui.setNextItemWidth(160);
float[] input = new float[]{this.tickrate/20f};
if (ImGui.sliderFloat("Speed", input, 0.1f, 10.0f)) {
float tickrate = input[0]*20f;
if (this.tickrate != tickrate) {
update.accept(keyframe -> ((TickrateKeyframe)keyframe).tickrate = tickrate);
}
}
}
@Override
public void apply(KeyframeHandler keyframeHandler) {
keyframeHandler.applyTickrate(this.tickrate);
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof TickrateKeyframe other)) {
this.apply(replayServer);
this.apply(keyframeHandler);
return;
}
float tickrate = Interpolation.linear(this.tickrate, other.tickrate, amount);
replayServer.desiredTickRate = tickrate;
keyframeHandler.applyTickrate(tickrate);
}
@Override
public void applyInterpolatedSmooth(ReplayServer replayServer, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) {
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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
@@ -54,7 +77,7 @@ public class TickrateKeyframe extends Keyframe<ReplayServer> {
}
}
replayServer.desiredTickRate = tickrate;
keyframeHandler.applyTickrate(tickrate);
}
public static class TypeAdapter implements JsonSerializer<TickrateKeyframe>, JsonDeserializer<TickrateKeyframe> {
@@ -62,13 +85,16 @@ public class TickrateKeyframe extends Keyframe<ReplayServer> {
public TickrateKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
float tickrate = jsonObject.get("tickrate").getAsFloat();
return new TickrateKeyframe(tickrate);
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new TickrateKeyframe(tickrate, interpolationType);
}
@Override
public JsonElement serialize(TickrateKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tickrate", src.tickrate);
jsonObject.addProperty("type", "tickrate");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
@@ -2,52 +2,63 @@ package com.moulberry.flashback.keyframe.impl;
import com.google.gson.*;
import com.moulberry.flashback.Interpolation;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.spline.CatmullRom;
import net.minecraft.client.Minecraft;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.GameRules;
import imgui.ImGui;
import imgui.type.ImInt;
import java.lang.reflect.Type;
import java.util.function.Consumer;
public class TimeOfDayKeyframe extends Keyframe<Minecraft> {
public class TimeOfDayKeyframe extends Keyframe {
private final int time;
public int time;
public TimeOfDayKeyframe(int time) {
super(Minecraft.class);
this(time, InterpolationType.DEFAULT);
}
public TimeOfDayKeyframe(int time, InterpolationType interpolationType) {
this.time = time;
this.interpolationType(interpolationType);
}
private void setTime(Minecraft minecraft, int time) {
time = time % 24000;
if (time < 0) {
time += 24000;
@Override
public Keyframe copy() {
return new TimeOfDayKeyframe(this.time, this.interpolationType());
}
@Override
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {
ImGui.setNextItemWidth(160);
ImInt input = new ImInt(this.time);
if (ImGui.inputInt("Time", input, 0)) {
if (this.time != input.get()) {
update.accept(keyframe -> ((TimeOfDayKeyframe)keyframe).time = input.get());
}
}
ReplayVisuals.overrideTimeOfDay = time;
}
@Override
public void apply(Minecraft minecraft) {
this.setTime(minecraft, this.time);
public void apply(KeyframeHandler keyframeHandler) {
keyframeHandler.applyTimeOfDay(this.time);
}
@Override
public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) {
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof TimeOfDayKeyframe other)) {
this.apply(minecraft);
this.apply(keyframeHandler);
return;
}
int time = Math.round(Interpolation.linear(this.time, other.time, amount));
this.setTime(minecraft, time);
keyframeHandler.applyTimeOfDay(time);
}
@Override
public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) {
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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
@@ -66,7 +77,7 @@ public class TimeOfDayKeyframe extends Keyframe<Minecraft> {
}
}
this.setTime(minecraft, Math.round(timeOfDay));
keyframeHandler.applyTimeOfDay(Math.round(timeOfDay));
}
@@ -75,13 +86,16 @@ public class TimeOfDayKeyframe extends Keyframe<Minecraft> {
public TimeOfDayKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
int timeOfDay = jsonObject.get("time").getAsInt();
return new TimeOfDayKeyframe(timeOfDay);
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new TimeOfDayKeyframe(timeOfDay, interpolationType);
}
@Override
public JsonElement serialize(TimeOfDayKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("time", src.time);
jsonObject.addProperty("type", "time");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
@@ -0,0 +1,87 @@
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.Utils;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import imgui.ImGui;
import imgui.type.ImString;
import java.lang.reflect.Type;
import java.util.function.Consumer;
public class TimelapseKeyframe extends Keyframe {
public int ticks;
private final ImString timelapseKeyframeInput;
public TimelapseKeyframe(int ticks) {
this.ticks = ticks;
this.timelapseKeyframeInput = ImGuiHelper.createResizableImString(Utils.timeToString(this.ticks));
this.timelapseKeyframeInput.inputData.allowedChars = "0123456789tsmh";
this.interpolationType(InterpolationType.LINEAR);
}
@Override
public Keyframe copy() {
return new TimelapseKeyframe(this.ticks);
}
@Override
public InterpolationType interpolationType() {
return InterpolationType.LINEAR;
}
@Override
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {
ImGui.setNextItemWidth(160);
ImGui.inputText("Time", timelapseKeyframeInput);
if (ImGui.isItemDeactivatedAfterEdit()) {
int ticks = Utils.stringToTime(timelapseKeyframeInput.get());
if (this.ticks != ticks) {
update.accept(keyframe -> ((TimelapseKeyframe)keyframe).ticks = ticks);
}
}
}
@Override
public void apply(KeyframeHandler keyframeHandler) {
throw new UnsupportedOperationException();
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) {
throw new UnsupportedOperationException();
}
@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) {
throw new UnsupportedOperationException();
}
public static class TypeAdapter implements JsonSerializer<TimelapseKeyframe>, JsonDeserializer<TimelapseKeyframe> {
@Override
public TimelapseKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
int ticks = jsonObject.get("ticks").getAsInt();
return new TimelapseKeyframe(ticks);
}
@Override
public JsonElement serialize(TimelapseKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("ticks", src.ticks);
jsonObject.addProperty("type", "timelapse");
return jsonObject;
}
}
}
@@ -11,6 +11,8 @@ public enum InterpolationType {
EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE),
HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD);
public static InterpolationType DEFAULT = SMOOTH;
public static final InterpolationType[] INTERPOLATION_TYPES = values();
public static String[] NAMES = new String[] {
@@ -16,7 +16,7 @@ public class MixinDebugScreenOverlay {
@Inject(method = "render", at = @At("HEAD"), cancellable = true)
public void render(GuiGraphics guiGraphics, CallbackInfo ci) {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) {
if (Flashback.isExporting()) {
ci.cancel();
}
}
@@ -5,7 +5,10 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.editor.ui.ReplayUI;
import com.moulberry.flashback.exporting.PerfectFrames;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -40,6 +43,18 @@ public abstract class MixinLevelRenderer {
@Shadow @Final public SectionOcclusionGraph sectionOcclusionGraph;
@Shadow
private int ticks;
@Inject(method = "tick", at = @At("HEAD"), cancellable = true)
public void tick(CallbackInfo ci) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
this.ticks = replayServer.getReplayTick();
ci.cancel();
}
}
@Inject(method = "renderLevel", at = @At("HEAD"))
public void renderLevel(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f projection, CallbackInfo ci) {
ReplayUI.lastProjectionMatrix = projection;
@@ -48,49 +63,56 @@ public abstract class MixinLevelRenderer {
@Inject(method = "renderSectionLayer", at = @At("HEAD"), cancellable = true)
public void renderSectionLayer(RenderType renderType, double d, double e, double f, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) {
if (!ReplayVisuals.renderBlocks) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderBlocks) {
ci.cancel();
}
}
@Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER))
public void renderLevel_levelFogColor(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) {
if (!ReplayVisuals.renderSky) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderSky) {
RenderSystem.clearColor(0.0f, 1.0f, 0.0f, 0.0F);
}
}
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;render(Lnet/minecraft/world/level/block/entity/BlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"))
public boolean renderLevel_renderBlockEntity(BlockEntityRenderDispatcher instance, BlockEntity blockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource) {
return ReplayVisuals.renderBlocks;
EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderBlocks;
}
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"))
public boolean renderLevel_renderEntity(LevelRenderer instance, Entity entity, double d, double e, double f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource) {
EditorState editorState = EditorStateManager.getCurrent();
if (entity instanceof Player) {
return ReplayVisuals.renderPlayers;
return editorState == null || editorState.replayVisuals.renderPlayers;
} else {
return ReplayVisuals.renderEntities;
return editorState == null || editorState.replayVisuals.renderEntities;
}
}
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;"))
public CloudStatus renderLevel_getCloudsType(Options instance, Operation<CloudStatus> original) {
if (ReplayVisuals.renderSky) {
return original.call(instance);
} else {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderSky) {
return CloudStatus.OFF;
} else {
return original.call(instance);
}
}
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V"))
public boolean renderLevel_renderParticles(ParticleEngine instance, LightTexture lightTexture, Camera camera, float f) {
return ReplayVisuals.renderParticles;
EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderParticles;
}
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSky(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FLnet/minecraft/client/Camera;ZLjava/lang/Runnable;)V"))
public boolean renderLevel_renderSky(LevelRenderer instance, Matrix4f matrix4f, Matrix4f matrix4f2, float f, Camera camera, boolean bl, Runnable runnable) {
return ReplayVisuals.renderSky;
EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderSky;
}
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V"))
@@ -5,9 +5,12 @@ 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.ReplayVisuals;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.exporting.PerfectFrames;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.ext.MinecraftExt;
@@ -63,6 +66,8 @@ import java.time.Instant;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@Mixin(Minecraft.class)
@@ -129,7 +134,9 @@ public abstract class MixinMinecraft implements MinecraftExt {
@Final
public ParticleEngine particleEngine;
@Shadow @Final public DeltaTracker.Timer timer;
@Shadow
@Nullable
public Entity cameraEntity;
@Inject(method="<init>", at=@At("RETURN"))
public void init(GameConfig gameConfig, CallbackInfo ci) {
@@ -145,7 +152,8 @@ public abstract class MixinMinecraft implements MinecraftExt {
@Inject(method = "renderNames", at = @At("HEAD"), cancellable = true)
private static void renderNames(CallbackInfoReturnable<Boolean> cir) {
if (!ReplayVisuals.renderNametags) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderNametags) {
cir.setReturnValue(false);
}
}
@@ -165,7 +173,7 @@ public abstract class MixinMinecraft implements MinecraftExt {
Flashback.RECORDER.endTick(false);
}
EditorStateCache.saveIfNeeded();
EditorStateManager.saveIfNeeded();
ReplayServer replayServer = Flashback.getReplayServer();
@@ -173,63 +181,11 @@ public abstract class MixinMinecraft implements MinecraftExt {
if (inReplay != inReplayLast) {
inReplayLast = inReplay;
if (inReplay) {
ReplayVisuals.setupReplay();
Minecraft.getInstance().options.hideGui = false;
} else {
ReplayVisuals.disable();
EditorStateCache.reset();
EditorStateManager.reset();
}
}
if (inReplay && ReplayVisuals.forceEntityLerpTicks > 0) {
ReplayVisuals.forceEntityLerpTicks -= 1;
if (replayServer.replayPaused && this.level != null && !this.level.tickRateManager().runsNormally()) {
for (Entity entity : this.level.entitiesForRendering()) {
if (entity == this.player) {
continue;
}
if (entity instanceof LivingEntity livingEntity) {
if (livingEntity.lerpSteps > 0) {
livingEntity.lerpPositionAndRotationStep(livingEntity.lerpSteps, livingEntity.lerpTargetX(),
livingEntity.lerpTargetY(), livingEntity.lerpTargetZ(), livingEntity.lerpTargetYRot(), livingEntity.lerpTargetXRot());
--livingEntity.lerpSteps;
}
if (livingEntity.lerpHeadSteps > 0) {
livingEntity.lerpHeadRotationStep(livingEntity.lerpHeadSteps, livingEntity.lerpYHeadRot);
--livingEntity.lerpHeadSteps;
}
livingEntity.setOldPosAndRot();
livingEntity.tickHeadTurn(livingEntity.yBodyRot, 0.0f);
} else {
entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(),
entity.lerpTargetYRot(), entity.lerpTargetXRot());
}
if (entity.isPassenger()) {
entity.setDeltaMovement(Vec3.ZERO);
entity.getVehicle().positionRider(entity);
}
}
}
}
}
@Unique
private volatile boolean forceClientTick = false;
@Override
public void flashback$forceClientTick() {
this.forceClientTick = true;
}
@WrapOperation(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/DeltaTracker$Timer;advanceTime(JZ)I"))
public int runTick_advanceTime(DeltaTracker.Timer instance, long l, boolean runTick, Operation<Integer> original) {
int ticks = original.call(instance, l, runTick);
if (this.forceClientTick) {
this.forceClientTick = false;
this.particleEngine.clearParticles();
return Math.max(1, ticks);
}
return ticks;
}
@Inject(method = "getTickTargetMillis", at = @At("HEAD"), cancellable = true)
@@ -249,8 +205,27 @@ public abstract class MixinMinecraft implements MinecraftExt {
@Unique
private final DeltaTracker.Timer localPlayerTimer = new DeltaTracker.Timer(20.0f, 0, FloatUnaryOperator.identity());
@Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At("HEAD"))
public void disconnect(Screen screen, boolean isTransferring, CallbackInfo ci) {
try {
if (Flashback.getConfig().automaticallyFinish && Flashback.RECORDER != null && !isTransferring) {
Flashback.finishRecordingReplay();
}
} catch (Exception e) {
Flashback.LOGGER.error("Failed to finish replay on disconnect", e);
}
}
@Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runAllTasks()V", shift = At.Shift.AFTER))
public void runTick_runAllTasks(boolean runTick, CallbackInfo ci) {
if (ExportJobQueue.drainingQueue) {
if (ExportJobQueue.queuedJobs.isEmpty()) {
ExportJobQueue.drainingQueue = false;
} else if (Flashback.EXPORT_JOB == null) {
Flashback.EXPORT_JOB = new ExportJob(ExportJobQueue.queuedJobs.removeFirst());
}
}
if (Flashback.EXPORT_JOB != null && !ReplayUI.isActive()) {
try {
PerfectFrames.enable();
@@ -266,18 +241,26 @@ public abstract class MixinMinecraft implements MinecraftExt {
if (this.level != null && this.player != null && !this.player.isPassenger() && !this.player.isRemoved()) {
localPlayerTicks = Math.min(10, localPlayerTicks);
for (int i = 0; i < localPlayerTicks; i++) {
this.level.tickNonPassenger(this.player);
this.level.guardEntityTick(this.level::tickNonPassenger, this.player);
}
}
}
}
@Override
public float flashback$getLocalPlayerPartialTick() {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) {
return this.timer.getGameTimeDeltaPartialTick(true);
public float flashback$getLocalPlayerPartialTick(float originalPartialTick) {
if (Flashback.isExporting() || this.cameraEntity != this.player) {
return originalPartialTick;
}
return localPlayerTimer.getGameTimeDeltaPartialTick(true);
return this.localPlayerTimer.getGameTimeDeltaPartialTick(true);
}
@Unique
private final AtomicBoolean applyKeyframes = new AtomicBoolean(false);
@Override
public void flashback$applyKeyframes() {
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)
@@ -287,9 +270,10 @@ public abstract class MixinMinecraft implements MinecraftExt {
return;
}
if (!replayServer.replayPaused) {
EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier);
editorState.applyKeyframes((Minecraft) (Object) this, replayServer.getPartialReplayTick());
boolean forceApplyKeyframes = this.applyKeyframes.compareAndSet(true, false);
if (!replayServer.replayPaused || forceApplyKeyframes) {
EditorState editorState = EditorStateManager.get(replayServer.getMetadata().replayIdentifier);
editorState.applyKeyframes(new MinecraftKeyframeHandler((Minecraft) (Object) this), replayServer.getPartialReplayTick());
}
if (!replayServer.doClientRendering()) {
ci.cancel();
@@ -1,5 +1,6 @@
package com.moulberry.flashback.mixin;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw;
import com.moulberry.flashback.editor.ui.ReplayUI;
import net.minecraft.client.MouseHandler;
@@ -16,17 +17,23 @@ public class MixinMouseHandler {
public void isMouseGrabbed(CallbackInfoReturnable<Boolean> cir) {
if (ReplayUI.isActive()) {
cir.setReturnValue(ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME);
} else if (Flashback.isExporting()) {
cir.setReturnValue(false);
}
}
@Inject(method = "grabMouse", at=@At("HEAD"), cancellable = true)
public void grabMouse(CallbackInfo ci) {
if (ReplayUI.isActive()) ci.cancel();
if (ReplayUI.isActive() || Flashback.isExporting()) {
ci.cancel();
}
}
@Inject(method = "releaseMouse", at=@At("HEAD"), cancellable = true)
public void releaseMouse(CallbackInfo ci) {
if (ReplayUI.isActive()) ci.cancel();
if (ReplayUI.isActive()) {
ci.cancel();
}
}
}
@@ -3,26 +3,22 @@ package com.moulberry.flashback.mixin;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.platform.GlStateManager;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.ReplayUI;
import net.minecraft.client.Minecraft;
import org.lwjgl.glfw.GLFW;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(value = RenderTarget.class, priority = 1100)
public class MixinRenderTarget {
@WrapOperation(method = "_blitToScreen", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_viewport(IIII)V", remap = false))
public void blitToScreenViewport(int left, int bottom, int width, int height, Operation<Void> original) {
if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.shouldModifyViewport()) {
ReplayUI.setupMainViewport();
} else {
original.call(left, bottom, width, height);
}
}
}
@@ -1,11 +1,15 @@
package com.moulberry.flashback.mixin;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.world.level.chunk.LightChunkGetter;
import net.minecraft.world.level.lighting.LevelLightEngine;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(ThreadedLevelLightEngine.class)
public abstract class MixinThreadedLevelLightEngine extends LevelLightEngine implements ThreadedLevelLightEngineExt {
@@ -21,4 +25,19 @@ public abstract class MixinThreadedLevelLightEngine extends LevelLightEngine imp
public void flashback$submitPost(int x, int z, Runnable runnable) {
this.addTask(x, z, ThreadedLevelLightEngine.TaskType.POST_UPDATE, runnable);
}
@WrapOperation(method = "runUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/lighting/LevelLightEngine;runLightUpdates()I"))
public int runUpdate_runLightUpdates(ThreadedLevelLightEngine instance, Operation<Integer> original) {
if (Flashback.isInReplay()) {
try {
return original.call(instance);
} catch (Exception e) {
Flashback.LOGGER.error("Exception occurred while processing light updates", e);
return 0;
}
} else {
return original.call(instance);
}
}
}
@@ -2,13 +2,14 @@ package com.moulberry.flashback.mixin;
import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.visuals.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.ReplayUI;
import org.lwjgl.glfw.GLFW;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@@ -36,12 +37,22 @@ public abstract class MixinWindow {
@Final
private long window;
@Unique
private float calculateWidthScaleFactor() {
return Math.max(1/8f, Math.min(8f, (float) this.framebufferWidth / this.width));
}
@Unique
private float calculateHeightScaleFactor() {
return Math.max(1/8f, Math.min(8f, (float) this.framebufferHeight / this.height));
}
@Inject(method = "getWidth", at=@At("HEAD"), cancellable = true)
public void getWidth(CallbackInfoReturnable<Integer> cir) {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) {
cir.setReturnValue(Flashback.EXPORT_JOB.getWidth());
} else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
cir.setReturnValue(ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width));
} else if (ReplayUI.shouldModifyViewport()) {
cir.setReturnValue(ReplayUI.getNewGameWidth(this.calculateWidthScaleFactor()));
}
}
@@ -49,49 +60,29 @@ public abstract class MixinWindow {
public void getHeight(CallbackInfoReturnable<Integer> cir) {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) {
cir.setReturnValue(Flashback.EXPORT_JOB.getHeight());
} else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
cir.setReturnValue(ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height));
} else if (ReplayUI.shouldModifyViewport()) {
cir.setReturnValue(ReplayUI.getNewGameHeight(this.calculateHeightScaleFactor()));
}
}
@Inject(method = "getScreenWidth", at=@At("HEAD"), cancellable = true)
public void getScreenWidth(CallbackInfoReturnable<Integer> cir) {
if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
if (ReplayUI.shouldModifyViewport()) {
cir.setReturnValue(ReplayUI.getNewGameWidth(1));
}
}
@Inject(method = "getScreenHeight", at=@At("HEAD"), cancellable = true)
public void getScreenHeight(CallbackInfoReturnable<Integer> cir) {
if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
if (ReplayUI.shouldModifyViewport()) {
cir.setReturnValue(ReplayUI.getNewGameHeight(1));
}
}
@Inject(method = "onFramebufferResize", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/WindowEventHandler;resizeDisplay()V", shift = At.Shift.BEFORE))
public void onFramebufferResize(long l, int i, int j, CallbackInfo ci) {
int[] widthB = new int[1];
int[] heightB = new int[1];
GLFW.glfwGetWindowSize(this.window, widthB, heightB);
if (widthB[0] > 0 && heightB[0] > 0) {
this.width = widthB[0];
this.height = heightB[0];
}
}
@Inject(method = "onResize", at=@At("HEAD"), cancellable = true)
public void onResize(long l, int i, int j, CallbackInfo ci) {
if (l != this.window) {
ci.cancel();
return;
}
int[] widthB = new int[1];
int[] heightB = new int[1];
GLFW.glfwGetFramebufferSize(this.window, widthB, heightB);
if (widthB[0] > 0 && heightB[0] > 0) {
this.framebufferWidth = widthB[0];
this.framebufferHeight = heightB[0];
}
}
@@ -109,9 +100,9 @@ public abstract class MixinWindow {
j++;
}
cir.setReturnValue(j);
} else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
int fbw = ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width);
int fbh = ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height);
} else if (ReplayUI.shouldModifyViewport()) {
int fbw = ReplayUI.getNewGameWidth(this.calculateWidthScaleFactor());
int fbh = ReplayUI.getNewGameHeight(this.calculateHeightScaleFactor());
int j = 1;
while (j != scale && j < fbw && j < fbh && fbw / (j + 1) >= 320 && fbh / (j + 1) >= 240) {
@@ -137,9 +128,9 @@ public abstract class MixinWindow {
this.guiScaledHeight = (double)fbh / d > (double)j ? j + 1 : j;
ci.cancel();
} else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
int fbw = ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width);
int fbh = ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height);
} else if (ReplayUI.shouldModifyViewport()) {
int fbw = ReplayUI.getNewGameWidth(this.calculateWidthScaleFactor());
int fbh = ReplayUI.getNewGameHeight(this.calculateHeightScaleFactor());
this.guiScale = d;
int i = (int)((double)fbw / d);
@@ -0,0 +1,62 @@
package com.moulberry.flashback.mixin.audio;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.audio.Library;
import com.moulberry.flashback.Flashback;
import org.lwjgl.openal.ALC10;
import org.lwjgl.openal.ALC11;
import org.lwjgl.openal.SOFTLoopback;
import org.lwjgl.system.MemoryStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.nio.IntBuffer;
@Mixin(Library.class)
public class MixinAudioLibrary {
@Shadow
public long currentDevice;
@Unique
private boolean usingLoopbackDevice = false;
@Inject(method = "init", at = @At("HEAD"))
public void init(String string, boolean bl, CallbackInfo ci) {
this.usingLoopbackDevice = Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().recordAudio();
if (this.usingLoopbackDevice) {
Flashback.LOGGER.info("Enabling loopback device for recording audio");
}
}
@WrapOperation(method = "init", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/audio/Library;openDeviceOrFallback(Ljava/lang/String;)J"))
public long init_openDevice(String string, Operation<Long> original) {
if (this.usingLoopbackDevice) {
return SOFTLoopback.alcLoopbackOpenDeviceSOFT((CharSequence) null);
} else {
return original.call(string);
}
}
@WrapOperation(method = "init", at = @At(value = "INVOKE", target = "Lorg/lwjgl/openal/ALC10;alcCreateContext(JLjava/nio/IntBuffer;)J", remap = false))
public long init_createContext(long deviceHandle, IntBuffer attrList, Operation<Long> original) {
if (this.usingLoopbackDevice) {
try (MemoryStack memoryStack = MemoryStack.stackPush()) {
IntBuffer intBuffer = memoryStack.callocInt(7)
.put(SOFTLoopback.ALC_FORMAT_TYPE_SOFT).put(SOFTLoopback.ALC_FLOAT_SOFT)
.put(SOFTLoopback.ALC_FORMAT_CHANNELS_SOFT).put(SOFTLoopback.ALC_MONO_SOFT)
.put(ALC10.ALC_FREQUENCY).put(44100)
.put(0).flip();
return ALC10.alcCreateContext(this.currentDevice, intBuffer);
}
} else {
return original.call(deviceHandle, attrList);
}
}
}
@@ -0,0 +1,29 @@
package com.moulberry.flashback.mixin.audio;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.sounds.SoundEngine;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(SoundEngine.class)
public class MixinSoundEngine {
@Unique
private boolean wasExportingAudio = false;
@Inject(method = "shouldChangeDevice", at = @At("HEAD"), cancellable = true)
public void shouldChangeDevice(CallbackInfoReturnable<Boolean> cir) {
boolean isExportingAudio = Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().recordAudio();
if (wasExportingAudio != isExportingAudio) {
wasExportingAudio = isExportingAudio;
cir.setReturnValue(true);
} else if (isExportingAudio) {
cir.setReturnValue(false);
}
}
}
@@ -1,7 +1,8 @@
package com.moulberry.flashback.mixin.compat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.mixinconstraints.annotations.IfModLoaded;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import net.minecraft.client.Camera;
@@ -23,9 +24,10 @@ public class MixinSodiumWorldRenderer {
@Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;Lnet/minecraft/client/Camera;F)V",
at = @At("HEAD"), cancellable = true)
public void renderBlockEntities(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap<SortedSet<BlockDestructionProgress>> blockBreakingProgressions, Camera camera, float tickDelta, CallbackInfo ci) {
if (!ReplayVisuals.renderBlocks) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderBlocks) {
ci.cancel();
}
}
}
}
@@ -0,0 +1,33 @@
package com.moulberry.flashback.mixin.norandom;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.Particle;
import net.minecraft.util.RandomSource;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Random;
@Mixin(Particle.class)
public class MixinParticle {
@Shadow
@Final
protected RandomSource random;
@Inject(method = "<init>(Lnet/minecraft/client/multiplayer/ClientLevel;DDD)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/Particle;setSize(FF)V"))
private void newParticle(ClientLevel clientLevel, double d, double e, double f, CallbackInfo ci) {
if (Flashback.isExporting()) {
Random random = Flashback.EXPORT_JOB.getParticleRandom();
if (random != null) {
this.random.setSeed(random.nextLong());
}
}
}
}
@@ -0,0 +1,30 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(AttributeInstance.class)
public abstract class MixinAttributeInstance {
@Shadow
public abstract boolean removeModifier(ResourceLocation resourceLocation);
@Inject(method = "addModifier", at = @At(value = "HEAD"))
public void addModifier(AttributeModifier attributeModifier, CallbackInfo ci) {
// Some mods (e.g. HorseBuff) may end up adding a duplicate modifier while inside a replay
// Remove the modifier first in order to ensure no exceptions are thrown
if (Flashback.isInReplay()) {
try {
this.removeModifier(attributeModifier.id());
} catch (Exception ignored) {}
}
}
}
@@ -0,0 +1,38 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.ext.LevelChunkExt;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.world.level.chunk.LevelChunk;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.BitSet;
@Mixin(value = ChunkHolder.class, priority = 1100)
public class MixinChunkHolder {
@Shadow
private boolean hasChangedSections;
@Shadow
@Final
private BitSet skyChangedLightSectionFilter;
@Shadow
@Final
private BitSet blockChangedLightSectionFilter;
@Inject(method = "broadcastChanges", at = @At("HEAD"))
public void broadcastChanges(LevelChunk levelChunk, CallbackInfo ci) {
if (levelChunk instanceof LevelChunkExt levelChunkExt) {
if (this.hasChangedSections || !this.skyChangedLightSectionFilter.isEmpty() || !this.blockChangedLightSectionFilter.isEmpty()) {
levelChunkExt.flashback$setCachedChunkId(-1);
}
}
}
}
@@ -4,10 +4,12 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.vertex.PoseStack;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.editor.ui.ReplayUI;
import com.moulberry.flashback.ext.ItemInHandRendererExt;
import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.visuals.CameraRotation;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Options;
@@ -20,6 +22,7 @@ import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.GameType;
import org.joml.Quaternionf;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@@ -29,7 +32,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(GameRenderer.class)
public class MixinGameRenderer {
public abstract class MixinGameRenderer {
@WrapOperation(method = "render", at=@At(value = "FIELD", target = "Lnet/minecraft/client/Options;pauseOnLostFocus:Z"))
@@ -48,6 +51,9 @@ public class MixinGameRenderer {
@Final
private Minecraft minecraft;
@Shadow
public abstract float getDepthFar();
@WrapOperation(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;"))
public GameType getPlayerMode(MultiPlayerGameMode instance, Operation<GameType> original) {
if (Flashback.getSpectatingPlayer() != null) {
@@ -60,8 +66,9 @@ public class MixinGameRenderer {
public void renderItemInHand_renderHandsWithItems(ItemInHandRenderer instance, float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, LocalPlayer localPlayer, int i, Operation<Void> original) {
AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer();
if (spectatingPlayer != null) {
f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick();
((ItemInHandRendererExt)instance).flashback$renderHandsWithItems(f, poseStack, bufferSource, spectatingPlayer, i);
Entity entity = this.minecraft.getCameraEntity() == null ? this.minecraft.player : this.minecraft.getCameraEntity();
float frozenPartialTick = this.minecraft.level.tickRateManager().isEntityFrozen(entity) ? 1.0f : f;
((ItemInHandRendererExt)instance).flashback$renderHandsWithItems(frozenPartialTick, poseStack, bufferSource, spectatingPlayer, i);
} else {
original.call(instance, f, poseStack, bufferSource, localPlayer, i);
}
@@ -70,11 +77,34 @@ public class MixinGameRenderer {
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setup(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/world/entity/Entity;ZZF)V"))
public void renderLevel_setupCamera(Camera instance, BlockGetter blockGetter, Entity entity, boolean bl, boolean bl2, float f, Operation<Void> original) {
if (Flashback.isInReplay()) {
f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick();
f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(f);
}
original.call(instance, blockGetter, entity, bl, bl2, f);
}
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;rotation()Lorg/joml/Quaternionf;"))
public Quaternionf renderLevel(Camera instance, Operation<Quaternionf> original) {
return CameraRotation.modifyViewQuaternion(original.call(instance));
}
// @Inject(method = "getProjectionMatrix", at = @At(value = "INVOKE", target = "Lorg/joml/Matrix4f;perspective(FFFF)Lorg/joml/Matrix4f;", shift = At.Shift.BEFORE))
// @Inject(method = "getProjectionMatrix", at = @At(value = "RETURN"))
// public void getProjectionMatrix(double d, CallbackInfoReturnable<Matrix4f> cir) {
// if (ReplayVisuals.overrideZoom) {
// cir.getReturnValue().scaleLocal(ReplayVisuals.overrideZoomAmount, ReplayVisuals.overrideZoomAmount, 1.0f);
// }
// }
// @Inject(method = "getProjectionMatrix", at = @At(value = "RETURN"), cancellable = true)
// public void getProjectionMatrix(double d, CallbackInfoReturnable<Matrix4f> cir) {
// if (ReplayVisuals.overrideZoom) {
// Window window = Minecraft.getInstance().getWindow();
// Matrix4f matrix4f = new Matrix4f().setOrtho(-10.0f, 10.0f, -10.0f, 10.0f, 0.05f, this.getDepthFar());
// cir.setReturnValue(matrix4f);
//// cir.setReturnValue(new Matrix4f().ortho());
// }
// }
@Inject(method = "tryTakeScreenshotIfNeeded", at = @At("HEAD"), cancellable = true)
public void tryTakeScreenshotIfNeeded(CallbackInfo ci) {
if (Flashback.isInReplay()) {
@@ -89,13 +119,13 @@ public class MixinGameRenderer {
cir.setReturnValue(70.0);
return;
}
int fov = this.minecraft.options.fov().get().intValue();
if (ReplayVisuals.overrideFov) {
cir.setReturnValue((double) ReplayVisuals.overrideFovAmount);
return;
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideFov) {
cir.setReturnValue((double) editorState.replayVisuals.overrideFovAmount);
} else {
int fov = this.minecraft.options.fov().get().intValue();
cir.setReturnValue((double) fov);
}
cir.setReturnValue((double) fov);
}
}
@@ -0,0 +1,125 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.ext.LevelChunkExt;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.UpgradeData;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.blending.BlendingData;
import net.minecraft.world.level.lighting.LightEngine;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.Inject;
@Mixin(LevelChunk.class)
public abstract class MixinLevelChunk extends ChunkAccess implements LevelChunkExt {
@Shadow
@Final
private Level level;
@Shadow
public abstract void addAndRegisterBlockEntity(BlockEntity blockEntity);
@Shadow
protected abstract <T extends BlockEntity> void updateBlockEntityTicker(T blockEntity);
@Shadow
public abstract @Nullable BlockEntity getBlockEntity(BlockPos blockPos, LevelChunk.EntityCreationType entityCreationType);
public MixinLevelChunk(ChunkPos chunkPos, UpgradeData upgradeData, LevelHeightAccessor levelHeightAccessor, Registry<Biome> registry, long l, @Nullable LevelChunkSection[] levelChunkSections, @Nullable BlendingData blendingData) {
super(chunkPos, upgradeData, levelHeightAccessor, registry, l, levelChunkSections, blendingData);
}
@Unique
private int cachedChunkId = -1;
@Override
public int flashback$getCachedChunkId() {
return this.cachedChunkId;
}
@Override
public void flashback$setCachedChunkId(int id) {
this.cachedChunkId = id;
}
@Override
public void flashback$setBlockStateWithoutUpdates(BlockPos blockPos, BlockState blockState) {
int y = blockPos.getY();
LevelChunkSection levelChunkSection = this.getSection(this.getSectionIndex(y));
boolean oldHasOnlyAir = levelChunkSection.hasOnlyAir();
if (oldHasOnlyAir && blockState.isAir()) {
return;
}
// Set block
int localX = blockPos.getX() & 0xF;
int localY = y & 0xF;
int localZ = blockPos.getZ() & 0xF;
BlockState oldBlockState = levelChunkSection.setBlockState(localX, localY, localZ, blockState);
if (oldBlockState == blockState) {
return;
}
// Update heightmaps
this.heightmaps.get(Heightmap.Types.MOTION_BLOCKING).update(localX, y, localZ, blockState);
this.heightmaps.get(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES).update(localX, y, localZ, blockState);
this.heightmaps.get(Heightmap.Types.OCEAN_FLOOR).update(localX, y, localZ, blockState);
this.heightmaps.get(Heightmap.Types.WORLD_SURFACE).update(localX, y, localZ, blockState);
// Update air status
boolean newHasOnlyAir = levelChunkSection.hasOnlyAir();
if (oldHasOnlyAir != newHasOnlyAir) {
this.level.getChunkSource().getLightEngine().updateSectionStatus(blockPos, newHasOnlyAir);
}
// Update light
if (LightEngine.hasDifferentLightProperties(this, blockPos, oldBlockState, blockState)) {
if (this.skyLightSources != null) {
this.skyLightSources.update(this, localX, y, localZ);
}
this.level.getChunkSource().getLightEngine().checkBlock(blockPos);
}
// Update block entity
Block block = blockState.getBlock();
if (!oldBlockState.is(block) && oldBlockState.hasBlockEntity()) {
this.removeBlockEntity(blockPos);
}
if (!levelChunkSection.getBlockState(localX, localY, localZ).is(block)) {
return;
}
if (blockState.hasBlockEntity()) {
BlockEntity blockEntity = this.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK);
if (blockEntity == null) {
blockEntity = ((EntityBlock)block).newBlockEntity(blockPos, blockState);
if (blockEntity != null) {
this.addAndRegisterBlockEntity(blockEntity);
}
} else {
blockEntity.setBlockState(blockState);
this.updateBlockEntityTicker(blockEntity);
}
}
this.unsaved = true;
}
}
@@ -1,56 +0,0 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.ext.LevelChunkSectionExt;
import net.minecraft.core.Holder;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.PalettedContainerRO;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(LevelChunkSection.class)
public class MixinLevelChunkSection implements LevelChunkSectionExt {
@Shadow
@Final
private PalettedContainer<BlockState> states;
@Shadow
private short nonEmptyBlockCount;
@Shadow
private PalettedContainerRO<Holder<Biome>> biomes;
@Unique
private int cachedChunkId = -1;
@Override
public int flashback$getCachedChunkId() {
return this.cachedChunkId;
}
@Override
public void flashback$setCachedChunkId(int cachedChunkId) {
this.cachedChunkId = cachedChunkId;
}
@Inject(method = "read", at = @At("RETURN"))
public void read(FriendlyByteBuf friendlyByteBuf, CallbackInfo ci) {
this.cachedChunkId = -1;
}
@Inject(method = "setBlockState(IIILnet/minecraft/world/level/block/state/BlockState;Z)Lnet/minecraft/world/level/block/state/BlockState;", at = @At("RETURN"))
public void setBlockState(int i, int j, int k, BlockState blockState, boolean bl, CallbackInfoReturnable<BlockState> cir) {
this.cachedChunkId = -1;
}
}
@@ -1,6 +1,7 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayPlayer;
import net.minecraft.client.Minecraft;
import net.minecraft.server.ServerTickRateManager;
import net.minecraft.world.TickRateManager;
@@ -10,6 +11,7 @@ import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(TickRateManager.class)
@@ -18,16 +20,34 @@ public abstract class MixinTickRateManager {
@Shadow
public abstract boolean runsNormally();
@Shadow
protected boolean runGameElements;
/*
* Freeze the replay server, preventing game elements from running normally
*/
@Inject(method = "tick", at = @At("RETURN"))
public void tick(CallbackInfo ci) {
if (Flashback.isInReplay() && this.isServerTickRateManager) {
this.runGameElements = false;
}
}
@Unique
private final boolean isClientTickRateManager = !((Object)this instanceof ServerTickRateManager);
private final boolean isServerTickRateManager = ((Object)this instanceof ServerTickRateManager);
@Inject(method = "isEntityFrozen", at = @At("HEAD"), cancellable = true)
public void isEntityFrozen(Entity entity, CallbackInfoReturnable<Boolean> cir) {
if (this.isClientTickRateManager && Flashback.isInReplay()) {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) {
cir.setReturnValue(false);
if (Flashback.isInReplay()) {
if (this.isServerTickRateManager) {
cir.setReturnValue(!(entity instanceof ReplayPlayer));
} else {
cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player);
if (Flashback.isExporting()) {
cir.setReturnValue(false);
} else {
cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player);
}
}
}
}
@@ -0,0 +1,58 @@
package com.moulberry.flashback.mixin.record;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientLevel.class)
public class MixinClientLevel {
@Shadow
@Final
private Minecraft minecraft;
@Inject(method = "levelEvent", at = @At("HEAD"))
public void levelEvent(Player player, int type, BlockPos blockPos, int data, CallbackInfo ci) {
if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) {
Flashback.RECORDER.writeLevelEvent(type, blockPos, data, false);
}
}
@Inject(method = "globalLevelEvent", at = @At("HEAD"))
public void globalLevelEvent(int type, BlockPos blockPos, int data, CallbackInfo ci) {
if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) {
Flashback.RECORDER.writeLevelEvent(type, blockPos, data, true);
}
}
@Inject(method = "playSeededSound(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/core/Holder;Lnet/minecraft/sounds/SoundSource;FFJ)V", at = @At("RETURN"))
public void playSeededSoundEntity(@Nullable Player player, Entity entity, Holder<SoundEvent> holder, SoundSource soundSource, float volume, float pitch, long seed, CallbackInfo ci) {
if (player != null && player == this.minecraft.player && Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) {
Flashback.RECORDER.writePacketAsync(new ClientboundSoundEntityPacket(holder, soundSource, entity, volume, pitch, seed), ConnectionProtocol.PLAY);
}
}
@Inject(method = "playSeededSound(Lnet/minecraft/world/entity/player/Player;DDDLnet/minecraft/core/Holder;Lnet/minecraft/sounds/SoundSource;FFJ)V", at = @At("RETURN"))
public void playSeededSoundNormal(@Nullable Player player, double x, double y, double z, Holder<SoundEvent> holder, SoundSource soundSource, float volume, float pitch, long seed, CallbackInfo ci) {
if (player != null && player == this.minecraft.player && Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) {
Flashback.RECORDER.writePacketAsync(new ClientboundSoundPacket(holder, soundSource, x, y, z, volume, pitch, seed), ConnectionProtocol.PLAY);
}
}
}
@@ -1,14 +1,20 @@
package com.moulberry.flashback.mixin.replay_server;
import com.llamalad7.mixinextras.injector.v2.WrapWithCondition;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.level.Level;
import org.slf4j.Logger;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import java.util.Optional;
@@ -21,6 +27,10 @@ public class MixinPlayerList {
* Don't change the dimension of replay viewers when spawning them
*/
@Shadow
@Final
private MinecraftServer server;
@WrapOperation(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Ljava/util/Optional;flatMap(Ljava/util/function/Function;)Ljava/util/Optional;"))
public Optional<ResourceKey<Level>> placeNewPlayer_flatMap(Optional instance, Function function, Operation<Optional<ResourceKey<Level>>> original,
@Local(argsOnly = true) ServerPlayer serverPlayer) {
@@ -30,4 +40,9 @@ public class MixinPlayerList {
return original.call(instance, function);
}
@WrapWithCondition(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;info(Ljava/lang/String;[Ljava/lang/Object;)V", remap = false))
public boolean placeNewPlayer_logInfo(Logger instance, String s, Object[] objects) {
return !(this.server instanceof ReplayServer);
}
}
@@ -4,6 +4,8 @@ import com.llamalad7.mixinextras.sugar.Local;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.server.level.ServerEntity;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
@@ -12,12 +14,12 @@ import org.spongepowered.asm.mixin.injection.ModifyVariable;
public class MixinServerEntity {
/*
* Force update interval to be 1 on a replay server
* Force update interval to be 1 on a replay server, sending updates as soon as possible
*/
@ModifyVariable(method = "<init>", at = @At("HEAD"), argsOnly = true)
private static int init_modifyUpdateInterval(int updateInterval, @Local(argsOnly = true) ServerLevel level) {
if (level.getServer() instanceof ReplayServer) {
if (updateInterval <= 3 && level != null && level.getServer() instanceof ReplayServer) {
return 1;
}
return updateInterval;
@@ -1,6 +1,7 @@
package com.moulberry.flashback.mixin.replay_server;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.server.MinecraftServer;
@@ -13,6 +14,7 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Mixin(ServerLoginPacketListenerImpl.class)
@@ -32,8 +34,11 @@ public abstract class MixinServerLoginPacketListenerImpl {
@Inject(method = "handleHello", at = @At("HEAD"), cancellable = true)
public void handleHello(ServerboundHelloPacket serverboundHelloPacket, CallbackInfo ci) {
if (this.server instanceof ReplayServer) {
this.requestedUsername = "ReplayViewer";
this.startClientVerification(new GameProfile(UUID.randomUUID(), "ReplayViewer"));
this.requestedUsername = ReplayServer.REPLAY_VIEWER_NAME;
UUID replayViewerUUID = UUID.nameUUIDFromBytes(serverboundHelloPacket.name().getBytes(StandardCharsets.UTF_8));
GameProfile gameProfile = new GameProfile(replayViewerUUID, ReplayServer.REPLAY_VIEWER_NAME);
gameProfile.getProperties().put("IsReplayViewer", new Property("IsReplayViewer", "True"));
this.startClientVerification(gameProfile);
ci.cancel();
}
}
@@ -3,27 +3,22 @@ package com.moulberry.flashback.mixin.replay_server;
import com.moulberry.flashback.Flashback;
import net.minecraft.server.ServerTickRateManager;
import net.minecraft.world.TickRateManager;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(TickRateManager.class)
public abstract class MixinTickRateManager {
@Shadow
protected boolean runGameElements;
/*
* Freeze the replay server, preventing game elements from running normally
*/
@Inject(method = "tick", at = @At("RETURN"))
public void tick(CallbackInfo ci) {
if (Flashback.isInReplay() && (Object)this instanceof ServerTickRateManager) {
this.runGameElements = false;
}
@Inject(method = "isEntityFrozen", at = @At("RETURN"))
public void isEntityFrozen(Entity entity, CallbackInfoReturnable<Boolean> cir) {
}
}
@@ -1,11 +1,14 @@
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.moulberry.flashback.Flashback;
import com.moulberry.flashback.screen.BottomTextWidget;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.layouts.GridLayout;
import net.minecraft.client.gui.layouts.LayoutElement;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.PauseScreen;
import net.minecraft.network.chat.Component;
@@ -19,8 +22,8 @@ public class MixinPauseScreen {
@Inject(method = "createPauseMenu", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/layouts/GridLayout;arrangeElements()V", shift = At.Shift.BEFORE))
public void createPauseMenu(CallbackInfo ci, @Local GridLayout.RowHelper rowHelper) {
if (!Flashback.isInReplay()) {
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Flashback"), Minecraft.getInstance().font), 2);
if (!Flashback.isInReplay() && !Flashback.getConfig().hidePauseMenuControls) {
rowHelper.addChild(new BottomTextWidget(204, 30, Component.literal("Flashback"), Minecraft.getInstance().font), 2);
if (Flashback.RECORDER == null) {
rowHelper.addChild(Button.builder(Component.literal("Start Recording"), (button) -> {
Flashback.startRecordingReplay();
@@ -59,4 +62,12 @@ public class MixinPauseScreen {
}
}
@WrapOperation(method = "createPauseMenu", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/layouts/FrameLayout;alignInRectangle(Lnet/minecraft/client/gui/layouts/LayoutElement;IIIIFF)V"))
public void createPauseMenu_alignInRectangle(LayoutElement layoutElement, int i, int j, int k, int l, float f, float g, Operation<Void> original) {
if (!Flashback.isInReplay() && !Flashback.getConfig().hidePauseMenuControls) {
g += 0.05f;
}
original.call(layoutElement, i, j, k, l, f, g);
}
}
@@ -4,10 +4,14 @@ 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.screen.FlashbackButton;
import com.moulberry.flashback.screen.SelectReplayScreen;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
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.Screen;
@@ -33,8 +37,34 @@ public class MixinTitleScreen extends Screen {
@Unique
private final List<AbstractWidget> normalMenuWidgets = new ArrayList<>();
@Unique
private AbstractWidget openSelectReplayScreenButton = null;
@Inject(method = "init", at = @At("RETURN"))
public void init(CallbackInfo ci) {
if (this.openSelectReplayScreenButton != null) {
this.removeWidget(this.openSelectReplayScreenButton);
this.openSelectReplayScreenButton = null;
}
}
// We do this on tick to ensure that our button is added after ever other mod's
// Our button logic has automatic repositioning, whereas other mods (i.e. ModMenu)
// might not implement repositioning logic, causing our button to render under theirs
@Inject(method = "tick", at = @At("RETURN"))
public void tick(CallbackInfo ci) {
if (this.openSelectReplayScreenButton == null) {
this.createOpenSelectReplayScreenButton();
}
}
@Unique
private void createOpenSelectReplayScreenButton() {
if (this.openSelectReplayScreenButton != null) {
this.removeWidget(this.openSelectReplayScreenButton);
this.openSelectReplayScreenButton = null;
}
for (int offsetX = 0; offsetX < 5; offsetX++) {
for (int i = this.normalMenuWidgets.size()-1; i >= 0; i--) {
AbstractWidget widget = this.normalMenuWidgets.get(i);
@@ -48,7 +78,7 @@ public class MixinTitleScreen extends Screen {
for (Renderable renderable : this.renderables) {
if (renderable instanceof AbstractWidget otherWidget) {
if (x < otherWidget.getRight() && x+size > otherWidget.getX() &&
y < otherWidget.getBottom() && y+size > otherWidget.getY()) {
y < otherWidget.getBottom() && y+size > otherWidget.getY()) {
overlapsWithExistingButton = true;
break;
}
@@ -56,9 +86,10 @@ public class MixinTitleScreen extends Screen {
}
if (!overlapsWithExistingButton) {
this.addRenderableWidget(Button.builder(Component.literal("R"), button -> {
this.openSelectReplayScreenButton = new FlashbackButton(x, y, size, size, Component.literal("Open Replays"), button -> {
this.minecraft.setScreen(new SelectReplayScreen(this));
}).bounds(x, y, size, size).build());
});
this.addRenderableWidget(this.openSelectReplayScreenButton);
return;
}
}
@@ -1,6 +1,7 @@
package com.moulberry.flashback.mixin.visuals;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.BossHealthOverlay;
import org.spongepowered.asm.mixin.Mixin;
@@ -13,7 +14,8 @@ public class MixinBossHealthOverlay {
@Inject(method = "render", at = @At("HEAD"), cancellable = true)
public void render(GuiGraphics guiGraphics, CallbackInfo ci) {
if (!ReplayVisuals.showBossBar) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showBossBar) {
ci.cancel();
}
}
@@ -1,6 +1,8 @@
package com.moulberry.flashback.mixin.visuals;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.visuals.ReplayVisuals;
import net.minecraft.client.multiplayer.ClientLevel;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@@ -12,8 +14,9 @@ public class MixinClientLevelData {
@Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true)
public void getDayTime(CallbackInfoReturnable<Long> cir) {
if (ReplayVisuals.overrideTimeOfDay >= 0) {
cir.setReturnValue(ReplayVisuals.overrideTimeOfDay);
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideTimeOfDay >= 0) {
cir.setReturnValue(editorState.replayVisuals.overrideTimeOfDay);
}
}
@@ -3,7 +3,8 @@ package com.moulberry.flashback.mixin.visuals;
import com.llamalad7.mixinextras.injector.v2.WrapWithCondition;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.editor.ui.ReplayUI;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
@@ -34,7 +35,8 @@ public abstract class MixinEntityRenderDispatcher {
// Prevent rendering shadows when blocks are turned off
@WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;renderShadow(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/entity/Entity;FFLnet/minecraft/world/level/LevelReader;F)V"))
public boolean renderShadow(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, float f, float g, LevelReader levelReader, float h) {
return ReplayVisuals.renderBlocks;
EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderBlocks;
}
}
@@ -2,7 +2,8 @@ package com.moulberry.flashback.mixin.visuals;
import com.mojang.blaze3d.shaders.FogShape;
import com.mojang.blaze3d.systems.RenderSystem;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.client.Camera;
import net.minecraft.client.renderer.FogRenderer;
import org.spongepowered.asm.mixin.Mixin;
@@ -15,9 +16,10 @@ public class MixinFogRenderer {
@Inject(method = "setupFog", at = @At("HEAD"), cancellable = true)
private static void setupFog(Camera camera, FogRenderer.FogMode fogMode, float f, boolean bl, float g, CallbackInfo ci) {
if (ReplayVisuals.overrideFog) {
RenderSystem.setShaderFogStart(ReplayVisuals.overrideFogStart);
RenderSystem.setShaderFogEnd(ReplayVisuals.overrideFogEnd);
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideFog) {
RenderSystem.setShaderFogStart(editorState.replayVisuals.overrideFogStart);
RenderSystem.setShaderFogEnd(editorState.replayVisuals.overrideFogEnd);
RenderSystem.setShaderFogShape(FogShape.SPHERE);
ci.cancel();
}
@@ -1,6 +1,8 @@
package com.moulberry.flashback.mixin.visuals;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw;
import com.moulberry.flashback.editor.ui.ReplayUI;
import net.minecraft.client.DeltaTracker;
@@ -18,28 +20,32 @@ public class MixinGui {
@Inject(method = "renderChat", at = @At("HEAD"), cancellable = true)
public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
if (!ReplayVisuals.showChat) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showChat) {
ci.cancel();
}
}
@Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true)
public void renderTitle(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
if (!ReplayVisuals.showTitleText) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showTitleText) {
ci.cancel();
}
}
@Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true)
public void renderScoreboardSidebar(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
if (!ReplayVisuals.showScoreboard) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showScoreboard) {
ci.cancel();
}
}
@Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true)
public void renderOverlayMessage(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
if (!ReplayVisuals.showActionBar) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showActionBar) {
ci.cancel();
}
}
@@ -49,6 +55,9 @@ public class MixinGui {
if (ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) {
cir.setReturnValue(true);
}
if (Flashback.getSpectatingPlayer() != null) {
cir.setReturnValue(true);
}
}
}
@@ -0,0 +1,60 @@
package com.moulberry.flashback.mixin.visuals;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.visuals.WorldRenderHook;
import net.minecraft.client.Camera;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.RenderBuffers;
import org.joml.Matrix4f;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(LevelRenderer.class)
public class MixinLevelRenderer {
@Shadow
@Final
private RenderBuffers renderBuffers;
@Inject(method="renderLevel", at=@At(
value = "INVOKE",
target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;",
shift = At.Shift.BEFORE
))
public void renderLevelPost(net.minecraft.client.DeltaTracker deltaTracker, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture,
Matrix4f matrix4f, Matrix4f projection, CallbackInfo ci) {
if (!Flashback.isInReplay()) {
return;
}
this.renderBuffers.bufferSource().endBatch();
PoseStack poseStack = new PoseStack();
poseStack.mulPose(matrix4f);
// Set model view stack to identity
var modelViewStack = RenderSystem.getModelViewStack();
modelViewStack.pushMatrix();
modelViewStack.identity();
RenderSystem.applyModelViewMatrix();
float tickDelta = deltaTracker.getGameTimeDeltaPartialTick(true);
WorldRenderHook.renderHook(poseStack, tickDelta, renderBlockOutline, camera, gameRenderer, lightTexture, projection);
this.renderBuffers.bufferSource().endBatch();
// Pop model view stack
modelViewStack.popMatrix();
RenderSystem.applyModelViewMatrix();
}
}
@@ -0,0 +1,54 @@
package com.moulberry.flashback.mixin.visuals;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.ext.OptionsExt;
import net.minecraft.client.MouseHandler;
import net.minecraft.client.OptionInstance;
import net.minecraft.client.Options;
import net.minecraft.network.chat.Component;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(MouseHandler.class)
public class MixinMouseHandler {
// Reduces sensitivity when overriding fov to a lower value
// This makes the camera much easier to control with low fov values
@WrapOperation(method = "turnPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;sensitivity()Lnet/minecraft/client/OptionInstance;"))
public OptionInstance<Double> turnPlayer_sensitivity(Options instance, Operation<OptionInstance<Double>> original) {
OptionInstance<Double> sensitivity = original.call(instance);
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideFov) {
float newFov = editorState.replayVisuals.overrideFovAmount;
if (newFov > 20.0) {
return original.call(instance);
}
float oldFov = ((OptionsExt)instance).flashback$getOriginalFov();
if (newFov < oldFov) {
float newFocalLength = Utils.fovToFocalLength(newFov);
float oldFocalLength = Utils.fovToFocalLength(oldFov);
float sensitivityMultiplier = oldFocalLength / newFocalLength;
double newSensitivity = sensitivity.get() * sensitivityMultiplier;
sensitivity = new OptionInstance<>("options.sensitivity", OptionInstance.noTooltip(), (component, double_) -> {
if (double_ == 0.0) {
return Options.genericValueLabel(component, Component.translatable("options.sensitivity.min"));
}
if (double_ == 1.0) {
return Options.genericValueLabel(component, Component.translatable("options.sensitivity.max"));
}
return Component.translatable("options.percent_value", component, (int)(double_ * 200.0));
}, OptionInstance.UnitDouble.INSTANCE, newSensitivity, double_ -> {});
}
}
return sensitivity;
}
}
@@ -1,34 +1,46 @@
package com.moulberry.flashback.mixin.visuals;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.ext.OptionsExt;
import net.minecraft.client.OptionInstance;
import net.minecraft.client.Options;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Options.class)
public class MixinOptions {
public class MixinOptions implements OptionsExt {
@Shadow
@Final
private OptionInstance<Integer> fov;
@Unique
private OptionInstance<Integer> cachedOptionInstance = null;
private OptionInstance<Integer> cachedFovOptionInstance = null;
@Inject(method = "fov", at = @At("RETURN"), cancellable = true)
public void fov(CallbackInfoReturnable<OptionInstance<Integer>> cir) {
if (ReplayVisuals.overrideFov) {
if (this.cachedOptionInstance == null || this.cachedOptionInstance.get() != Math.round(ReplayVisuals.overrideFovAmount)) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideFov) {
if (this.cachedFovOptionInstance == null || this.cachedFovOptionInstance.get() != Math.round(editorState.replayVisuals.overrideFovAmount)) {
OptionInstance<Integer> delegate = cir.getReturnValue();
this.cachedOptionInstance = new OptionInstance<>("options.fov", OptionInstance.noTooltip(), Options::genericValueLabel,
delegate.values(), delegate.codec(), Math.round(ReplayVisuals.overrideFovAmount), value -> {
ReplayVisuals.overrideFov = false;
this.cachedFovOptionInstance = new OptionInstance<>("options.fov", OptionInstance.noTooltip(), Options::genericValueLabel,
delegate.values(), delegate.codec(), Math.round(editorState.replayVisuals.overrideFovAmount), value -> {
editorState.replayVisuals.overrideFov = false;
delegate.set(value);
});
}
cir.setReturnValue(this.cachedOptionInstance);
cir.setReturnValue(this.cachedFovOptionInstance);
}
}
@Override
public int flashback$getOriginalFov() {
return this.fov.get();
}
}
@@ -0,0 +1,15 @@
package com.moulberry.flashback.packet;
import com.moulberry.flashback.Flashback;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
public class FlashbackClearParticles implements CustomPacketPayload {
public static final Type<FlashbackClearParticles> TYPE = new Type<>(Flashback.createResourceLocation("clear_particles"));
public static final FlashbackClearParticles INSTANCE = new FlashbackClearParticles();
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}
@@ -0,0 +1,15 @@
package com.moulberry.flashback.packet;
import com.moulberry.flashback.Flashback;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
public class FlashbackForceClientTick implements CustomPacketPayload {
public static final Type<FlashbackForceClientTick> TYPE = new Type<>(Flashback.createResourceLocation("force_client_tick"));
public static final FlashbackForceClientTick INSTANCE = new FlashbackForceClientTick();
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}
@@ -0,0 +1,15 @@
package com.moulberry.flashback.packet;
import com.moulberry.flashback.Flashback;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
public class FlashbackInstantlyLerp implements CustomPacketPayload {
public static final Type<FlashbackInstantlyLerp> TYPE = new Type<>(Flashback.createResourceLocation("instantly_lerp"));
public static final FlashbackInstantlyLerp INSTANCE = new FlashbackInstantlyLerp();
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}
@@ -1,8 +1,10 @@
package com.moulberry.flashback.playback;
import com.mojang.authlib.GameProfile;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.PacketHelper;
import com.moulberry.flashback.exception.UnsupportedPacketException;
import com.moulberry.flashback.ext.LevelChunkExt;
import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt;
import io.netty.channel.embedded.EmbeddedChannel;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
@@ -43,7 +45,11 @@ import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeMap;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.decoration.HangingEntity;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.decoration.Painting;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.npc.Villager;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.GameRules;
@@ -61,6 +67,7 @@ import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.lighting.LevelLightEngine;
import net.minecraft.world.level.storage.DerivedLevelData;
import net.minecraft.world.level.storage.PrimaryLevelData;
import net.minecraft.world.level.storage.ServerLevelData;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable;
@@ -102,6 +109,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
serverChunkCache.broadcast(entity, packet);
}
private void setBlockState(ServerLevel level, BlockPos blockPos, BlockState blockState) {
LevelChunk levelChunk = level.getChunkAt(blockPos);
((LevelChunkExt)levelChunk).flashback$setBlockStateWithoutUpdates(blockPos, blockState);
level.getChunkSource().blockChanged(blockPos);
}
public void flushPendingEntities() {
ServerLevel level = this.level();
for (Entity pendingEntity : this.pendingEntities.values()) {
@@ -115,6 +128,8 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
existingEntity.setXRot(pendingEntity.getXRot());
existingEntity.setYRot(pendingEntity.getYRot());
existingEntity.setYHeadRot(pendingEntity.getYHeadRot());
existingEntity.setDeltaMovement(pendingEntity.getDeltaMovement());
existingEntity.hasImpulse = pendingEntity.hasImpulse;
if (pendingEntity instanceof LivingEntity pendingLiving) {
existingEntity.setYBodyRot(pendingLiving.yBodyRot);
}
@@ -149,7 +164,11 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleAddEntity(ClientboundAddEntityPacket clientboundAddEntityPacket) {
if (Entity.ENTITY_COUNTER.get() <= clientboundAddEntityPacket.getId()) {
Entity.ENTITY_COUNTER.set(clientboundAddEntityPacket.getId() + 1);
Entity.ENTITY_COUNTER.set(clientboundAddEntityPacket.getId() + 1000);
}
if (clientboundAddEntityPacket.id >= ReplayServer.REPLAY_VIEWER_IDS_START && clientboundAddEntityPacket.id <= ReplayServer.REPLAY_VIEWER_IDS_START+128) {
clientboundAddEntityPacket.id += 128;
}
Entity entity = this.createEntityFromPacket(clientboundAddEntityPacket);
@@ -167,6 +186,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
private void spawnPlayer(ClientboundAddEntityPacket addEntityPacket, GameProfile gameProfile, GameType gameType) {
this.flushPendingEntities();
gameProfile.getProperties().removeAll("IsReplayViewer");
CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false);
ServerPlayer serverPlayer = new ServerPlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()){
@@ -228,6 +248,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
entity.setYRot(0.0f);
entity.setXRot(0.0f);
entity.setId(clientboundAddExperienceOrbPacket.getId());
entity.setDeltaMovement(Vec3.ZERO);
Entity existingEntity = this.level().getEntity(clientboundAddExperienceOrbPacket.getId());
if (existingEntity instanceof ExperienceOrb) {
@@ -303,8 +324,8 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleBlockUpdate(ClientboundBlockUpdatePacket clientboundBlockUpdatePacket) {
this.level().setBlock(clientboundBlockUpdatePacket.getPos(),
clientboundBlockUpdatePacket.getBlockState(), 18);
this.setBlockState(this.level(), clientboundBlockUpdatePacket.getPos(),
clientboundBlockUpdatePacket.getBlockState());
}
@Override
@@ -329,8 +350,9 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleChunkBlocksUpdate(ClientboundSectionBlocksUpdatePacket clientboundSectionBlocksUpdatePacket) {
ServerLevel level = this.level();
clientboundSectionBlocksUpdatePacket.runUpdates((blockPos, blockState) -> {
this.level().setBlock(blockPos, blockState, 18);
this.setBlockState(level, blockPos, blockState);
});
}
@@ -559,8 +581,22 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
this.localPlayerId = clientboundLoginPacket.playerId();
this.ensureWorldCreated(clientboundLoginPacket.commonPlayerSpawnInfo(), recreatePlayer ? null : localPlayer, true);
// Update special world property
CommonPlayerSpawnInfo spawnInfo = clientboundLoginPacket.commonPlayerSpawnInfo();
if (this.replayServer.getWorldData() instanceof PrimaryLevelData primaryLevelData) {
PrimaryLevelData.SpecialWorldProperty specialWorldProperty;
if (spawnInfo.isFlat()) {
specialWorldProperty = PrimaryLevelData.SpecialWorldProperty.FLAT;
} else if (spawnInfo.isDebug()) {
specialWorldProperty = PrimaryLevelData.SpecialWorldProperty.DEBUG;
} else {
specialWorldProperty = PrimaryLevelData.SpecialWorldProperty.NONE;
}
primaryLevelData.specialWorldProperty = specialWorldProperty;
}
if (recreatePlayer) {
ClientboundAddEntityPacket addEntityPacket = PacketHelper.createAddEntity(localPlayer);
ClientboundAddEntityPacket addEntityPacket = (ClientboundAddEntityPacket) PacketHelper.createAddEntity(localPlayer);
addEntityPacket.id = clientboundLoginPacket.playerId();
this.spawnPlayer(addEntityPacket, localPlayer.getGameProfile(), localPlayer.gameMode.getGameModeForPlayer());
}
@@ -595,7 +631,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
}
}
if (!this.replayServer.levels.containsKey(dimension)) {
ServerLevel oldLevel = this.replayServer.getLevel(dimension);
// Force recreate level if the DimensionType has changed
boolean forceRecreate = oldLevel != null && !oldLevel.dimensionType().equals(commonPlayerSpawnInfo.dimensionType().value());
if (oldLevel == null || forceRecreate) {
ServerLevelData serverLevelData = this.replayServer.worldData.overworldData();
if (dimension != Level.OVERWORLD) {
serverLevelData = new DerivedLevelData(this.replayServer.worldData, serverLevelData);
@@ -609,19 +650,27 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
serverLevel.noSave = true;
this.replayServer.levels.put(dimension, serverLevel);
this.replayServer.followLocalPlayerNextTick = true;
if (oldLevel != null) {
this.replayServer.closeLevel(oldLevel);
}
}
if (this.currentDimension == dimension) {
this.replayServer.followLocalPlayerNextTickIfFar = true;
ServerLevel newLevel = this.replayServer.getLevel(dimension);
if (newLevel == oldLevel) {
if (!this.replayServer.isProcessingSnapshot) {
this.replayServer.followLocalPlayerNextTickIfFar = true;
}
return;
}
// Move local player and replay viewer
if (localPlayer != null) {
localPlayer.teleportTo(this.replayServer.getLevel(dimension), 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f);
localPlayer.teleportTo(newLevel, 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f);
}
for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) {
replayViewer.teleportTo(this.replayServer.getLevel(dimension), 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f);
replayViewer.teleportTo(newLevel, 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f);
}
this.replayServer.followLocalPlayerNextTick = true;
@@ -822,10 +871,11 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
return;
}
double motionX = clientboundSetEntityMotionPacket.getXa() / 8000.0;
double motionY = clientboundSetEntityMotionPacket.getYa() / 8000.0;
double motionZ = clientboundSetEntityMotionPacket.getZa() / 8000.0;
double motionX = clientboundSetEntityMotionPacket.getXa();
double motionY = clientboundSetEntityMotionPacket.getYa();
double motionZ = clientboundSetEntityMotionPacket.getZa();
entity.setDeltaMovement(motionX, motionY, motionZ);
entity.hasImpulse = true;
}
@Override
@@ -906,6 +956,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleSoundEvent(ClientboundSoundPacket clientboundSoundPacket) {
if (Flashback.EXPORT_JOB == null && this.replayServer.replayPaused) {
return;
}
Holder<SoundEvent> sound = clientboundSoundPacket.getSound();
double x = clientboundSoundPacket.getX();
double y = clientboundSoundPacket.getY();
@@ -917,6 +971,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleSoundEntityEvent(ClientboundSoundEntityPacket clientboundSoundEntityPacket) {
if (Flashback.EXPORT_JOB == null && this.replayServer.replayPaused) {
return;
}
Entity entity = this.level().getEntity(clientboundSoundEntityPacket.getId());
if (entity == null) {
return;
@@ -9,9 +9,11 @@ import net.minecraft.stats.Stat;
import net.minecraft.world.item.crafting.RecipeHolder;
import java.util.Collection;
import java.util.UUID;
public class ReplayPlayer extends ServerPlayer {
public boolean followLocalPlayerNextTick = false;
public UUID spectatingUuid = null;
public ReplayPlayer(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation clientInformation) {
super(minecraftServer, serverLevel, gameProfile, clientInformation);
@@ -4,11 +4,14 @@ import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.ext.LevelChunkExt;
import com.moulberry.flashback.TempFolderProvider;
import com.moulberry.flashback.keyframe.handler.ReplayServerKeyframeHandler;
import com.moulberry.flashback.packet.FlashbackClearParticles;
import com.moulberry.flashback.packet.FlashbackForceClientTick;
import com.moulberry.flashback.packet.FlashbackInstantlyLerp;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
import com.moulberry.flashback.ext.LevelChunkSectionExt;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.ext.ServerGamePacketListenerImplExt;
import com.moulberry.flashback.io.ReplayReader;
@@ -51,12 +54,12 @@ import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.WorldDataConfiguration;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.storage.LevelStorageSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -66,6 +69,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -73,19 +77,22 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ReplayServer extends IntegratedServer {
private static final Gson GSON = new Gson();
public static int REPLAY_VIEWER_IDS_START = -981723987;
public static String REPLAY_VIEWER_NAME = "Replay Viewer";
public volatile int jumpToTick = -1;
public volatile boolean replayPaused = true;
public AtomicBoolean forceApplyKeyframes = new AtomicBoolean(false);
public AtomicBoolean sendFinishedServerTick = new AtomicBoolean(false);
public volatile float desiredTickRate = 20.0f;
private volatile float desiredTickRate = 20.0f;
private volatile float desiredTickRateManual = 20.0f;
private int currentTick = 0;
private int targetTick = 0;
private volatile int targetTick = 0;
private final int totalTicks;
public ResourceKey<Level> spawnLevel = null;
private final ReplayGamePacketHandler gamePacketHandler;
@@ -97,6 +104,7 @@ public class ReplayServer extends IntegratedServer {
public boolean followLocalPlayerNextTickIfFar = false;
public boolean isProcessingSnapshot = false;
private boolean processedSnapshot = false;
private volatile boolean fastForwarding = false;
private final UUID playbackUUID;
private final FlashbackMeta metadata;
@@ -112,6 +120,7 @@ public class ReplayServer extends IntegratedServer {
private Component tabListFooter = Component.empty();
private Component shutdownReason = null;
private FileSystem playbackFileSystem = null;
public ReplayServer(Thread thread, Minecraft minecraft, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Services services,
ChunkProgressListenerFactory chunkProgressListenerFactory, UUID playbackUUID, Path path) {
@@ -124,36 +133,10 @@ public class ReplayServer extends IntegratedServer {
this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec();
try {
Path playbackFolder = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.PLAYBACK, playbackUUID);
this.playbackFileSystem = FileSystems.newFileSystem(path);
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(Files.newInputStream(path));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(playbackFolder.toFile(), zipEntry);
if (zipEntry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create directory " + newFile);
}
} else {
// fix for Windows-created archives
File parent = newFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent);
}
// write file content
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
String metadataJson = Files.readString(playbackFolder.resolve("metadata.json"));
Path metadataPath = this.playbackFileSystem.getPath("/metadata.json");
String metadataJson = Files.readString(metadataPath);
this.metadata = FlashbackMeta.fromJson(GSON.fromJson(metadataJson, JsonObject.class));
if (this.metadata == null) {
throw new RuntimeException("Invalid metadata file");
@@ -161,14 +144,14 @@ public class ReplayServer extends IntegratedServer {
int ticks = 0;
for (Map.Entry<String, FlashbackChunkMeta> entry : this.metadata.chunks.entrySet()) {
var chunkMetaWithPath = new PlayableChunk(entry.getValue(), playbackFolder.resolve(entry.getKey()));
var chunkMetaWithPath = new PlayableChunk(entry.getValue(), this.playbackFileSystem.getPath("/"+entry.getKey()));
this.playableChunksByStart.put(ticks, chunkMetaWithPath);
ticks += entry.getValue().duration;
}
this.totalTicks = ticks;
Path levelChunkCachePath = playbackFolder.resolve("level_chunk_cache");
Path levelChunkCachePath = this.playbackFileSystem.getPath("/level_chunk_cache");
if (Files.exists(levelChunkCachePath)) {
int chunkCacheIndex = 0;
@@ -214,19 +197,6 @@ public class ReplayServer extends IntegratedServer {
return this.metadata;
}
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
public void updateRegistry(FeatureFlagSet featureFlagSet, Collection<String> selectedPacks, List<Packet<? super ClientConfigurationPacketListener>> initialPackets,
List<ConfigurationTask> configurationTasks) {
this.worldData.setDataConfiguration(new WorldDataConfiguration(
@@ -252,7 +222,9 @@ public class ReplayServer extends IntegratedServer {
@Override
public boolean initServer() {
AtomicInteger newPlayerIds = new AtomicInteger(-981723987);
Entity.ENTITY_COUNTER.set(1000000);
AtomicInteger newPlayerIds = new AtomicInteger(REPLAY_VIEWER_IDS_START);
this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, 1) {
@Override
public ServerPlayer getPlayerForLogin(GameProfile gameProfile, ClientInformation clientInformation) {
@@ -347,6 +319,22 @@ public class ReplayServer extends IntegratedServer {
this.jumpToTick = tick;
}
public float getDesiredTickRate(boolean manual) {
if (manual) {
return this.desiredTickRateManual;
} else {
return this.desiredTickRate;
}
}
public void setDesiredTickRate(float tickrate, boolean manual) {
if (manual) {
this.desiredTickRateManual = tickrate;
} else {
this.desiredTickRate = tickrate;
}
}
public int getReplayTick() {
return this.targetTick;
}
@@ -355,9 +343,8 @@ public class ReplayServer extends IntegratedServer {
private long lastTickTimeNanos;
public float getPartialReplayTick() {
int lastReplayTick = this.lastReplayTick;
if (this.replayPaused || this.isPaused()) {
return lastReplayTick;
return this.targetTick;
} else {
long currentNanos = Util.getNanos();
long nanosPerTick = this.tickRateManager().nanosecondsPerTick();
@@ -365,7 +352,7 @@ public class ReplayServer extends IntegratedServer {
double partial = (currentNanos - this.lastTickTimeNanos) / (double) nanosPerTick;
partial = Math.max(0, Math.min(1, partial));
return lastReplayTick + (float) partial;
return this.lastReplayTick + (float) partial;
}
}
@@ -374,7 +361,7 @@ public class ReplayServer extends IntegratedServer {
}
public boolean doClientRendering() {
return !this.isProcessingSnapshot && !this.processedSnapshot;
return !this.isProcessingSnapshot && !this.processedSnapshot && !this.fastForwarding;
}
public void updateBossBar(ClientboundBossEventPacket packet) {
@@ -540,8 +527,8 @@ public class ReplayServer extends IntegratedServer {
if (!doesCachedChunkIdMatch(chunk, index)) {
packet.handle(this.gamePacketHandler);
for (LevelChunkSection section : chunk.getSections()) {
((LevelChunkSectionExt)section).flashback$setCachedChunkId(index);
if (chunk instanceof LevelChunkExt ext) {
ext.flashback$setCachedChunkId(index);
}
}
} else {
@@ -550,13 +537,10 @@ public class ReplayServer extends IntegratedServer {
}
private static boolean doesCachedChunkIdMatch(LevelChunk chunk, int chunkId) {
for (LevelChunkSection section : chunk.getSections()) {
if (chunkId != ((LevelChunkSectionExt) section).flashback$getCachedChunkId()) {
return false;
}
if (chunk instanceof LevelChunkExt ext) {
return ext.flashback$getCachedChunkId() == chunkId;
}
return true;
return false;
}
public static final TicketType<ChunkPos> ENTITY_LOAD_TICKET = TicketType.create("replay_entity_load", Comparator.comparingLong(ChunkPos::toLong), 5);
@@ -597,48 +581,70 @@ public class ReplayServer extends IntegratedServer {
return super.haveTime() && this.jumpToTick < 0;
}
public EditorState getEditorState() {
return EditorStateManager.get(this.metadata.replayIdentifier);
}
@Override
public void tickServer(BooleanSupplier booleanSupplier) {
this.lastReplayTick = this.currentTick;
this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick();
if (!this.replayPaused) {
EditorState editorState = EditorStateCache.get(this.metadata.replayIdentifier);
editorState.applyKeyframes(this, this.lastReplayTick);
}
// Update list of replay viewers
this.replayViewers.clear();
for (ServerPlayer player : this.getPlayerList().getPlayers()) {
if (player instanceof ReplayPlayer replayPlayer) {
Entity cameraEntity = replayPlayer.getCamera();
replayPlayer.spectatingUuid = cameraEntity == null || cameraEntity == replayPlayer ? null : cameraEntity.getUUID();
this.replayViewers.add(replayPlayer);
}
}
int extraForceEntityLerpTicks = 0;
// Update current tick
boolean normalPlayback = false;
if (this.jumpToTick >= 0) {
this.targetTick = this.jumpToTick;
this.jumpToTick = -1;
extraForceEntityLerpTicks = Math.max(0, Math.abs(this.targetTick - this.currentTick) - 1);
} else if (!this.isPaused() && !this.replayPaused && this.targetTick < this.totalTicks) {
// Normal playback
this.targetTick += 1;
normalPlayback = true;
} else if (this.targetTick == this.totalTicks && this.currentTick == this.totalTicks) {
// Pause when reaching end of replay
this.replayPaused = true;
}
// Update tick rate & frozen state
if (this.tickRateManager().tickrate() != this.desiredTickRate) {
this.tickRateManager().setTickRate(this.desiredTickRate);
if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback) {
this.runUpdates(booleanSupplier);
} else {
int realTargetTick = this.targetTick;
if (this.targetTick < this.currentTick) {
int minTick = this.playableChunksByStart.floorKey(this.targetTick) + 1;
this.targetTick = Math.max(minTick, realTargetTick - 20);
} else {
this.targetTick = Math.max(this.currentTick+1, realTargetTick - 20);
}
if (this.targetTick >= realTargetTick) {
this.targetTick = realTargetTick;
this.runUpdates(booleanSupplier);
} else {
while (this.targetTick <= realTargetTick) {
this.fastForwarding = this.targetTick < realTargetTick;
this.runUpdates(booleanSupplier);
if (this.targetTick == realTargetTick) {
break;
} else {
this.targetTick += 1;
}
}
this.fastForwarding = false;
}
}
boolean wantFrozen = this.replayPaused && this.targetTick == this.currentTick;
if (this.tickRateManager().isFrozen() != wantFrozen) {
this.tickRateManager().setFrozen(wantFrozen);
}
this.handleActions();
this.tryFollowLocalPlayer();
// Update resourcepacks
@@ -653,11 +659,11 @@ public class ReplayServer extends IntegratedServer {
RemotePack oldRemotePack = this.oldRemotePacks.get(entry.getKey());
if (oldRemotePack == null) {
this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash,
true, Optional.empty()));
true, Optional.empty()));
} else if (!oldRemotePack.equals(remotePack)) {
this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.of(remotePack.id)));
this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash,
true, Optional.empty()));
true, Optional.empty()));
}
this.oldRemotePacks.put(entry.getKey(), remotePack);
}
@@ -671,9 +677,41 @@ public class ReplayServer extends IntegratedServer {
});
}
if (extraForceEntityLerpTicks > 0) {
ReplayVisuals.forceEntityLerpTicks = Math.min(10, ReplayVisuals.forceEntityLerpTicks + extraForceEntityLerpTicks);
if (this.sendFinishedServerTick.compareAndExchange(true, false)) {
for (ReplayPlayer replayViewer : this.replayViewers) {
ServerPlayNetworking.send(replayViewer, FinishedServerTick.INSTANCE);
}
if (this.replayViewers.isEmpty() && Flashback.EXPORT_JOB != null) {
Flashback.EXPORT_JOB.onFinishedServerTick();
}
}
}
private void runUpdates(BooleanSupplier booleanSupplier) {
boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false) && Flashback.EXPORT_JOB == null;
if (!this.replayPaused || forceApplyKeyframes) {
this.desiredTickRate = 20.0f;
EditorState editorState = EditorStateManager.get(this.metadata.replayIdentifier);
editorState.applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick);
if (forceApplyKeyframes) {
((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes();
}
}
float tickRate = this.desiredTickRate;
if (Flashback.EXPORT_JOB == null) {
tickRate *= this.desiredTickRateManual / 20f;
}
// Update tick rate & frozen state
if (this.tickRateManager().tickrate() != tickRate) {
this.tickRateManager().setTickRate(tickRate);
}
boolean tickChanged = this.targetTick != this.currentTick;
this.handleActions();
// Add tickets for keeping entities loaded
for (ServerLevel level : this.getAllLevels()) {
@@ -686,34 +724,55 @@ public class ReplayServer extends IntegratedServer {
// Tick underlying server
super.tickServer(booleanSupplier);
if (this.processedSnapshot) {
this.processedSnapshot = false;
if (Flashback.EXPORT_JOB == null) {
if (this.processedSnapshot) {
this.processedSnapshot = false;
for (ReplayPlayer replayViewer : this.replayViewers) {
replayViewer.connection.chunkSender.sendNextChunks(replayViewer);
}
for (ServerLevel level : this.getAllLevels()) {
for (ServerPlayer player : level.players()) {
if (player instanceof ReplayPlayer) {
// Called twice, first one will update the chunk tracking & second one will update the entity tracking
level.getChunkSource().move(player);
level.getChunkSource().move(player);
for (ReplayPlayer replayViewer : this.replayViewers) {
replayViewer.connection.chunkSender.sendNextChunks(replayViewer);
ServerPlayNetworking.send(replayViewer, FlashbackInstantlyLerp.INSTANCE);
ServerPlayNetworking.send(replayViewer, FlashbackClearParticles.INSTANCE);
// Ensure replay viewers are still spectating
if (replayViewer.spectatingUuid != null) {
Entity camera = replayViewer.getCamera();
if (camera == null || camera == replayViewer || camera.isRemoved()) {
Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid);
if (targetEntity != null && !targetEntity.isRemoved()) {
replayViewer.setCamera(targetEntity);
} else {
replayViewer.spectatingUuid = null;
}
} else {
replayViewer.spectatingUuid = null;
}
}
}
for (ServerLevel level : this.getAllLevels()) {
for (ServerPlayer player : level.players()) {
if (player instanceof ReplayPlayer) {
// Called twice, first one will update the chunk tracking & second one will update the entity tracking
level.getChunkSource().move(player);
level.getChunkSource().move(player);
}
}
}
}
if (Flashback.EXPORT_JOB == null) {
ReplayVisuals.forceEntityLerpTicks = 10;
((MinecraftExt)Minecraft.getInstance()).flashback$forceClientTick();
}
}
if (this.sendFinishedServerTick.compareAndExchange(true, false)) {
for (ReplayPlayer replayViewer : this.replayViewers) {
ServerPlayNetworking.send(replayViewer, FinishedServerTick.INSTANCE);
}
if (this.replayViewers.isEmpty() && Flashback.EXPORT_JOB != null) {
Flashback.EXPORT_JOB.onFinishedServerTick();
if (this.replayPaused) {
if (tickChanged) {
if (this.tickRateManager().isFrozen()) {
this.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);
}
} else if (this.tickRateManager().isFrozen()) {
this.tickRateManager().setFrozen(false);
}
}
}
@@ -751,6 +810,15 @@ public class ReplayServer extends IntegratedServer {
if (shouldJump) {
this.processedSnapshot = true;
// Clear bossbars and particles
for (ReplayPlayer replayViewer : this.replayViewers) {
for (UUID uuid : this.bossEvents.keySet()) {
replayViewer.connection.send(ClientboundBossEventPacket.createRemovePacket(uuid));
}
}
this.bossEvents.clear();
Map.Entry<Integer, PlayableChunk> entry = this.playableChunksByStart.floorEntry(this.targetTick);
ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess());
replayReader.handleSnapshot(this);
@@ -867,7 +935,13 @@ public class ReplayServer extends IntegratedServer {
super.stopServer();
this.clearReplayTempFolder();
TempFolderProvider.deleteTemp(TempFolderProvider.TempFolderType.PLAYBACK, this.playbackUUID);
if (this.playbackFileSystem != null) {
try {
this.playbackFileSystem.close();
} catch (IOException e) {
Flashback.LOGGER.error("Failed to close playback zip", e);
}
}
}
public void clearReplayTempFolder() {
@@ -876,6 +950,6 @@ public class ReplayServer extends IntegratedServer {
@Override
public boolean isSingleplayerOwner(GameProfile gameProfile) {
return gameProfile.getName().equals("ReplayViewer");
return gameProfile.getName().equals(REPLAY_VIEWER_NAME) && gameProfile.getProperties().containsKey("IsReplayViewer");
}
}
@@ -10,16 +10,29 @@ import java.util.UUID;
public class FlashbackMeta {
public String name = "Unnamed";
public LinkedHashMap<String, FlashbackChunkMeta> chunks = new LinkedHashMap<>();
public int totalTicks = -1;
public UUID replayIdentifier = UUID.randomUUID();
public String name = "Unnamed";
public String versionString = null;
public int dataVersion = 0;
public int protocolVersion = 0;
public int totalTicks = -1;
public LinkedHashMap<String, FlashbackChunkMeta> chunks = new LinkedHashMap<>();
public JsonObject toJson() {
JsonObject meta = new JsonObject();
meta.addProperty("uuid", this.replayIdentifier.toString());
meta.addProperty("name", this.name);
meta.addProperty("uuid", this.replayIdentifier.toString());
if (this.versionString != null) {
meta.addProperty("version_string", this.versionString);
}
if (this.dataVersion != 0) {
meta.addProperty("data_version", this.dataVersion);
}
if (this.protocolVersion != 0) {
meta.addProperty("protocol_version", this.protocolVersion);
}
if (this.totalTicks > 0) {
meta.addProperty("total_ticks", this.totalTicks);
@@ -38,17 +51,27 @@ public class FlashbackMeta {
public static FlashbackMeta fromJson(JsonObject meta) {
FlashbackMeta flashbackMeta = new FlashbackMeta();
// UUID
if (!meta.has("uuid")) {
return null;
}
flashbackMeta.replayIdentifier = UUID.fromString(meta.get("uuid").getAsString());
// Name
if (!meta.has("name")) {
return null;
}
flashbackMeta.name = meta.get("name").getAsString();
// UUID
if (!meta.has("uuid")) {
return null;
if (meta.has("version_string")) {
flashbackMeta.versionString = meta.get("version_string").getAsString();
}
if (meta.has("data_version")) {
flashbackMeta.dataVersion = meta.get("data_version").getAsInt();
}
if (meta.has("protocol_version")) {
flashbackMeta.protocolVersion = meta.get("protocol_version").getAsInt();
}
flashbackMeta.replayIdentifier = UUID.fromString(meta.get("uuid").getAsString());
// Total ticks
if (meta.has("total_ticks")) {
@@ -74,7 +74,8 @@ public class IgnoredPacketSet {
ClientboundChunkBatchStartPacket.class,
ClientboundChunkBatchFinishedPacket.class,
ClientboundDebugSamplePacket.class,
ClientboundPongResponsePacket.class
ClientboundPongResponsePacket.class,
ClientboundLevelEventPacket.class
);
}
@@ -10,11 +10,13 @@ import com.moulberry.flashback.action.*;
import com.moulberry.flashback.io.AsyncReplaySaver;
import com.moulberry.flashback.io.ReplayWriter;
import io.netty.buffer.ByteBuf;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Screenshot;
import net.minecraft.client.gui.components.BossHealthOverlay;
import net.minecraft.client.gui.components.LerpingBossEvent;
import net.minecraft.client.gui.components.PlayerTabOverlay;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.multiplayer.ClientChunkCache;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.ClientPacketListener;
@@ -56,11 +58,10 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.border.WorldBorder;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.scores.*;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
import java.util.*;
@@ -106,6 +107,7 @@ public class Recorder {
private boolean isConfiguring = false;
private boolean finishedConfiguration = false;
private boolean finishedPausing = false;
private ResourceKey<Level> lastDimensionType = null;
private volatile boolean needsInitialSnapshot = true;
private volatile boolean closeForWriting = false;
@@ -116,6 +118,10 @@ public class Recorder {
this.asyncReplaySaver = new AsyncReplaySaver(registryAccess);
this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec();
this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec();
this.metadata.dataVersion = SharedConstants.getCurrentVersion().getDataVersion().getVersion();
this.metadata.protocolVersion = SharedConstants.getProtocolVersion();
this.metadata.versionString = SharedConstants.VERSION_STRING;
}
public void setRegistryAccess(RegistryAccess registryAccess) {
@@ -155,29 +161,42 @@ public class Recorder {
this.finishedConfiguration |= this.flushPackets();
if (Minecraft.getInstance().level != null && Minecraft.getInstance().getOverlay() == null && !Minecraft.getInstance().isPaused() && !this.isPaused) {
Minecraft minecraft = Minecraft.getInstance();
boolean isLevelLoaded = !(Minecraft.getInstance().screen instanceof ReceivingLevelScreen);
boolean changedDimensions = false;
if (minecraft.level != null && (minecraft.getOverlay() == null || !minecraft.getOverlay().isPauseScreen()) &&
!minecraft.isPaused() && !this.isPaused && isLevelLoaded) {
this.writeEntityPositions();
this.writeLocalData();
this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE));
this.writtenTicksInChunk += 1;
this.writtenTicks += 1;
if (!this.hasTakenScreenshot) {
Minecraft minecraft = Minecraft.getInstance();
if (minecraft.levelRenderer.countRenderedSections() > 10 && minecraft.levelRenderer.hasRenderedAllSections()) {
NativeImage nativeImage = Screenshot.takeScreenshot(minecraft.getMainRenderTarget());
this.asyncReplaySaver.writeIcon(nativeImage);
this.hasTakenScreenshot = true;
}
if (!this.hasTakenScreenshot && ((this.writtenTicks >= 20 && minecraft.screen == null) || close)) {
NativeImage nativeImage = Screenshot.takeScreenshot(minecraft.getMainRenderTarget());
this.asyncReplaySaver.writeIcon(nativeImage);
this.hasTakenScreenshot = true;
}
// Write chunk after changing dimensions
ResourceKey<Level> dimension = minecraft.level.dimension();
if (this.lastDimensionType == null) {
this.lastDimensionType = dimension;
} else if (this.lastDimensionType != dimension) {
this.lastDimensionType = dimension;
changedDimensions = true;
}
}
this.finishedPausing |= this.wasPaused && !this.isPaused;
boolean writeChunk = close;
if (Minecraft.getInstance().level != null) {
if (minecraft.level != null) {
boolean finished = this.finishedConfiguration || this.finishedPausing;
writeChunk |= this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || finished;
writeChunk |= this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || finished || changedDimensions;
}
if (writeChunk) {
@@ -214,6 +233,9 @@ public class Recorder {
this.finishedPausing = false;
this.finishedConfiguration = false;
if (minecraft.level != null) {
this.lastDimensionType = minecraft.level.dimension();
}
}
if (!this.isPaused) {
@@ -229,17 +251,8 @@ public class Recorder {
this.isPaused = paused;
}
public void finish(@Nullable Path outputFile) {
Path recordFolder = this.asyncReplaySaver.finish();
if (outputFile != null) {
ReplayExporter.export(recordFolder, outputFile);
} else {
try {
FileUtils.deleteDirectory(recordFolder.toFile());
} catch (Exception e) {
Flashback.LOGGER.error("Exception deleting record folder", e);
}
}
public Path finish() {
return this.asyncReplaySaver.finish();
}
private void writeLocalData() {
@@ -337,13 +350,18 @@ public class Recorder {
List<IdWithPosition> changedPositions = new ArrayList<>();
for (Entity entity : level.entitiesForRendering()) {
if (PacketHelper.shouldIgnoreEntity(entity)) {
continue;
}
Position position;
if (entity instanceof LivingEntity livingEntity) {
double lerpHeadRot = livingEntity.lerpHeadSteps > 0 ? livingEntity.lerpYHeadRot : livingEntity.getYHeadRot();
position = new Position(livingEntity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(),
entity.lerpTargetYRot(), entity.lerpTargetXRot(), (float) lerpHeadRot, entity.onGround());
} else {
position = new Position(entity.getX(), entity.getY(), entity.getZ(),
var trackingPosition = entity.trackingPosition();
position = new Position(trackingPosition.x, trackingPosition.y, trackingPosition.z,
entity.getYRot(), entity.getXRot(), entity.getYHeadRot(), entity.onGround());
}
Position lastPosition = this.lastPositions.get(entity);
@@ -430,6 +448,14 @@ public class Recorder {
return endedConfiguration;
}
public void writeLevelEvent(int type, BlockPos blockPos, int data, boolean globalEvent) {
if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) {
return;
}
this.pendingPackets.add(new PacketWithPhase(new ClientboundLevelEventPacket(type, blockPos, data, globalEvent), ConnectionProtocol.PLAY));
}
public void writePacketAsync(Packet<?> packet, ConnectionProtocol phase) {
if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) {
return;
@@ -522,7 +548,7 @@ public class Recorder {
// Login packet
CommonPlayerSpawnInfo commonPlayerSpawnInfo = new CommonPlayerSpawnInfo(level.dimensionTypeRegistration(), level.dimension(), 0,
gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), false, Optional.empty(), 0);
gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), level.getLevelData().isFlat, Optional.empty(), 0);
var loginPacket = new ClientboundLoginPacket(localPlayer.getId(), level.getLevelData().isHardcore(), connection.levels(),
1, Minecraft.getInstance().options.getEffectiveRenderDistance(), level.getServerSimulationDistance(),
localPlayer.isReducedDebugInfo(), localPlayer.shouldShowDeathScreen(), localPlayer.getDoLimitedCrafting(), commonPlayerSpawnInfo, false);
@@ -671,6 +697,10 @@ public class Recorder {
// Entity data
for (Entity entity : level.entitiesForRendering()) {
if (PacketHelper.shouldIgnoreEntity(entity)) {
continue;
}
if (!(entity instanceof LocalPlayer)) {
gamePackets.add(PacketHelper.createAddEntity(entity));
}
@@ -9,6 +9,7 @@ import org.jetbrains.annotations.Nullable;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -20,7 +21,7 @@ public class ReplayExporter {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static void export(Path recordFolder, Path outputFile) {
public static void export(Path recordFolder, Path outputFile, @Nullable String name) {
Flashback.LOGGER.info("Exporting {} to {}", recordFolder, outputFile);
FlashbackMeta meta = tryReadMeta(recordFolder.resolve("metadata.json"));
@@ -32,6 +33,10 @@ public class ReplayExporter {
return;
}
if (name != null) {
meta.name = name;
}
// Validate
meta.chunks.keySet().removeIf(chunkName -> {
Path chunkPath = recordFolder.resolve(chunkName);
@@ -48,6 +53,12 @@ public class ReplayExporter {
return;
}
try {
Files.createDirectories(outputFile.getParent());
} catch (IOException e) {
Flashback.LOGGER.error("Unable to create parent directories", e);
}
try {
FileOutputStream fos = new FileOutputStream(outputFile.toFile());
BufferedOutputStream bos = new BufferedOutputStream(fos);
@@ -7,11 +7,18 @@ import net.minecraft.network.chat.Component;
public class BottomTextWidget extends AbstractStringWidget {
public float horizontalAlignment = 0.5f;
public BottomTextWidget(int width, int height, Component component, Font font) {
super(0, 0, width, height, component, font);
this.active = false;
}
public BottomTextWidget alignLeft() {
this.horizontalAlignment = 0.0f;
return this;
}
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
Component component = this.getMessage();
@@ -19,7 +26,7 @@ public class BottomTextWidget extends AbstractStringWidget {
int width = this.getWidth();
int textWidth = font.width(component);
int x = this.getX() + Math.round((width - textWidth)/2.0f);
int x = this.getX() + Math.round((width - textWidth) * this.horizontalAlignment);
int y = this.getY() + this.getHeight() - this.getFont().lineHeight + 1;
guiGraphics.drawString(font, component.getVisualOrderText(), x, y, this.getColor());
@@ -1,11 +1,15 @@
package com.moulberry.flashback.screen;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.options.OptionsSubScreen;
import net.minecraft.network.chat.Component;
import java.nio.file.Path;
public class ConfigScreen extends OptionsSubScreen {
public ConfigScreen(Screen previous) {
@@ -14,11 +18,13 @@ public class ConfigScreen extends OptionsSubScreen {
protected void addOptions() {
if (this.list != null) {
this.list.addSmall(FlashbackConfig.createOptionInstances());
this.list.addSmall(Flashback.getConfig().createOptionInstances());
}
}
public void removed() {
Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback");
Flashback.getConfig().saveToFolder(configFolder);
}
}
@@ -0,0 +1,53 @@
package com.moulberry.flashback.screen;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
public class FlashbackButton extends Button {
public FlashbackButton(int x, int y, int width, int height, Component component, OnPress onPress) {
super(x, y, width, height, component, onPress, DEFAULT_NARRATION);
}
@Override
protected void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
super.renderWidget(guiGraphics, i, j, f);
final int size = 14;
int paddingX = (this.getWidth() - size) / 2;
int paddingY = (this.getHeight() - size) / 2;
int x = this.getX() + paddingX;
int y = this.getY() + paddingY;
double guiScale = Minecraft.getInstance().getWindow().getGuiScale();
int realSize = (int)(size * guiScale);
ResourceLocation icon;
if (realSize == 14) {
icon = ResourceLocation.parse("flashback:icon_14x.png");
} else if (realSize == 28) {
icon = ResourceLocation.parse("flashback:icon_28x.png");
} else if (realSize == 42) {
icon = ResourceLocation.parse("flashback:icon_42x.png");
} else if (realSize == 56) {
icon = ResourceLocation.parse("flashback:icon_56x.png");
} else {
icon = ResourceLocation.parse("flashback:icon.png");
}
guiGraphics.blit(icon, x, y, 0f, 0f, size, size, size, size);
}
@Override
public void renderString(GuiGraphics guiGraphics, Font font, int i) {
}
}
@@ -5,13 +5,16 @@ 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;
@@ -48,6 +51,8 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
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();
@@ -58,6 +63,8 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
private String filter;
private final LoadingHeader loadingHeader;
private Map<UUID, Long> 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;
@@ -125,8 +132,49 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
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<Map<UUID, Long>> typeToken = (TypeToken<Map<UUID, Long>>) 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<List<ReplaySummary>> loadReplays() {
Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback");
Path flashbackDir = Flashback.getDataDirectory();
Path replayDir = flashbackDir.resolve("replays");
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
@@ -148,14 +196,12 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastOpened = Math.max(basicFileAttributes.creationTime().toMillis(),
Math.max(basicFileAttributes.lastAccessTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis()));
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);
@@ -176,10 +222,10 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class);
FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson);
if (metadata != null) {
return new ReplaySummary(path, metadata, fileName, lastOpened, iconBytes);
return new ReplaySummary(path, metadata, fileName, lastModified, iconBytes);
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
Flashback.LOGGER.error("Failed to load replay", e);
}
return null;
}, Util.backgroundExecutor()));
@@ -300,7 +346,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
@Override
public Component getNarration() {
MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(),
Component.translationArg(new Date(this.summary.getLastPlayed())),
Component.translationArg(new Date(this.summary.getLastModified())),
this.summary.getInfo());
return Component.translatable("narrator.select", component);
}
@@ -309,7 +355,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) {
String title = this.summary.getReplayName();
String fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastPlayed();
long p = this.summary.getLastModified();
if (p != -1L) {
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
}
@@ -318,7 +364,14 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
}
Component info = this.summary.getInfo();
guiGraphics.drawString(this.minecraft.font, title, k + ICON_WIDTH + 3, j + 1, 0xFFFFFF, false);
int titleColour = 0xFFFFFF;
if (!this.summary.canOpen()) {
titleColour = 0xFF5555;
} else if (this.summary.hasWarning()) {
titleColour = 0xFFAA55;
}
guiGraphics.drawString(this.minecraft.font, title, k + ICON_WIDTH + 3, j + 1, titleColour, false);
guiGraphics.drawString(this.minecraft.font, fileAndTime, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
guiGraphics.drawString(this.minecraft.font, info, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
@@ -329,15 +382,21 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
if (this.minecraft.options.touchscreen().get() || bl) {
guiGraphics.fill(k, j, k + ICON_WIDTH, j + ICON_HEIGHT, -1601138544);
int q = n - k;
boolean bl2 = q < 32;
boolean hoveredIcon = q < 32;
if (!this.summary.canOpen()) {
ResourceLocation resourceLocation3 = bl2 ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE;
guiGraphics.blitSprite(resourceLocation3, k, j, ICON_WIDTH, ICON_HEIGHT);
} else {
ResourceLocation resourceLocation = bl2 ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
guiGraphics.blitSprite(resourceLocation, k, j, ICON_WIDTH, ICON_HEIGHT);
if (bl && this.summary.getHoverInfo() != null) {
guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), n, o);
}
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(iconOverlay, k, j, ICON_WIDTH, ICON_HEIGHT);
}
}
@@ -366,6 +425,9 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
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();
}
}
@@ -398,7 +460,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
public void editReplay() {
SystemToast.add(this.minecraft.getToasts(), new SystemToast.SystemToastId(3000),
Component.literal("Sorry"), Component.literal("Editing replay data hasn't been implemented yet"));
// todo:
// todo: implement editing replay data
// EditWorldScreen editWorldScreen;
// ReplayStorageSource.ReplayStorageAccess levelStorageAccess;
// this.queueLoadScreen();
@@ -3,28 +3,56 @@
*/
package com.moulberry.flashback.screen;
import com.moulberry.flashback.editor.ui.windows.TimelineWindow;
import com.moulberry.flashback.record.FlashbackMeta;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.util.FormattedCharSequence;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
import java.util.List;
public class ReplaySummary implements Comparable<ReplaySummary> {
private final Path path;
private final FlashbackMeta metadata;
private final String replayId;
private final long lastOpened;
private final long lastModified;
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 lastOpened, @Nullable byte[] iconBytes) {
public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, @Nullable byte[] iconBytes) {
this.path = path;
this.metadata = metadata;
this.replayId = replayId;
this.lastOpened = lastOpened;
this.lastModified = lastModified;
this.iconBytes = iconBytes;
if (metadata.protocolVersion != 0 && metadata.protocolVersion != SharedConstants.getProtocolVersion()) {
this.canOpen = false;
if (metadata.versionString != null && !metadata.versionString.equals(SharedConstants.VERSION_STRING)) {
this.hoverInfo = Component.literal("Unable to open replay\nReplay was created in " + metadata.versionString +
" and is incompatible with " + SharedConstants.VERSION_STRING);
} else {
this.hoverInfo = Component.literal("Unable to open replay\nReplay was created with protocol version " + metadata.protocolVersion +
" and is incompatible with " + SharedConstants.getProtocolVersion());
}
} else if (metadata.dataVersion != 0 && metadata.dataVersion != SharedConstants.getCurrentVersion().getDataVersion().getVersion()) {
this.hasWarning = true;
if (metadata.versionString != null && !metadata.versionString.equals(SharedConstants.VERSION_STRING)) {
this.hoverInfo = Component.literal("Important Warning\nReplay was created in " + metadata.versionString +
" and may fail to load in " + SharedConstants.VERSION_STRING);
} else {
this.hoverInfo = Component.literal("Important Warning\nReplay was created with data version " + metadata.dataVersion +
" and may fail to load with " + SharedConstants.getCurrentVersion().getDataVersion().getVersion());
}
}
}
public Path getPath() {
@@ -35,12 +63,16 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
return this.replayId;
}
public FlashbackMeta getReplayMetadata() {
return this.metadata;
}
public String getReplayName() {
return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name;
}
public long getLastPlayed() {
return this.lastOpened;
public long getLastModified() {
return this.lastModified;
}
public Component getInfo() {
@@ -68,6 +100,9 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
}
builder.append(seconds).append('s');
}
if (builder.isEmpty()) {
builder.append("0s");
}
mutable.append(Component.translatable("flashback.select_replay.duration", builder));
}
@@ -81,16 +116,24 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
return this.iconBytes;
}
public Component getHoverInfo() {
return this.hoverInfo;
}
public boolean hasWarning() {
return this.hasWarning;
}
public boolean canOpen() {
return true;
return this.canOpen;
}
@Override
public int compareTo(ReplaySummary levelSummary) {
if (this.getLastPlayed() < levelSummary.getLastPlayed()) {
if (this.getLastModified() < levelSummary.getLastModified()) {
return 1;
}
if (this.getLastPlayed() > levelSummary.getLastPlayed()) {
if (this.getLastModified() > levelSummary.getLastModified()) {
return -1;
}
return this.replayId.compareTo(levelSummary.replayId);
@@ -0,0 +1,164 @@
package com.moulberry.flashback.screen;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.record.ReplayExporter;
import net.minecraft.FileUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.StringWidget;
import net.minecraft.client.gui.layouts.FrameLayout;
import net.minecraft.client.gui.layouts.GridLayout;
import net.minecraft.client.gui.screens.AlertScreen;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.PauseScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class SaveReplayScreen extends Screen {
private Path recordFolder;
private String replayName;
private Path savePath = null;
private boolean generateFileFromReplayName = true;
private Button filePathButton;
private Screen previousScreen;
public SaveReplayScreen(Screen previousScreen, Path recordFolder, String replayName) {
super(Component.literal("Save Replay"));
this.recordFolder = recordFolder;
this.setReplayName(replayName);
if (this.savePath == null) {
this.savePath = Flashback.getReplayFolder().resolve(UUID.randomUUID() + ".zip");
}
if (!(previousScreen instanceof SaveReplayScreen)) {
this.previousScreen = previousScreen;
}
}
@Override
protected void init() {
super.init();
GridLayout gridLayout = new GridLayout();
gridLayout.defaultCellSetting().padding(4, 4, 4, 0);
GridLayout.RowHelper rowHelper = gridLayout.createRowHelper(2);
rowHelper.addChild(new StringWidget(204, 20, Component.literal("Save Replay"), this.font), 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Replay Name"), this.font).alignLeft(), 2);
EditBox replayNameEditBox = new EditBox(this.font, 0, 0, 204, 20, Component.literal(this.replayName));
replayNameEditBox.setValue(this.replayName);
replayNameEditBox.setResponder(this::setReplayName);
rowHelper.addChild(replayNameEditBox, 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Filename"), this.font).alignLeft(), 2);
this.filePathButton = Button.builder(Component.literal(this.savePath.getFileName().toString()), button -> {
CompletableFuture<String> future = AsyncFileDialogs.saveFileDialog(this.savePath.getParent().toString(), this.savePath.getFileName().toString(),
"Replay Archive", "zip");
future.thenAccept(pathStr -> {
if (pathStr != null) {
this.savePath = Path.of(pathStr);
this.generateFileFromReplayName = false;
}
});
}).width(204).build();
rowHelper.addChild(this.filePathButton, 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2);
rowHelper.addChild(Button.builder(Component.literal("Save Replay"), button -> {
this.saveReplay();
Minecraft.getInstance().setScreen(this.previousScreen);
}).width(98).build(), 1);
rowHelper.addChild(Button.builder(Component.literal("Delete Replay"), button -> {
Minecraft.getInstance().setScreen(new ConfirmScreen(value -> {
if (value) {
this.deleteReplay();
Minecraft.getInstance().setScreen(this.previousScreen);
} else {
Minecraft.getInstance().setScreen(SaveReplayScreen.this);
}
}, Component.literal("Confirm Delete Recording"),
Component.literal("Are you sure you want to delete the recording? You won't be able to recover it")));
}).width(98).build(), 1);
gridLayout.arrangeElements();
FrameLayout.alignInRectangle(gridLayout, 0, 0, this.width, this.height, 0.5f, 0.5f);
gridLayout.visitWidgets(this::addRenderableWidget);
}
@Override
public boolean shouldCloseOnEsc() {
return false;
}
@Override
public void tick() {
super.tick();
if (!Files.exists(this.recordFolder)) {
Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.previousScreen),
Component.literal("Error Saving Replay"), Component.literal("Recording folder seems to be missing. Did you delete it?")));
}
}
private void saveReplay() {
if (!Files.exists(this.recordFolder)) {
Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.previousScreen),
Component.literal("Error Saving Replay"), Component.literal("Recording folder seems to be missing. Did you delete it?")));
return;
}
ReplayExporter.export(this.recordFolder, this.savePath, this.replayName);
Flashback.removePendingReplaySave(this.recordFolder);
}
private void deleteReplay() {
try {
FileUtils.deleteDirectory(this.recordFolder.toFile());
} catch (Exception e) {
Flashback.LOGGER.error("Exception deleting record folder", e);
}
Flashback.removePendingReplaySave(this.recordFolder);
}
private void setReplayName(String replayName) {
this.replayName = replayName;
if (!this.replayName.isEmpty() && (this.savePath == null || this.generateFileFromReplayName)) {
Path replayDir = Flashback.getReplayFolder();
String filename;
try {
filename = FileUtil.findAvailableName(replayDir, this.replayName.replace(' ', '_'), ".zip");
} catch (IOException e) {
Flashback.LOGGER.error("Error while trying to determine filename", e);
filename = UUID.randomUUID() + ".zip";
}
this.savePath = replayDir.resolve(filename);
if (this.filePathButton != null) {
this.filePathButton.setMessage(Component.literal(this.savePath.getFileName().toString()));
}
}
}
}
@@ -4,15 +4,16 @@ import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
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;
public class SelectReplayScreen extends Screen {
protected final Screen lastScreen;
private Button deleteButton;
private Button selectButton;
private Button editButton;
private Button deleteButton;
protected EditBox searchBox;
private ReplaySelectionList list;
@@ -26,14 +27,16 @@ public class SelectReplayScreen extends Screen {
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.addWidget(this.searchBox);
this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft,
this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft,
this.width, this.height - 112, 48, 36, this.searchBox.getValue(), this.list));
this.selectButton = this.addRenderableWidget(Button.builder(Component.translatable("flashback.select_replay.open"), this::tryOpenReplay)
.bounds(this.width / 2 - 150, this.height - 52, 300, 20).build());
.bounds(this.width / 2 - 154, this.height - 52, 308, 20).build());
this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay)
.bounds(this.width / 2 - 150, this.height - 28, 146, 20).build());
.bounds(this.width / 2 - 154, this.height - 28, 150, 20).build());
this.deleteButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.delete"), this::tryDeleteReplay)
.bounds(this.width / 2 + 4, this.height - 28, 146, 20).build());
.bounds(this.width / 2 + 4, this.height - 28, 72, 20).build());
this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, button -> this.minecraft.setScreen(this.lastScreen))
.bounds(this.width / 2 + 82, this.height - 28, 72, 20).build());
this.updateButtonStatus(null);
}
@@ -267,7 +267,7 @@ public class CatmullRom {
if (t1 == t3) {
b2 = Interpolation.linear(a2, a3, 0.5f);
} else {
b2 =Interpolation.linear(a2, a3, (t - t1)/(t3 - t1));
b2 = Interpolation.linear(a2, a3, (t - t1)/(t3 - t1));
}
if (t1 == t2) {
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more