This commit is contained in:
Moulberry committed 2024-07-25 16:40:29 +08:00
1 parent 9c4a30d224
commit 666398e480
174 files changed
+8694 -2942

No files matched your search

@@ -0,0 +1,179 @@
package com.moulberry.flashback;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.network.protocol.game.ClientboundLightUpdatePacketData;
import net.minecraft.world.level.block.entity.BlockEntityType;
import java.util.Arrays;
import java.util.Objects;
public class CachedChunkPacket {
private final ClientboundLevelChunkWithLightPacket packet;
private boolean calculatedHashCode = false;
private int hashCode = 0;
public int index;
public CachedChunkPacket(ClientboundLevelChunkWithLightPacket packet, int index) {
this.packet = packet;
this.index = index;
}
@Override
public int hashCode() {
if (!this.calculatedHashCode) {
this.hashCode = this.calculateHashCode();
this.calculatedHashCode = true;
}
return this.hashCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CachedChunkPacket that)) return false;
if (this.hashCode() != that.hashCode()) {
return false;
}
ClientboundLevelChunkPacketData thisChunkData = this.packet.getChunkData();
ClientboundLightUpdatePacketData thisLightData = this.packet.getLightData();
ClientboundLevelChunkPacketData thatChunkData = that.packet.getChunkData();
ClientboundLightUpdatePacketData thatLightData = that.packet.getLightData();
if (this.packet.getX() != that.packet.getX()) {
return false;
}
if (this.packet.getZ() != that.packet.getZ()) {
return false;
}
if (!thisChunkData.getHeightmaps().equals(thatChunkData.getHeightmaps())) {
return false;
}
if (!thisLightData.getSkyYMask().equals(thatLightData.getSkyYMask())) {
return false;
}
if (!thisLightData.getBlockYMask().equals(thatLightData.getBlockYMask())) {
return false;
}
if (!thisLightData.getEmptySkyYMask().equals(thatLightData.getEmptySkyYMask())) {
return false;
}
if (!thisLightData.getEmptyBlockYMask().equals(thatLightData.getEmptyBlockYMask())) {
return false;
}
if (thisLightData.getSkyUpdates().size() != thatLightData.getSkyUpdates().size()) {
return false;
}
if (thisLightData.getBlockUpdates().size() != thatLightData.getBlockUpdates().size()) {
return false;
}
int skySize = thisLightData.getSkyUpdates().size();
for (int i = 0; i < skySize; i++) {
byte[] thisSkyLight = thisLightData.getSkyUpdates().get(i);
byte[] thatSkyLight = thatLightData.getSkyUpdates().get(i);
if (!Arrays.equals(thisSkyLight, thatSkyLight)) {
return false;
}
}
int blockSize = thisLightData.getBlockUpdates().size();
for (int i = 0; i < blockSize; i++) {
byte[] thisBlockLight = thisLightData.getBlockUpdates().get(i);
byte[] thatBlockLight = thatLightData.getBlockUpdates().get(i);
if (!Arrays.equals(thisBlockLight, thatBlockLight)) {
return false;
}
}
Long2ObjectOpenHashMap<CompoundTag> thisBlockEntityMap = new Long2ObjectOpenHashMap<>();
if (thisChunkData.blockEntitiesData.size() != thatChunkData.blockEntitiesData.size()) {
return false;
}
for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesDatum : thisChunkData.blockEntitiesData) {
long key = ((long)blockEntitiesDatum.y) << 32 | blockEntitiesDatum.packedXZ;
thisBlockEntityMap.put(key, blockEntitiesDatum.tag);
}
for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesDatum : thatChunkData.blockEntitiesData) {
long key = ((long)blockEntitiesDatum.y) << 32 | blockEntitiesDatum.packedXZ;
if (!thisBlockEntityMap.containsKey(key)) {
return false;
}
CompoundTag thisBlockEntity = thisBlockEntityMap.get(key);
if (!Objects.equals(thisBlockEntity, blockEntitiesDatum.tag)) {
return false;
}
}
return Arrays.equals(thisChunkData.buffer, thatChunkData.buffer);
}
private int calculateHashCode() {
ClientboundLevelChunkPacketData chunkData = this.packet.getChunkData();
ClientboundLightUpdatePacketData lightData = this.packet.getLightData();
int hashCode = 1;
hashCode = hashCode*31 + this.packet.getX();
hashCode = hashCode*31 + this.packet.getZ();
hashCode = hashCode*31 + chunkData.getHeightmaps().hashCode();
hashCode = hashCode*31 + lightData.getSkyYMask().hashCode();
hashCode = hashCode*31 + lightData.getBlockYMask().hashCode();
hashCode = hashCode*31 + lightData.getEmptySkyYMask().hashCode();
hashCode = hashCode*31 + lightData.getEmptyBlockYMask().hashCode();
for (byte[] skyUpdate : lightData.getSkyUpdates()) {
hashCode = hashCode*31 + fixedSizeHashForLightArray(skyUpdate);
}
for (byte[] blockUpdate : lightData.getBlockUpdates()) {
hashCode = hashCode*31 + fixedSizeHashForLightArray(blockUpdate);
}
for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesDatum : chunkData.blockEntitiesData) {
hashCode = hashCode*31 + blockEntitiesDatum.packedXZ;
hashCode = hashCode*31 + blockEntitiesDatum.y;
hashCode = hashCode*31 + BlockEntityType.getKey(blockEntitiesDatum.type).hashCode();
hashCode = hashCode*31 + (blockEntitiesDatum.tag == null ? 0 : blockEntitiesDatum.tag.hashCode());
}
hashCode = hashCode*31 + chunkData.getReadBuffer().hashCode();
return hashCode;
}
private static final int[] fixedSizeHashCoefficients = new int[2048];
static {
int coefficient = 1;
for (int i = fixedSizeHashCoefficients.length - 1; i >= 0; i--) {
fixedSizeHashCoefficients[i] = coefficient;
coefficient *= 31;
}
}
private static int fixedSizeHashForLightArray(byte[] array) {
if (array.length != 2048) {
throw new IllegalArgumentException("Array must be of length 2048");
}
int hash = 0;
for (int i = 0; i < array.length; i += 4) {
hash += fixedSizeHashCoefficients[i] * array[i] +
fixedSizeHashCoefficients[i+1] * array[i+1] +
fixedSizeHashCoefficients[i+2] * array[i+2] +
fixedSizeHashCoefficients[i+3] * array[i+3];
}
return hash;
}
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback;
import net.minecraft.client.DeltaTracker;
public class FixedDeltaTracker implements DeltaTracker {
private final float deltaTick;
private final float partialTick;
public FixedDeltaTracker(float deltaTick, float partialTick) {
this.deltaTick = deltaTick;
this.partialTick = partialTick;
}
public float getGameTimeDeltaTicks() {
return this.deltaTick;
}
public float getGameTimeDeltaPartialTick(boolean bl) {
return this.partialTick;
}
public float getRealtimeDeltaTicks() {
return this.deltaTick;
}
}
@@ -0,0 +1,260 @@
package com.moulberry.flashback;
import com.mojang.brigadier.context.CommandContext;
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.FinishedServerTick;
import com.moulberry.flashback.playback.EmptyLevelSource;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.record.Recorder;
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.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.player.AbstractClientPlayer;
import net.minecraft.commands.Commands;
import net.minecraft.core.*;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.*;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.*;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.WorldDimensions;
import net.minecraft.world.level.levelgen.WorldOptions;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class Flashback implements ModInitializer, ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("flashback");
public static final int MAGIC = 0xD780E884;
public static Recorder RECORDER = null;
public static ExportJob EXPORT_JOB = null;
private static Path configDirectory = null;
public static ResourceLocation createResourceLocation(String value) {
return ResourceLocation.fromNamespaceAndPath("flashback", value);
}
public static Path getConfigDirectory() {
if (configDirectory == null) {
configDirectory = FabricLoader.getInstance().getConfigDir().resolve("flashback");
try {
Files.createDirectories(configDirectory);
} catch (Exception e) {
LOGGER.error("Unable to create directories for config folder", e);
}
}
return configDirectory;
}
@Override
public void onInitialize() {
net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry.playS2C().register(FinishedServerTick.TYPE,
StreamCodec.unit(FinishedServerTick.INSTANCE));
}
@Override
public void onInitializeClient() {
// todo: try recover unfinished recordings
TempFolderProvider.tryDeleteStaleFolders();
try {
FileUtils.deleteDirectory(Path.of("replay_export_temp").toFile());
} catch (Exception ignored) {}
ActionRegistry.register(ActionNextTick.INSTANCE);
ActionRegistry.register(ActionGamePacket.INSTANCE);
ActionRegistry.register(ActionConfigurationPacket.INSTANCE);
ActionRegistry.register(ActionCreateLocalPlayer.INSTANCE);
ActionRegistry.register(ActionMoveEntities.INSTANCE);
ActionRegistry.register(ActionLevelChunkCached.INSTANCE);
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
var flashback = ClientCommandManager.literal("flashback");
flashback.then(ClientCommandManager.literal("start").executes(this::startRecordingReplay));
flashback.then(ClientCommandManager.literal("end").executes(this::finishRecordingReplay));
dispatcher.register(flashback);
});
}
@Nullable
public static ReplayServer getReplayServer() {
if (Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer replayServer) {
return replayServer;
}
return null;
}
public static boolean isInReplay() {
return Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer;
}
private int startRecordingReplay(CommandContext<FabricClientCommandSource> command) {
startRecordingReplay();
return 0;
}
private int finishRecordingReplay(CommandContext<FabricClientCommandSource> command) {
finishRecordingReplay();
return 0;
}
public static void startRecordingReplay() {
if (RECORDER != null) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Already Recording"), Component.literal("Cannot start new recording when already recording"));
return;
}
RECORDER = new Recorder(Minecraft.getInstance().player.registryAccess());
if (FlashbackConfig.showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Started Recording"), Component.literal("Started recording"));
}
}
public static void pauseRecordingReplay(boolean pause) {
RECORDER.setPaused(pause);
if (FlashbackConfig.showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Paused Recording"), Component.literal("Paused recording"));
}
}
public static void cancelRecordingReplay() {
Recorder recorder = RECORDER;
RECORDER = null;
recorder.finish(null);
if (FlashbackConfig.showRecordingToasts) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Cancelled Recording"), Component.literal("Cancelled recording"));
}
}
public static void finishRecordingReplay() {
if (RECORDER == null) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Not Recording"), Component.literal("Cannot finish recording when not recording"));
return;
}
Recorder recorder = RECORDER;
RECORDER = null;
recorder.endTick(true);
Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback");
Path replayDir = flashbackDir.resolve("replays");
try {
Files.createDirectories(replayDir);
} catch (IOException e) {
Flashback.LOGGER.error("Error while trying to create replay directory", e);
}
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) {
SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST,
Component.literal("Finished Recording"), Component.literal(name));
}
}
@Nullable
public static AbstractClientPlayer getSpectatingPlayer() {
if (!isInReplay()) {
return null;
}
if (Minecraft.getInstance().getCameraEntity() instanceof AbstractClientPlayer clientPlayer) {
if (clientPlayer != Minecraft.getInstance().player) {
return clientPlayer;
}
}
return null;
}
public static void openReplayWorld(Path path) {
try {
UUID replayUuid = UUID.randomUUID();
Path replayTemp = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.SERVER, replayUuid);
FileUtils.deleteDirectory(replayTemp.toFile());
LevelStorageSource source = new LevelStorageSource(replayTemp.resolve("saves"), replayTemp.resolve("backups"),
Minecraft.getInstance().directoryValidator(), Minecraft.getInstance().getFixerUpper());
LevelStorageSource.LevelStorageAccess access = source.createAccess("replay");
PackRepository packRepository = ServerPacksSource.createVanillaTrustedRepository();
packRepository.reload();
GameRules gameRules = new GameRules();
gameRules.getRule(GameRules.RULE_DOMOBSPAWNING).set(false, null);
gameRules.getRule(GameRules.RULE_WEATHER_CYCLE).set(false, null);
gameRules.getRule(GameRules.RULE_RANDOMTICKING).set(0, null);
WorldDataConfiguration worldDataConfiguration = new WorldDataConfiguration(new DataPackConfig(List.of(), List.of()), FeatureFlags.DEFAULT_FLAGS);
LevelSettings levelSettings = new LevelSettings("Replay", GameType.SPECTATOR, false, Difficulty.NORMAL, true, gameRules, worldDataConfiguration);
WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, worldDataConfiguration, false, true);
WorldLoader.InitConfig initConfig = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, 4);
WorldStem worldStem = Util.blockUntilDone(executor -> WorldLoader.load(initConfig, dataLoadContext -> {
Registry<LevelStem> registry = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
Holder.Reference<Biome> plains = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.BIOME).getHolder(Biomes.PLAINS).get();
Holder.Reference<DimensionType> overworld = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.DIMENSION_TYPE).getHolder(BuiltinDimensionTypes.OVERWORLD).get();
WorldDimensions worldDimensions = new WorldDimensions(Map.of(LevelStem.OVERWORLD, new LevelStem(overworld, new EmptyLevelSource(plains))));
WorldDimensions.Complete complete = worldDimensions.bake(registry);
return new WorldLoader.DataLoadOutput<>(new PrimaryLevelData(levelSettings, new WorldOptions(0L, false, false),
complete.specialWorldProperty(), complete.lifecycle()), complete.dimensionsRegistryAccess());
}, WorldStem::new, Util.backgroundExecutor(), executor)).get();
((MinecraftExt)Minecraft.getInstance()).flashback$startReplayServer(access, packRepository, worldStem, replayUuid, path);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,31 @@
package com.moulberry.flashback;
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.FOVKeyframe;
import com.moulberry.flashback.keyframe.impl.TickrateKeyframe;
import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe;
import com.moulberry.flashback.serialization.QuaternionTypeAdapater;
import com.moulberry.flashback.serialization.Vector3fTypeAdapater;
import org.joml.Quaternionf;
import org.joml.Vector3f;
public class FlashbackGson {
public static Gson PRETTY = build().setPrettyPrinting().create();
public static Gson COMPRESSED = build().create();
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());
}
}
@@ -0,0 +1,13 @@
package com.moulberry.flashback;
import com.moulberry.flashback.screen.ConfigScreen;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import com.terraformersmc.modmenu.api.ModMenuApi;
public class FlashbackModMenuApiImpl implements ModMenuApi {
@Override
public ConfigScreenFactory<?> getModConfigScreenFactory() {
return ConfigScreen::new;
}
}
@@ -0,0 +1,9 @@
package com.moulberry.flashback;
import net.minecraft.client.gui.components.toasts.SystemToast;
public class FlashbackSystemToasts {
public static final SystemToast.SystemToastId RECORDING_TOAST = new SystemToast.SystemToastId();
}
@@ -0,0 +1,19 @@
package com.moulberry.flashback;
import org.joml.Quaternionf;
public class Interpolation {
public static double linear(double from, double to, float amount) {
return from + (to - from) * amount;
}
public static float linear(float from, float to, float amount) {
return from + (to - from) * amount;
}
public static Quaternionf linear(Quaternionf from, Quaternionf to, float amount) {
return from.slerp(to, amount, new Quaternionf());
}
}
@@ -0,0 +1,17 @@
package com.moulberry.flashback;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.world.entity.Entity;
public class PacketHelper {
public static ClientboundAddEntityPacket createAddEntity(Entity entity) {
return createAddEntity(entity, 0);
}
public static ClientboundAddEntityPacket createAddEntity(Entity entity, int data) {
return new ClientboundAddEntityPacket(entity.getId(), entity.getUUID(), entity.getX(), entity.getY(), entity.getZ(),
entity.getXRot(), entity.getYRot(), entity.getType(), data, entity.getDeltaMovement(), entity.getYHeadRot());
}
}
@@ -0,0 +1,79 @@
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;
}
}
@@ -0,0 +1,10 @@
package com.moulberry.flashback;
public class SneakyThrow {
@SuppressWarnings("unchecked")
public static <E extends Throwable> RuntimeException sneakyThrow(Throwable e) throws E {
throw (E) e;
}
}
@@ -0,0 +1,152 @@
package com.moulberry.flashback;
import net.fabricmc.loader.api.FabricLoader;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class TempFolderProvider {
public enum TempFolderType {
SERVER("server"),
RECORDING("recording"),
PLAYBACK("playback");
private final String id;
TempFolderType(String id) {
this.id = id;
}
}
private static Path getSharedTempFolder() {
return FabricLoader.getInstance().getGameDir()
.resolve("flashback")
.resolve("temp");
}
public static void tryDeleteStaleFolders() {
Path tempFolder = getSharedTempFolder();
if (!Files.exists(tempFolder)) {
return;
}
for (TempFolderType type : TempFolderType.values()) {
// todo: special handling for recordings
Path typedTempFolder = tempFolder.resolve(type.id);
if (!Files.exists(typedTempFolder)) {
continue;
}
Set<Path> toDelete = new HashSet<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(typedTempFolder)) {
for (Path path : directoryStream) {
if (!Files.isDirectory(path)) {
continue;
}
Path lockFile = path.resolve("flashback_pid");
String pidStr = "?";
boolean isStillInUse = false;
try {
pidStr = Files.readString(lockFile);
long pid = Long.parseLong(pidStr);
isStillInUse = ProcessHandle.of(pid).isPresent();
} catch (Exception ignored) {}
if (!isStillInUse) {
toDelete.add(path);
} else {
Flashback.LOGGER.error("Cannot delete stale temp folder {}, pid {} is still in use", tempFolder.relativize(path), pidStr);
}
}
} catch (IOException e) {
Flashback.LOGGER.error("Failed to find stale temp folders to delete", e);
}
for (Path path : toDelete) {
Flashback.LOGGER.info("Deleting stale temp folder {}", tempFolder.relativize(path));
try {
FileUtils.deleteDirectory(path.toFile());
} catch (Exception e) {
Flashback.LOGGER.error("Failed to delete stale temp folder", e);
}
}
deleteDirectoryIfEmpty(typedTempFolder);
}
deleteDirectoryIfEmpty(tempFolder);
}
public static Path createTemp(TempFolderType type, UUID uuid) {
Path path = getTempPath(type, uuid);
if (!Files.exists(path)) {
// Create directories
try {
Files.createDirectories(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
// Write pid file
long pid = ProcessHandle.current().pid();
try {
Files.writeString(path.resolve("flashback_pid"), String.valueOf(pid));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return path;
}
private static Path getTempPath(TempFolderType type, UUID uuid) {
return getSharedTempFolder()
.resolve(type.id)
.resolve(uuid.toString());
}
public static void deleteTemp(TempFolderType type, UUID uuid) {
Path path = getTempPath(type, uuid);
// Delete directory
try {
FileUtils.deleteDirectory(path.toFile());
} catch (Exception e) {
throw new RuntimeException(e);
}
deleteDirectoryIfEmpty(path.getParent());
deleteDirectoryIfEmpty(path.getParent().getParent());
}
public static void deleteDirectoryIfEmpty(Path path) {
if (!Files.exists(path)) {
return;
}
try {
boolean empty;
try (var stream = Files.newDirectoryStream(path)) {
empty = !stream.iterator().hasNext();
}
if (empty) {
Files.deleteIfExists(path);
}
} catch (IOException ignored) {}
}
}
@@ -0,0 +1,60 @@
package com.moulberry.flashback;
import it.unimi.dsi.fastutil.objects.Object2FloatFunction;
import org.jetbrains.annotations.Nullable;
public class Utils {
/*
* I love Utils.java, very cool, thank you
*/
public enum ClosestElement {
LEFT,
RIGHT,
NONE
}
public static <T> T chooseClosest(float position, float leftPosition, T left, float rightPosition, T right, float threshold) {
if (left == null) {
if (Math.abs(rightPosition - position) <= threshold) {
return right;
} else {
return null;
}
}
if (right == null) {
if (Math.abs(leftPosition - position) <= threshold) {
return left;
} else {
return null;
}
}
return switch (findClosest(position, leftPosition, rightPosition, threshold)) {
case LEFT -> left;
case RIGHT -> right;
case NONE -> null;
};
}
public static Utils.ClosestElement findClosest(float position, float leftPosition, float rightPosition, float threshold) {
boolean leftValid = Math.abs(leftPosition - position) <= threshold;
boolean rightValid = Math.abs(rightPosition - position) <= threshold;
if (leftValid && rightValid) {
if (position <= leftPosition) {
return ClosestElement.LEFT;
} else {
return ClosestElement.RIGHT;
}
} else if (leftValid) {
return ClosestElement.LEFT;
} else if (rightValid) {
return ClosestElement.RIGHT;
} else {
return ClosestElement.NONE;
}
}
}
@@ -0,0 +1,12 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public interface Action {
ResourceLocation name();
void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf);
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ActionConfigurationPacket implements Action {
private static final ResourceLocation NAME = Flashback.createResourceLocation("action/configuration_packet");
public static final ActionConfigurationPacket INSTANCE = new ActionConfigurationPacket();
private ActionConfigurationPacket() {
}
@Override
public ResourceLocation name() {
return NAME;
}
@Override
public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) {
replayServer.handleConfigurationPacket(friendlyByteBuf);
}
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ActionCreateLocalPlayer implements Action {
private static final ResourceLocation NAME = Flashback.createResourceLocation("action/create_local_player");
public static final ActionCreateLocalPlayer INSTANCE = new ActionCreateLocalPlayer();
private ActionCreateLocalPlayer() {
}
@Override
public ResourceLocation name() {
return NAME;
}
@Override
public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) {
replayServer.handleCreateLocalPlayer(friendlyByteBuf);
}
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ActionGamePacket implements Action {
private static final ResourceLocation NAME = Flashback.createResourceLocation("action/game_packet");
public static final ActionGamePacket INSTANCE = new ActionGamePacket();
private ActionGamePacket() {
}
@Override
public ResourceLocation name() {
return NAME;
}
@Override
public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) {
replayServer.handleGamePacket(friendlyByteBuf);
}
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ActionLevelChunkCached implements Action {
private static final ResourceLocation NAME = Flashback.createResourceLocation("action/level_chunk_cached");
public static final ActionLevelChunkCached INSTANCE = new ActionLevelChunkCached();
private ActionLevelChunkCached() {
}
@Override
public ResourceLocation name() {
return NAME;
}
@Override
public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) {
replayServer.handleLevelChunkCached(friendlyByteBuf.readVarInt());
}
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ActionMoveEntities implements Action {
private static final ResourceLocation NAME = Flashback.createResourceLocation("action/move_entities");
public static final ActionMoveEntities INSTANCE = new ActionMoveEntities();
private ActionMoveEntities() {
}
@Override
public ResourceLocation name() {
return NAME;
}
@Override
public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) {
replayServer.handleMoveEntities(friendlyByteBuf);
}
}
@@ -0,0 +1,25 @@
package com.moulberry.flashback.action;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ActionNextTick implements Action {
private static final ResourceLocation NAME = Flashback.createResourceLocation("action/next_tick");
public static final ActionNextTick INSTANCE = new ActionNextTick();
private ActionNextTick() {
}
@Override
public ResourceLocation name() {
return NAME;
}
@Override
public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) {
replayServer.handleNextTick();
}
}
@@ -0,0 +1,40 @@
package com.moulberry.flashback.action;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ActionRegistry {
private static final List<Action> actions = new ArrayList<>();
private static final Map<ResourceLocation, Action> resourceToAction = new HashMap<>();
private static final Set<Class<? extends Action>> registeredActions = new HashSet<>();
public static void register(Action action) {
if (!registeredActions.add(action.getClass())) {
throw new IllegalArgumentException("Action already registered: " + action.getClass());
}
if (resourceToAction.containsKey(action.name())) {
throw new IllegalArgumentException("Action already registered by name: " + action.name());
}
actions.add(action);
resourceToAction.put(action.name(), action);
}
public static List<Action> getActions() {
return Collections.unmodifiableList(actions);
}
public static @Nullable Action getAction(ResourceLocation actionName) {
return resourceToAction.get(actionName);
}
}
@@ -0,0 +1,28 @@
package com.moulberry.flashback.combo_options;
public enum AspectRatio implements ComboOption {
ASPECT_16_9("16:9 (HDTV)", 16/9f),
ASPECT_9_16("9:16 (Shorts)", 9/16f),
ASPECT_240_1("2.40:1 (Widescreen)", 2.4f),
ASPECT_1_1("1:1 (Square)", 1f),
ASPECT_4_3("4:3 (Fullscreen)", 4/3f),
ASPECT_3_2("3:2 (Photo)", 3/2f);
private final String text;
private final float aspectRatio;
AspectRatio(String text, float aspectRatio) {
this.text = text;
this.aspectRatio = aspectRatio;
}
@Override
public String text() {
return this.text;
}
public float aspectRatio() {
return aspectRatio;
}
}
@@ -0,0 +1,7 @@
package com.moulberry.flashback.combo_options;
public interface ComboOption {
String text();
}
@@ -0,0 +1,21 @@
package com.moulberry.flashback.combo_options;
public enum Sizing implements ComboOption {
KEEP_ASPECT_RATIO("Keep Aspect Ratio"),
FILL("Fill"),
UNDERLAY("Underlay"),
CHANGE_ASPECT_RATIO("Change Aspect Ratio");
private final String text;
Sizing(String text) {
this.text = text;
}
@Override
public String text() {
return this.text;
}
}
@@ -0,0 +1,93 @@
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 org.bytedeco.ffmpeg.avcodec.AVCodec;
import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig;
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.*;
public enum VideoCodec implements ComboOption {
H264("H264 (AVC)", avcodec.AV_CODEC_ID_H264),
H265("H265 (HEVC)", avcodec.AV_CODEC_ID_H265),
AV1("AV1", avcodec.AV_CODEC_ID_AV1),
VP9("VP9", avcodec.AV_CODEC_ID_VP9),
PRO_RES("Apple ProRes", avcodec.AV_CODEC_ID_PRORES),
QUICK_TIME("QuickTime", avcodec.AV_CODEC_ID_QTRLE);
private final String text;
private final int codecId;
private String[] encoders;
VideoCodec(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 || name.equals("libaom-av1")) {
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;
}
}
}
@@ -0,0 +1,59 @@
package com.moulberry.flashback.combo_options;
import org.bytedeco.ffmpeg.avformat.AVOutputFormat;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avformat;
import java.util.ArrayList;
import java.util.List;
public enum VideoContainer implements ComboOption {
MP4("MP4", "mp4"),
MKV("MKV", "mkv"),
AVI("AVI", "avi"),
MOV("MOV", "mov");
private final String text;
private final String extension;
private VideoCodec[] supportedCodecs = null;
VideoContainer(String text, String extension) {
this.text = text;
this.extension = extension;
}
@Override
public String text() {
return this.text;
}
public String extension() {
return extension;
}
public VideoCodec[] getSupportedCodecs() {
if (this.supportedCodecs == null) {
List<VideoCodec> supportedCodecs = new ArrayList<>();
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (VideoCodec codec : VideoCodec.values()) {
if (codec == VideoCodec.AV1 && this != VideoContainer.MP4) {
continue;
}
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.supportedCodecs = supportedCodecs.toArray(new VideoCodec[0]);
}
return this.supportedCodecs;
}
}
@@ -0,0 +1,31 @@
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,73 @@
package com.moulberry.flashback.configuration;
import com.moulberry.flashback.Flashback;
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 java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
public class FlashbackConfig {
@OptionCaption("flashback.option.automatically_start")
@OptionDescription("flashback.option.automatically_start.description")
public static boolean automaticallyStart = false;
@OptionCaption("flashback.option.automatically_finish")
@OptionDescription("flashback.option.automatically_finish.description")
public static boolean automaticallyFinish = true;
@OptionCaption("flashback.option.show_recording_toasts")
@OptionDescription("flashback.option.show_recording_toasts.description")
public static boolean showRecordingToasts = true;
@SuppressWarnings("unchecked")
public static OptionInstance<?>[] createOptionInstances() {
List<OptionInstance<?>> options = new ArrayList<>();
for (Field field : FlashbackConfig.class.getDeclaredFields()) {
try {
// Ignore non-static fields
if ((field.getModifiers() & Modifier.STATIC) == 0) {
continue;
}
OptionCaption caption = field.getDeclaredAnnotation(OptionCaption.class);
if (caption == null) {
continue;
}
OptionInstance.TooltipSupplier tooltipSupplier = OptionInstance.noTooltip();
OptionDescription description = field.getDeclaredAnnotation(OptionDescription.class);
if (description != null) {
MutableComponent root = Component.empty();
root.append(Component.translatable(caption.value()).withStyle(ChatFormatting.YELLOW));
root.append(Component.literal("\n"));
root.append(Component.translatable(description.value()));
tooltipSupplier = OptionInstance.cachedConstantTooltip(root);
}
if (field.getType() == boolean.class) {
options.add(OptionInstance.createBoolean(caption.value(), tooltipSupplier, field.getBoolean(null), value -> {
try {
field.set(null, value);
} catch (Exception e) {
throw SneakyThrow.sneakyThrow(e);
}
}));
}
} catch (Exception e) {
Flashback.LOGGER.error("Error while trying to convert config field to OptionInstance", e);
}
}
return options.toArray(new OptionInstance[0]);
}
}
@@ -0,0 +1,14 @@
package com.moulberry.flashback.configuration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface OptionCaption {
String value();
}
@@ -0,0 +1,14 @@
package com.moulberry.flashback.configuration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface OptionDescription {
String value();
}
@@ -0,0 +1,55 @@
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.KeyframeTrack;
import java.util.Map;
import java.util.TreeMap;
public record SavedTrack(KeyframeType type, int track, boolean copiedFromDisabled,
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);
}
}
// 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);
}
}
// 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;
}
public int applyTo(KeyframeTrack keyframeTrack, int cursorTicks, int totalTicks) {
int count = 0;
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());
count += 1;
}
}
return count;
}
}
@@ -0,0 +1,22 @@
package com.moulberry.flashback.editor;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.KeyframeTrack;
import it.unimi.dsi.fastutil.ints.IntSet;
public record SelectedKeyframes(KeyframeType type, int trackIndex, IntSet keyframeTicks) {
public boolean checkValid(EditorState state) {
if (this.trackIndex < 0 || this.trackIndex >= state.keyframeTracks.size()) {
return false;
}
KeyframeTrack keyframeTrack = state.keyframeTracks.get(this.trackIndex);
if (keyframeTrack.keyframeType != this.type) {
return false;
}
this.keyframeTicks.removeIf(tick -> !keyframeTrack.keyframesByTick.containsKey(tick));
return !this.keyframeTicks.isEmpty();
}
}
@@ -0,0 +1,592 @@
package com.moulberry.flashback.editor.ui;
import imgui.ImDrawData;
import imgui.ImFontAtlas;
import imgui.ImGui;
import imgui.ImGuiIO;
import imgui.ImGuiViewport;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.callback.ImPlatformFuncViewport;
import imgui.flag.ImGuiBackendFlags;
import imgui.flag.ImGuiConfigFlags;
import imgui.flag.ImGuiViewportFlags;
import imgui.type.ImInt;
import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.lwjgl.opengl.GL32.*;
/**
* This class is a straightforward port of the
* <a href="https://raw.githubusercontent.com/ocornut/imgui/256594575d95d56dda616c544c509740e74906b4/backends/imgui_impl_opengl3.cpp">imgui_impl_opengl3.cpp</a>.
* <p>
* It do support a backup and restoring of the GL state in the same way the original Dear ImGui code does.
* Some of the very specific OpenGL variables may be ignored here,
* yet you can copy-paste this class in your codebase and modify the rendering routine in the way you'd like.
* <p>
* This implementation has an ability to use a GLSL version provided during the initialization.
* Please read the documentation for the {@link #init(String)}.
*/
@SuppressWarnings("MagicNumber")
public final class CustomImGuiImplGl3 {
// OpenGL Data
private int glVersion = 0;
private String glslVersion = "";
private int gFontTexture = -1;
private int gShaderHandle = 0;
private int gVertHandle = 0;
private int gFragHandle = 0;
private int gAttribLocationTex = 0;
private int gAttribLocationProjMtx = 0;
private int gAttribLocationVtxPos = 0;
private int gAttribLocationVtxUV = 0;
private int gAttribLocationVtxColor = 0;
private int gVboHandle = 0;
private int gElementsHandle = 0;
private int gVertexArrayObjectHandle = 0;
// Used to store tmp renderer data
private final ImVec2 displaySize = new ImVec2();
private final ImVec2 framebufferScale = new ImVec2();
private final ImVec2 displayPos = new ImVec2();
private final ImVec4 clipRect = new ImVec4();
private final float[] orthoProjMatrix = new float[4 * 4];
// Variables used to backup GL state before and after the rendering of Dear ImGui
private final int[] lastActiveTexture = new int[1];
private final int[] lastProgram = new int[1];
private final int[] lastTexture = new int[1];
private final int[] lastArrayBuffer = new int[1];
private final int[] lastVertexArrayObject = new int[1];
private final int[] lastFramebuffer = new int[1];
private final int[] lastViewport = new int[4];
private final int[] lastScissorBox = new int[4];
private final int[] lastBlendSrcRgb = new int[1];
private final int[] lastBlendDstRgb = new int[1];
private final int[] lastBlendSrcAlpha = new int[1];
private final int[] lastBlendDstAlpha = new int[1];
private final int[] lastBlendEquationRgb = new int[1];
private final int[] lastBlendEquationAlpha = new int[1];
private boolean lastEnableBlend = false;
private boolean lastEnableCullFace = false;
private boolean lastEnableDepthTest = false;
private boolean lastEnableStencilTest = false;
private boolean lastEnableScissorTest = false;
/**
* Method to do an initialization of the {@link CustomImGuiImplGl3} state.
* It SHOULD be called before calling of the {@link CustomImGuiImplGl3#renderDrawData(ImDrawData)} method.
* <p>
* Unlike in the {@link #init(String)} method, here the glslVersion argument is omitted.
* Thus a "#version 130" string will be used instead.
*/
public void init() {
this.init(null);
}
/**
* Method to do an initialization of the {@link CustomImGuiImplGl3} state.
* It SHOULD be called before calling of the {@link CustomImGuiImplGl3#renderDrawData(ImDrawData)} method.
* <p>
* Method takes an argument, which should be a valid GLSL string with the version to use.
* <pre>
* ----------------------------------------
* OpenGL GLSL GLSL
* version version string
* ---------------------------------------
* 2.0 110 "#version 110"
* 2.1 120 "#version 120"
* 3.0 130 "#version 130"
* 3.1 140 "#version 140"
* 3.2 150 "#version 150"
* 3.3 330 "#version 330 core"
* 4.0 400 "#version 400 core"
* 4.1 410 "#version 410 core"
* 4.2 420 "#version 410 core"
* 4.3 430 "#version 430 core"
* ES 3.0 300 "#version 300 es" = WebGL 2.0
* ---------------------------------------
* </pre>
* <p>
* If the argument is null, then a "#version 130" string will be used by default.
*
* @param glslVersion string with the version of the GLSL
*/
public void init(final String glslVersion) {
this.readGlVersion();
this.setupBackendCapabilitiesFlags();
if (glslVersion == null) {
this.glslVersion = "#version 130";
} else {
this.glslVersion = glslVersion;
}
this.createDeviceObjects();
if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {
this.initPlatformInterface();
}
}
/**
* Method to render {@link ImDrawData} into current OpenGL context.
*
* @param drawData draw data to render
*/
public void renderDrawData(final ImDrawData drawData) {
if (drawData.getCmdListsCount() <= 0) {
return;
}
// Will project scissor/clipping rectangles into framebuffer space
drawData.getDisplaySize(this.displaySize); // (0,0) unless using multi-viewports
drawData.getDisplayPos(this.displayPos);
drawData.getFramebufferScale(this.framebufferScale); // (1,1) unless using retina display which are often (2,2)
final float clipOffX = this.displayPos.x;
final float clipOffY = this.displayPos.y;
final float clipScaleX = this.framebufferScale.x;
final float clipScaleY = this.framebufferScale.y;
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
final int fbWidth = (int) (this.displaySize.x * this.framebufferScale.x);
final int fbHeight = (int) (this.displaySize.y * this.framebufferScale.y);
if (fbWidth <= 0 || fbHeight <= 0) {
return;
}
this.backupGlState();
this.bind(fbWidth, fbHeight);
// Render command lists
for (int cmdListIdx = 0; cmdListIdx < drawData.getCmdListsCount(); cmdListIdx++) {
// Upload vertex/index buffers
glBufferData(GL_ARRAY_BUFFER, drawData.getCmdListVtxBufferData(cmdListIdx), GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, drawData.getCmdListIdxBufferData(cmdListIdx), GL_STREAM_DRAW);
for (int cmdBufferIdx = 0; cmdBufferIdx < drawData.getCmdListCmdBufferSize(cmdListIdx); cmdBufferIdx++) {
drawData.getCmdListCmdBufferClipRect(cmdListIdx, cmdBufferIdx, this.clipRect);
final float clipMinX = (this.clipRect.x - clipOffX) * clipScaleX;
final float clipMinY = (this.clipRect.y - clipOffY) * clipScaleY;
final float clipMaxX = (this.clipRect.z - clipOffX) * clipScaleX;
final float clipMaxY = (this.clipRect.w - clipOffY) * clipScaleY;
if (clipMaxX <= clipMinX || clipMaxY <= clipMinY) {
continue;
}
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
glScissor((int) clipMinX, (int) (fbHeight - clipMaxY), (int) (clipMaxX - clipMinX), (int) (clipMaxY - clipMinY));
// Bind texture, Draw
final int textureId = drawData.getCmdListCmdBufferTextureId(cmdListIdx, cmdBufferIdx);
final int elemCount = drawData.getCmdListCmdBufferElemCount(cmdListIdx, cmdBufferIdx);
final int idxBufferOffset = drawData.getCmdListCmdBufferIdxOffset(cmdListIdx, cmdBufferIdx);
final int vtxBufferOffset = drawData.getCmdListCmdBufferVtxOffset(cmdListIdx, cmdBufferIdx);
final int indices = idxBufferOffset * ImDrawData.SIZEOF_IM_DRAW_IDX;
glBindTexture(GL_TEXTURE_2D, textureId);
if (this.glVersion >= 320) {
glDrawElementsBaseVertex(GL_TRIANGLES, elemCount, GL_UNSIGNED_SHORT, indices, vtxBufferOffset);
} else {
glDrawElements(GL_TRIANGLES, elemCount, GL_UNSIGNED_SHORT, indices);
}
}
}
this.unbind();
this.restoreModifiedGlState();
}
/**
* Call this method in the end of your application cycle to dispose resources used by {@link CustomImGuiImplGl3}.
*/
public void dispose() {
glDeleteBuffers(this.gVboHandle);
glDeleteBuffers(this.gElementsHandle);
glDetachShader(this.gShaderHandle, this.gVertHandle);
glDetachShader(this.gShaderHandle, this.gFragHandle);
glDeleteProgram(this.gShaderHandle);
glDeleteTextures(this.gFontTexture);
this.shutdownPlatformInterface();
}
/**
* Method rebuilds the font atlas for Dear ImGui. Could be used to update application fonts in runtime.
*/
public void updateFontsTexture() {
if (this.gFontTexture != -1) glDeleteTextures(this.gFontTexture);
final ImFontAtlas fontAtlas = ImGui.getIO().getFonts();
final ImInt width = new ImInt();
final ImInt height = new ImInt();
final ByteBuffer buffer = fontAtlas.getTexDataAsRGBA32(width, height);
this.gFontTexture = glGenTextures();
glBindTexture(GL_TEXTURE_2D, this.gFontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width.get(), height.get(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
fontAtlas.setTexID(this.gFontTexture);
}
private void readGlVersion() {
final int[] major = new int[1];
final int[] minor = new int[1];
glGetIntegerv(GL_MAJOR_VERSION, major);
glGetIntegerv(GL_MINOR_VERSION, minor);
this.glVersion = major[0] * 100 + minor[0] * 10;
}
private void setupBackendCapabilitiesFlags() {
final ImGuiIO io = ImGui.getIO();
io.setBackendRendererName("imgui_java_impl_opengl3");
// We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
if (this.glVersion >= 320) {
io.addBackendFlags(ImGuiBackendFlags.RendererHasVtxOffset);
}
// We can create multi-viewports on the Renderer side (optional)
io.addBackendFlags(ImGuiBackendFlags.RendererHasViewports);
}
private void createDeviceObjects() {
// Backup GL state
final int[] lastTexture = new int[1];
final int[] lastArrayBuffer = new int[1];
final int[] lastVertexArray = new int[1];
glGetIntegerv(GL_TEXTURE_BINDING_2D, lastTexture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, lastArrayBuffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, lastVertexArray);
this.createShaders();
this.gAttribLocationTex = glGetUniformLocation(this.gShaderHandle, "Texture");
this.gAttribLocationProjMtx = glGetUniformLocation(this.gShaderHandle, "ProjMtx");
this.gAttribLocationVtxPos = glGetAttribLocation(this.gShaderHandle, "Position");
this.gAttribLocationVtxUV = glGetAttribLocation(this.gShaderHandle, "UV");
this.gAttribLocationVtxColor = glGetAttribLocation(this.gShaderHandle, "Color");
// Create buffers
this.gVboHandle = glGenBuffers();
this.gElementsHandle = glGenBuffers();
this.updateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, lastTexture[0]);
glBindBuffer(GL_ARRAY_BUFFER, lastArrayBuffer[0]);
glBindVertexArray(lastVertexArray[0]);
}
private void createShaders() {
final int glslVersionValue = this.parseGlslVersionString();
// Select shaders matching our GLSL versions
final CharSequence vertShaderSource;
final CharSequence fragShaderSource;
if (glslVersionValue < 130) {
vertShaderSource = this.getVertexShaderGlsl120();
fragShaderSource = this.getFragmentShaderGlsl120();
} else if (glslVersionValue == 300) {
vertShaderSource = this.getVertexShaderGlsl300es();
fragShaderSource = this.getFragmentShaderGlsl300es();
} else if (glslVersionValue >= 410) {
vertShaderSource = this.getVertexShaderGlsl410Core();
fragShaderSource = this.getFragmentShaderGlsl410Core();
} else {
vertShaderSource = this.getVertexShaderGlsl130();
fragShaderSource = this.getFragmentShaderGlsl130();
}
this.gVertHandle = this.createAndCompileShader(GL_VERTEX_SHADER, vertShaderSource);
this.gFragHandle = this.createAndCompileShader(GL_FRAGMENT_SHADER, fragShaderSource);
this.gShaderHandle = glCreateProgram();
glAttachShader(this.gShaderHandle, this.gVertHandle);
glAttachShader(this.gShaderHandle, this.gFragHandle);
glLinkProgram(this.gShaderHandle);
if (glGetProgrami(this.gShaderHandle, GL_LINK_STATUS) == GL_FALSE) {
throw new IllegalStateException("Failed to link shader program:\n" + glGetProgramInfoLog(this.gShaderHandle));
}
}
private int parseGlslVersionString() {
final Pattern p = Pattern.compile("\\d+");
final Matcher m = p.matcher(this.glslVersion);
if (m.find()) {
return Integer.parseInt(m.group());
} else {
throw new IllegalArgumentException("Invalid GLSL version string: " + this.glslVersion);
}
}
private void backupGlState() {
glGetIntegerv(GL_ACTIVE_TEXTURE, this.lastActiveTexture);
glActiveTexture(GL_TEXTURE0);
glGetIntegerv(GL_CURRENT_PROGRAM, this.lastProgram);
glGetIntegerv(GL_TEXTURE_BINDING_2D, this.lastTexture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, this.lastArrayBuffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, this.lastVertexArrayObject);
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, this.lastFramebuffer);
glGetIntegerv(GL_VIEWPORT, this.lastViewport);
glGetIntegerv(GL_SCISSOR_BOX, this.lastScissorBox);
glGetIntegerv(GL_BLEND_SRC_RGB, this.lastBlendSrcRgb);
glGetIntegerv(GL_BLEND_DST_RGB, this.lastBlendDstRgb);
glGetIntegerv(GL_BLEND_SRC_ALPHA, this.lastBlendSrcAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, this.lastBlendDstAlpha);
glGetIntegerv(GL_BLEND_EQUATION_RGB, this.lastBlendEquationRgb);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, this.lastBlendEquationAlpha);
this.lastEnableBlend = glIsEnabled(GL_BLEND);
this.lastEnableCullFace = glIsEnabled(GL_CULL_FACE);
this.lastEnableDepthTest = glIsEnabled(GL_DEPTH_TEST);
this.lastEnableStencilTest = glIsEnabled(GL_STENCIL_TEST);
this.lastEnableScissorTest = glIsEnabled(GL_SCISSOR_TEST);
}
private void restoreModifiedGlState() {
glUseProgram(this.lastProgram[0]);
glBindTexture(GL_TEXTURE_2D, this.lastTexture[0]);
glActiveTexture(this.lastActiveTexture[0]);
glBindVertexArray(this.lastVertexArrayObject[0]);
glBindFramebuffer(GL_FRAMEBUFFER, this.lastFramebuffer[0]);
glBindBuffer(GL_ARRAY_BUFFER, this.lastArrayBuffer[0]);
glBlendEquationSeparate(this.lastBlendEquationRgb[0], this.lastBlendEquationAlpha[0]);
glBlendFuncSeparate(this.lastBlendSrcRgb[0], this.lastBlendDstRgb[0], this.lastBlendSrcAlpha[0], this.lastBlendDstAlpha[0]);
// @formatter:off CHECKSTYLE:OFF
if (this.lastEnableBlend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (this.lastEnableCullFace) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (this.lastEnableDepthTest) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (this.lastEnableStencilTest) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
if (this.lastEnableScissorTest) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
// @formatter:on CHECKSTYLE:ON
glViewport(this.lastViewport[0], this.lastViewport[1], this.lastViewport[2], this.lastViewport[3]);
glScissor(this.lastScissorBox[0], this.lastScissorBox[1], this.lastScissorBox[2], this.lastScissorBox[3]);
}
// Setup desired GL state
private void bind(final int fbWidth, final int fbHeight) {
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
this.gVertexArrayObjectHandle = glGenVertexArrays();
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glEnable(GL_SCISSOR_TEST);
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
// DisplayPos is (0,0) for single viewport apps.
glViewport(0, 0, fbWidth, fbHeight);
final float left = this.displayPos.x;
final float right = this.displayPos.x + this.displaySize.x;
final float top = this.displayPos.y;
final float bottom = this.displayPos.y + this.displaySize.y;
// Orthographic matrix projection
this.orthoProjMatrix[0] = 2.0f / (right - left);
this.orthoProjMatrix[5] = 2.0f / (top - bottom);
this.orthoProjMatrix[10] = -1.0f;
this.orthoProjMatrix[12] = (right + left) / (left - right);
this.orthoProjMatrix[13] = (top + bottom) / (bottom - top);
this.orthoProjMatrix[15] = 1.0f;
// Bind shader
glUseProgram(this.gShaderHandle);
glUniform1i(this.gAttribLocationTex, 0);
glUniformMatrix4fv(this.gAttribLocationProjMtx, false, this.orthoProjMatrix);
glBindVertexArray(this.gVertexArrayObjectHandle);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Bind vertex/index buffers and setup attributes for ImDrawVert
glBindBuffer(GL_ARRAY_BUFFER, this.gVboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this.gElementsHandle);
glEnableVertexAttribArray(this.gAttribLocationVtxPos);
glEnableVertexAttribArray(this.gAttribLocationVtxUV);
glEnableVertexAttribArray(this.gAttribLocationVtxColor);
glVertexAttribPointer(this.gAttribLocationVtxPos, 2, GL_FLOAT, false, ImDrawData.SIZEOF_IM_DRAW_VERT, 0);
glVertexAttribPointer(this.gAttribLocationVtxUV, 2, GL_FLOAT, false, ImDrawData.SIZEOF_IM_DRAW_VERT, 8);
glVertexAttribPointer(this.gAttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, true, ImDrawData.SIZEOF_IM_DRAW_VERT, 16);
}
private void unbind() {
// Destroy the temporary VAO
glDeleteVertexArrays(this.gVertexArrayObjectHandle);
}
//--------------------------------------------------------------------------------------------------------
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
// This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
//--------------------------------------------------------------------------------------------------------
private void initPlatformInterface() {
ImGui.getPlatformIO().setRendererRenderWindow(new ImPlatformFuncViewport() {
@Override
public void accept(final ImGuiViewport vp) {
if (!vp.hasFlags(ImGuiViewportFlags.NoRendererClear)) {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
}
CustomImGuiImplGl3.this.renderDrawData(vp.getDrawData());
}
});
}
private void shutdownPlatformInterface() {
ImGui.destroyPlatformWindows();
}
private int createAndCompileShader(final int type, final CharSequence source) {
final int id = glCreateShader(type);
glShaderSource(id, source);
glCompileShader(id);
if (glGetShaderi(id, GL_COMPILE_STATUS) == GL_FALSE) {
throw new IllegalStateException("Failed to compile shader:\n" + glGetShaderInfoLog(id));
}
return id;
}
private String getVertexShaderGlsl120() {
return this.glslVersion + "\n"
+ "uniform mat4 ProjMtx;\n"
+ "attribute vec2 Position;\n"
+ "attribute vec2 UV;\n"
+ "attribute vec4 Color;\n"
+ "varying vec2 Frag_UV;\n"
+ "varying vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getVertexShaderGlsl130() {
return this.glslVersion + "\n"
+ "uniform mat4 ProjMtx;\n"
+ "in vec2 Position;\n"
+ "in vec2 UV;\n"
+ "in vec4 Color;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getVertexShaderGlsl300es() {
return this.glslVersion + "\n"
+ "precision highp float;\n"
+ "layout (location = 0) in vec2 Position;\n"
+ "layout (location = 1) in vec2 UV;\n"
+ "layout (location = 2) in vec4 Color;\n"
+ "uniform mat4 ProjMtx;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getVertexShaderGlsl410Core() {
return this.glslVersion + "\n"
+ "layout (location = 0) in vec2 Position;\n"
+ "layout (location = 1) in vec2 UV;\n"
+ "layout (location = 2) in vec4 Color;\n"
+ "uniform mat4 ProjMtx;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getFragmentShaderGlsl120() {
return this.glslVersion + "\n"
+ "#ifdef GL_ES\n"
+ " precision mediump float;\n"
+ "#endif\n"
+ "uniform sampler2D Texture;\n"
+ "varying vec2 Frag_UV;\n"
+ "varying vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
+ "}\n";
}
private String getFragmentShaderGlsl130() {
return this.glslVersion + "\n"
+ "uniform sampler2D Texture;\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "out vec4 Out_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
}
private String getFragmentShaderGlsl300es() {
return this.glslVersion + "\n"
+ "precision mediump float;\n"
+ "uniform sampler2D Texture;\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "layout (location = 0) out vec4 Out_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
}
private String getFragmentShaderGlsl410Core() {
return this.glslVersion + "\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "uniform sampler2D Texture;\n"
+ "layout (location = 0) out vec4 Out_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,256 @@
package com.moulberry.flashback.editor.ui;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import org.joml.Intersectionf;
import org.joml.Vector3f;
import org.lwjgl.glfw.GLFW;
public abstract sealed class EditorMovementControls permits EditorMovementControls.None, EditorMovementControls.Rotate, EditorMovementControls.Pan, EditorMovementControls.Arcball {
// Interface
public abstract boolean allowGameInputWhileCaptureKeyboard();
public abstract boolean shouldStop(boolean isGrabbed);
public abstract void update(double mouseDeltaX, double mouseDeltaY);
// Static constructors
public static EditorMovementControls none() {
return None.INSTANCE;
}
public static EditorMovementControls rotate() {
LocalPlayer player = Minecraft.getInstance().player;
if (player == null) return None.INSTANCE;
return new Rotate(ReplayUI.getMouseForwardsVector(), new Vec2(
Minecraft.getInstance().player.getXRot(),
Minecraft.getInstance().player.getYRot()
));
}
// public static EditorMovementControls pan() {
// LocalPlayer player = Minecraft.getInstance().player;
// if (player == null) return None.INSTANCE;
//
// RayCaster.RaycastResult result = Tool.raycastBlock();
// if (result == null) return None.INSTANCE;
//
// Vec3 planePoint = result.getLocation();
// return new Pan(player.position(), planePoint.toVector3f(), player.getLookAngle().toVector3f().negate());
// }
// public static EditorMovementControls arcball() {
// LocalPlayer player = Minecraft.getInstance().player;
// if (player == null) return None.INSTANCE;
//
// var look = ReplayUI.getMouseLookVector();
// if (look == null) return None.INSTANCE;
//
// RayCaster.RaycastResult result = RayCaster.raycast(Minecraft.getInstance().level,
// player.getEyePosition().toVector3f(), look.toVector3f(), false, false);
//
// Vec3 point;
// if (result != null) {
// point = result.getLocation();
// } else {
// return None.INSTANCE;
// }
//
// float distance = (float) point.distanceTo(player.getEyePosition());
// return new Arcball(point, distance, true);
// }
// Implementations
protected static final class None extends EditorMovementControls {
private static final None INSTANCE = new None();
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return false;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return false;
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
}
}
protected static final class Rotate extends EditorMovementControls {
private final Vec3 originalForwards;
private final Vec2 originalAngles;
public Rotate(Vec3 originalForwards, Vec2 originalAngles) {
this.originalForwards = originalForwards;
this.originalAngles = originalAngles;
}
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return true;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return !ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_LEFT);
// todo: keybinds
// return !Keybinds.ROTATE_CAMERA.isDownIgnoreMods();
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
Vec3 forwards = ReplayUI.getMouseForwardsVector();
LocalPlayer player = Minecraft.getInstance().player;
if (forwards == null || player == null) return;
float pitch = this.originalAngles.x;
float yaw = this.originalAngles.y;
Vec3 lastVector = this.originalForwards;
for (int i=1; i<=10; i++) {
Vec3 thisVector = this.originalForwards.lerp(forwards, i/10f);
// Calculate pitch
double differenceY = lastVector.y - thisVector.y;
double pitchDelta = Math.toDegrees(Math.asin(differenceY / 2f)) * 2;
pitch = Mth.wrapDegrees(pitch - (float) pitchDelta);
pitch = Mth.clamp(pitch, -90, 90);
// Calculate change in yaw
double yaw1 = Math.toDegrees(Math.atan2(lastVector.x, lastVector.z));
double yaw2 = Math.toDegrees(Math.atan2(thisVector.x, thisVector.z));
double yawDelta = Mth.wrapDegrees(yaw1 - yaw2);
// Calculate scaling factor (radius of circle on unit sphere at current pitch)
Vector3f forwards3f = lastVector.lerp(thisVector, 0.5f).toVector3f();
forwards3f.rotateX((float) Math.toRadians(pitch));
forwards3f.normalize();
float radius = (float) Math.sqrt(1 - forwards3f.y() * forwards3f.y()) * 1.08f;
if (radius < 0.2f) radius = 0.2f;
yaw = Mth.wrapDegrees(yaw - (float) yawDelta / radius);
lastVector = thisVector;
}
// Set values
player.setXRot(pitch);
player.setYRot(yaw);
}
}
protected static final class Pan extends EditorMovementControls {
private final Vec3 originalPos;
private final Vector3f planePoint;
private final Vector3f planeNormal;
public Pan(Vec3 originalPos, Vector3f planePoint, Vector3f planeNormal) {
this.originalPos = originalPos;
this.planePoint = planePoint;
this.planeNormal = planeNormal;
}
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return false;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return !ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_RIGHT);
// return !Keybinds.PAN_CAMERA.isDownIgnoreMods();
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
Vec3 forwards = ReplayUI.getMouseForwardsVector();
LocalPlayer player = Minecraft.getInstance().player;
if (forwards == null || player == null) return;
var origin = this.originalPos.add(0, player.getEyeHeight(), 0).toVector3f();
var view = ReplayUI.getMouseLookVectorFromForwards(forwards).toVector3f();
var distance = Intersectionf.intersectRayPlane(origin, view, this.planePoint, this.planeNormal, 1E-5f);
if (distance < 0) return;
Vector3f targetPoint = origin.add(new Vector3f(view).mul(distance));
Vector3f targetDelta = new Vector3f(targetPoint).sub(this.planePoint);
var finalPos = this.originalPos.subtract(targetDelta.x, targetDelta.y, targetDelta.z);
player.setPos(finalPos);
player.setOldPosAndRot();
}
}
protected static final class Arcball extends EditorMovementControls {
private final Vec3 point;
private float distance;
private boolean snapLook;
public Arcball(Vec3 point, float distance, boolean snapLook) {
this.point = point;
this.distance = Math.max(1, distance);
this.snapLook = snapLook;
}
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return false;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return !isGrabbed;
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
LocalPlayer player = Minecraft.getInstance().player;
if (player == null) return;
if (this.snapLook) {
this.snapLook = false;
var look = ReplayUI.getMouseLookVector();
double horizontal = Math.sqrt(look.x*look.x + look.z*look.z);
float newXRot = Mth.wrapDegrees((float)(Math.toDegrees(-(Mth.atan2(look.y, horizontal)))));
float newYRot = Mth.wrapDegrees((float)(Math.toDegrees(Mth.atan2(look.z, look.x))) - 90.0f);
player.setXRot(newXRot);
player.setYRot(newYRot);
return;
}
double baseSensitivity = Minecraft.getInstance().options.sensitivity().get() * (double)0.6f + (double)0.2f;
double sensitivity = baseSensitivity * baseSensitivity * baseSensitivity * 8.0;
int invert = Minecraft.getInstance().options.invertYMouse().get() ? -1 : 1;
player.turn(mouseDeltaX * sensitivity, mouseDeltaY * sensitivity * invert);
if (ImGui.getIO().getMouseWheel() != 0) {
float wheel = Math.signum(ImGui.getIO().getMouseWheel());
float move = this.distance * 0.05f;
if (move > 4) move = 4 + (float)Math.sqrt(move - 4);
move *= wheel;
if (ReplayUI.isMoveQuickDown()) move *= 2;
this.distance = Math.max(1, this.distance - move);
}
Vec3 position = this.point.subtract(player.getLookAngle().scale(this.distance));
Minecraft.getInstance().player.setPos(position.subtract(0, player.getEyeHeight(), 0));
Minecraft.getInstance().player.setOldPosAndRot();
}
}
}
@@ -0,0 +1,160 @@
package com.moulberry.flashback.editor.ui;
public class GlyphRanges {
private static final short[] SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00 = {
0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2,
1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4,
2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1,
1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2,
3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6,
1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1,
1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3,
2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4,
27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12,
3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1,
1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23,
176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6,
5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6,
1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1,
6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5,
2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15,
2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6,
2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4,
3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5,
3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2,
3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16,
1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31,
140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7,
5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2,
2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13,
4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3,
2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4,
4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1,
3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3,
3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11,
2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9,
5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2,
3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3,
1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12,
4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8,
4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5,
26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1,
3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5,
2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6,
10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6
};
private static final short[] SC_BASE_RANGES = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x2000, 0x206F, // General Punctuation
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
(short)0xFF00, (short)0xFFEF, // Half-width characters
(short)0xFFFD, (short)0xFFFD // Invalid
};
private static short[] SC_FULL_RANGES = null;
public static short[] getSimplifiedChineseRanges() {
if (SC_FULL_RANGES == null) {
SC_FULL_RANGES = new short[SC_BASE_RANGES.length + SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00.length*2 + 1];
System.arraycopy(SC_BASE_RANGES, 0, SC_FULL_RANGES, 0, SC_BASE_RANGES.length);
unpackAccumulativeOffsetsIntoRanges(0x4E00,SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00, SC_BASE_RANGES.length, SC_FULL_RANGES);
}
return SC_FULL_RANGES;
}
private static final short[] JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00 = new short[] {
0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1,
1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3,
2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8,
2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5,
2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1,
1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30,
2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3,
13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4,
5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14,
2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1,
1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1,
7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1,
1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1,
6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2,
10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7,
2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5,
3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1,
6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7,
4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2,
4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5,
1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6,
12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2,
1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16,
22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11,
2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18,
18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9,
14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3,
1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6,
40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1,
12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8,
2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1,
1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10,
1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5,
3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2,
14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5,
12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1,
2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5,
1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4,
3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7,
2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5,
13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13,
18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21,
37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1,
5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38,
32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4,
1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4,
4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
3,2,1,1,1,1,2,1,1
};
private static final short JP_BASE_RANGES[] = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
(short)0xFF00, (short)0xFFEF, // Half-width characters
(short)0xFFFD, (short)0xFFFD // Invalid
};
private static short[] JP_FULL_RANGES = null;
public static short[] getJapaneseRanges() {
if (JP_FULL_RANGES == null) {
JP_FULL_RANGES = new short[JP_BASE_RANGES.length + JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00.length*2 + 1];
System.arraycopy(JP_BASE_RANGES, 0, JP_FULL_RANGES, 0, JP_BASE_RANGES.length);
unpackAccumulativeOffsetsIntoRanges(0x4E00, JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00, JP_BASE_RANGES.length, JP_FULL_RANGES);
}
return JP_FULL_RANGES;
}
private static final short[] TC_FULL_RANGES = {
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x2000, 0x206F, // General Punctuation
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
(short)0xFF00, (short)0xFFEF, // Half-width characters
(short)0xFFFD, (short)0xFFFD, // Invalid
0x4e00, (short)0x9FAF, // CJK Ideograms
0,
};
public static short[] getChineseFullRanges() {
return TC_FULL_RANGES;
}
static void unpackAccumulativeOffsetsIntoRanges(int baseCodepoint, short[] accumulativeOffsets, int index, short[] output) {
for (int n = 0; n < accumulativeOffsets.length; n++, index += 2) {
output[index] = output[index+1] = (short)(baseCodepoint + accumulativeOffsets[n]);
baseCodepoint += accumulativeOffsets[n];
}
output[output.length - 1] = 0;
}
}
@@ -0,0 +1,535 @@
package com.moulberry.flashback.editor.ui;
import com.moulberry.flashback.combo_options.ComboOption;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiComboFlags;
import imgui.flag.ImGuiHoveredFlags;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImBoolean;
import imgui.type.ImString;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ConfirmLinkScreen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.glfw.GLFW;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntConsumer;
import java.util.function.Predicate;
public class ImGuiHelper {
public static String getString(ImString string) {
StringBuilder builder = new StringBuilder();
String str = string.get();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c == '\0') break;
builder.append(c);
}
return builder.toString();
}
public static ImString createResizableImString(String text) {
ImString imString = new ImString(text);
imString.inputData.isResizable = true;
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<>();
public static <T extends Enum<?> & ComboOption> T enumCombo(String label, T c, T[] values) {
int currentIndex = -1;
for (int i = 0; i < values.length; i++) {
T value = values[i];
if (value == c) {
currentIndex = i;
break;
}
}
String[] text = new String[values.length];
for (int i = 0; i < text.length; i++) {
text[i] = values[i].text();
}
enumComboSharedArray[0] = currentIndex;
combo(label, enumComboSharedArray, text);
if (enumComboSharedArray[0] == currentIndex) {
return c;
} else {
return values[enumComboSharedArray[0]];
}
}
@SuppressWarnings("unchecked")
public static <T extends Enum<?> & ComboOption> T enumCombo(String label, T c) {
Class<?> clazz = c.getClass();
int currentIndex = c.ordinal();
String[] text = enumComboCachedText.get(clazz);
if (text == null) {
T[] options = (T[]) clazz.getEnumConstants();
enumComboCachedValues.put(clazz, options);
text = new String[options.length];
for (int i = 0; i < text.length; i++) {
text[i] = options[i].text();
}
enumComboCachedText.put(clazz, text);
}
enumComboSharedArray[0] = currentIndex;
combo(label, enumComboSharedArray, text);
if (enumComboSharedArray[0] == currentIndex) {
return c;
} else {
return (T) enumComboCachedValues.get(clazz)[enumComboSharedArray[0]];
}
}
public static boolean combo(String label, int[] currentItem, String[] values) {
return combo(label, currentItem, values, ImGuiComboFlags.None);
}
public static boolean combo(String label, int[] currentItem, String[] values, int imguiComboFlags) {
boolean changed = false;
if (currentItem[0] >= values.length && values.length > 0) {
currentItem[0] = values.length-1;
}
if (ImGui.beginCombo(label, currentItem[0] < 0 ? "" : values[currentItem[0]], imguiComboFlags)) {
for (int i=0; i<values.length; i++) {
ImGui.pushID(i);
boolean selected = i == currentItem[0];
if (ImGui.selectable(values[i], selected) && !selected) {
currentItem[0] = i;
changed = true;
}
if (selected) ImGui.setItemDefaultFocus();
ImGui.popID();
}
ImGui.endCombo();
}
return changed;
}
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);
}
public static String modifyFromInput(String existing) {
wantSpecialInputThisFrame = true;
String newInput = specialInput.toString();
existing = existing.substring(0, Math.max(0, existing.length() - backspaceCount));
existing += newInput;
specialInput.setLength(0);
backspaceCount = 0;
return existing;
}
public static boolean getWantsSpecialInput() {
return wantSpecialInputLastFrame;
}
public static boolean addInputCharacter(char c) {
if (wantSpecialInputLastFrame) {
specialInput.append(c);
return true;
}
return false;
}
public static boolean backspaceInput(int mods) {
if (wantSpecialInputLastFrame) {
if ((mods & GLFW.GLFW_MOD_CONTROL) != 0) {
specialInput.setLength(0);
backspaceCount = 10000;
return true;
}
if (specialInput.length() > 0) {
specialInput.setLength(specialInput.length() - 1);
} else {
backspaceCount += 1;
}
return true;
}
return false;
}
public static boolean beginPopup(String id) {
return beginPopup(id, ImGuiWindowFlags.None);
}
public static boolean beginPopup(String id, int imGuiWindowFlags) {
if (ImGui.beginPopup(id, imGuiWindowFlags | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings)) {
closeableModalOnTop = false;
return true;
} else {
return false;
}
}
public static boolean beginPopupModal(String id) {
return beginPopupModal(id, ImGuiWindowFlags.None);
}
public static boolean beginPopupModal(String id, int imGuiWindowFlags) {
if (ImGui.beginPopupModal(id, imGuiWindowFlags | ImGuiWindowFlags.NoSavedSettings)) {
closeableModalOnTop = false;
return true;
} else {
return false;
}
}
public static boolean beginPopupModalCloseable(String id) {
return beginPopupModalCloseable(id, ImGuiWindowFlags.None);
}
public static boolean beginPopupModalCloseable(String id, int imGuiWindowFlags) {
if (ImGui.beginPopupModal(id, new ImBoolean(true), imGuiWindowFlags | ImGuiWindowFlags.NoSavedSettings)) {
closeableModalOnTop = true;
return true;
} else {
return false;
}
}
public static void endPopupModalCloseable() {
if (closeableModalOnTop && closeableModalOnTopLast && ReplayUI.consumeNavClose()) {
ImGui.closeCurrentPopup();
}
ImGui.endPopup();
}
public static float borderIndentation = 0;
public static void setupBorder() {
ImGui.beginGroup();
float windowPadding = ImGui.getStyle().getWindowPaddingX();
borderIndentation += windowPadding;
ImGui.indent(windowPadding);
ImGui.setCursorPosY(ImGui.getCursorPosY() + ImGui.getStyle().getWindowPaddingY());
}
public static void finishBorder() {
float windowPadding = ImGui.getStyle().getWindowPaddingX();
borderIndentation -= windowPadding;
ImGui.unindent(windowPadding);
ImGui.endGroup();
ImGui.getWindowDrawList().addRect(ImGui.getItemRectMinX(), ImGui.getItemRectMinY(),
ImGui.getItemRectMinX() + ImGui.getContentRegionAvailX(),
ImGui.getItemRectMaxY() + ImGui.getStyle().getWindowPaddingY(), ImGui.getColorU32(ImGuiCol.Separator));
ImGui.setCursorPosY(ImGui.getCursorPosY() + ImGui.getStyle().getWindowPaddingY());
}
public static float calcTextWidth(String text) {
ImVec2 textSizeVec = new ImVec2();
ImGui.calcTextSize(textSizeVec, text);
return textSizeVec.x;
}
public static void helpMarker(String message) {
ImGui.textDisabled("(?)");
tooltip(message);
}
public static void tooltip(String message) {
tooltip(message, ImGuiHoveredFlags.None);
}
public static void tooltip(String message, int imGuiHoveredFlags) {
if (ImGui.isItemHovered(imGuiHoveredFlags)) {
drawTooltip(message);
}
}
public static void drawTooltip(String message) {
ImGui.beginTooltip();
ImGui.pushTextWrapPos(ImGui.getFontSize() * 35.0f);
ImGui.textUnformatted(message);
ImGui.popTextWrapPos();
ImGui.endTooltip();
}
public static void disabledMenuItem(String label, String disabledMessage) {
ImGui.beginDisabled();
ImGui.menuItem(label);
ImGui.endDisabled();
tooltip(disabledMessage, ImGuiHoveredFlags.AllowWhenDisabled);
}
public static void separatorWithText(String text) {
float textStartX = ImGui.getCursorScreenPosX() + ImGui.getStyle().getIndentSpacing();
float size = ImGui.getWindowSizeX() - borderIndentation;
if (ImGui.isRectVisible(size, ImGui.getFontSize())) {
float textEndX = textStartX + ImGuiHelper.calcTextWidth(text);
float lineEndX = ImGui.getWindowPosX() + size;
float lineY = ImGui.getCursorScreenPosY() + ImGui.getFontSize()/2f;
ImGui.getWindowDrawList().addLine(ImGui.getCursorScreenPosX() - 4, lineY,
Math.min(lineEndX, textStartX) - 4, lineY,
ImGui.getColorU32(ImGuiCol.Separator));
if (textEndX + 4 < lineEndX) {
ImGui.getWindowDrawList().addLine(textEndX + 4, lineY,
lineEndX - 4, lineY,
ImGui.getColorU32(ImGuiCol.Separator));
}
}
ImGui.setCursorScreenPos(textStartX, ImGui.getCursorScreenPosY());
ImGui.textColored(ImGui.getColorU32(ImGuiCol.TextDisabled), text);
}
public static boolean radio(String label, int[] currentItem, String[] values) {
int item = currentItem[0];
int newItem = -1;
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (i > 0) ImGui.sameLine();
if (item == i) ImGui.beginDisabled();
if (ImGui.button(value)) newItem = i;
if (item == i) ImGui.endDisabled();
}
if (label != null) {
ImGui.sameLine();
ImGui.text(label);
}
if (newItem != -1) {
currentItem[0] = newItem;
return true;
} else {
return false;
}
}
public static int buttons(String... labels) {
if (labels.length == 0) return -1;
// Calculate widths
float[] widths = new float[labels.length];
float totalRawWidth = 0;
for (int i = 0; i < labels.length; i++) {
String label = labels[i];
float width = ImGuiHelper.calcTextWidth(label);
widths[i] = width;
totalRawWidth += width;
}
// Calculate extraPadding
float availableWidth = ImGui.getContentRegionAvailX();
float freeSpace = availableWidth - totalRawWidth - ImGui.getStyle().getItemSpacingX()*(labels.length - 1);
float extraPadding = Math.max(ImGui.getStyle().getFramePaddingX()*2, freeSpace / labels.length);
// Draw buttons
float height = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2f;
int pressed = -1;
for (int i = 0; i < labels.length; i++) {
if (ImGui.button(labels[i], widths[i] + extraPadding, height)) {
pressed = i;
}
if (i != labels.length-1) ImGui.sameLine();
}
return pressed;
}
private static int pushedColors = 0;
private static int pushedStyleVars = 0;
public static void popAllStyleColors() {
ImGui.popStyleColor(pushedColors);
pushedColors = 0;
}
public static void popAllStyleVars() {
ImGui.popStyleVar(pushedStyleVars);
pushedStyleVars = 0;
}
public static void pushStyleColor(int imGuiCol, float r, float g, float b, float a) {
ImGui.pushStyleColor(imGuiCol, r, g, b, a);
pushedColors += 1;
}
public static void pushStyleColor(int imGuiCol, int r, int g, int b, int a) {
ImGui.pushStyleColor(imGuiCol, r, g, b, a);
pushedColors += 1;
}
public static void pushStyleColor(int imGuiCol, int col) {
ImGui.pushStyleColor(imGuiCol, col);
pushedColors += 1;
}
public static void popStyleColor() {
if (pushedColors >= 1) {
ImGui.popStyleColor();
pushedColors -= 1;
}
}
public static void popStyleColor(int count) {
count = Math.min(count, pushedColors);
if (count == 0) return;
ImGui.popStyleColor(count);
pushedColors -= count;
}
public static void pushStyleVar(int imGuiStyleVar, float val) {
ImGui.pushStyleVar(imGuiStyleVar, val);
pushedStyleVars += 1;
}
public static void pushStyleVar(int imGuiStyleVar, float valX, float valY) {
ImGui.pushStyleVar(imGuiStyleVar, valX, valY);
pushedStyleVars += 1;
}
public static void popStyleVar() {
if (pushedStyleVars >= 1) {
ImGui.popStyleVar();
pushedStyleVars -= 1;
}
}
public static void popStyleVar(int count) {
count = Math.min(count, pushedStyleVars);
if (count == 0) return;
ImGui.popStyleVar(count);
pushedStyleVars -= count;
}
}
@@ -0,0 +1,7 @@
package com.moulberry.flashback.editor.ui;
public class Keybinds {
}
@@ -0,0 +1,878 @@
package com.moulberry.flashback.editor.ui;
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.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.windows.MainMenuBar;
import com.moulberry.flashback.editor.ui.windows.StartExportWindow;
import com.moulberry.flashback.editor.ui.windows.TimelineWindow;
import com.moulberry.flashback.editor.ui.windows.VisualsWindow;
import imgui.*;
import imgui.flag.*;
import imgui.internal.ImGuiContext;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
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;
import net.minecraft.world.level.GameType;
import net.minecraft.world.phys.*;
import net.minecraft.world.phys.shapes.CollisionContext;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector4f;
import org.lwjgl.glfw.GLFW;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
public class ReplayUI {
public static final CustomImGuiImplGlfw imguiGlfw = new CustomImGuiImplGlfw();
private static final CustomImGuiImplGl3 imguiGl3 = new CustomImGuiImplGl3();
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;
private static boolean activeLastFrame = false;
public static Matrix4f lastProjectionMatrix = null;
public static Quaternionf lastViewQuaternion = null;
private static ImFont font = null;
public static ImFont icons = null;
private static String languageCode = null;
private static boolean wasNavClose = false;
private static boolean navClose = false;
private static final Lock deferredCloseLock = new ReentrantLock();
private static final IntList deferredCloseTextureIds = new IntArrayList();
private static final List<AutoCloseable> deferredClose = new ArrayList<>();
private static float globalScale = 1.0f;
public static float newGlobalScale = 1.0f;
private static float contentScale = 1.0f;
private static ImGuiContext imGuiContext = null;
private static ImGuiIO imGuiIo = null;
private static boolean popupOpenLastFrame = false;
private static String infoOverlayText = null;
private static long infoOverlayStartMillis = 0;
private static int selectedEntity = Integer.MIN_VALUE;
private static boolean openSelectedEntityPopup = false;
public static void init() {
if (initialized) {
throw new IllegalStateException("ReplayUI initialized twice");
}
initialized = true;
// todo: introduce global scale option
// newGlobalScale = globalScale = Configuration.internal.globalScale;
// Initialize config so that everything starts nicely docked
Path path = Flashback.getConfigDirectory().resolve("imgui.ini");
if (!Files.exists(path)) {
try {
Files.writeString(path, ReplayUIDefaults.LAYOUT);
} catch(IOException ignored) {}
}
long oldImGuiContext = ImGui.getCurrentContext().ptr;
imGuiContext = new ImGuiContext(ImGui.createContext().ptr);
ImGui.setCurrentContext(imGuiContext);
Path relativePath = FabricLoader.getInstance().getGameDir().relativize(path);
ImGui.getIO().setIniFilename(relativePath.toString());
ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
ImGui.getIO().addConfigFlags(ImGuiConfigFlags.DockingEnable);
// ImGui.getIO().addConfigFlags(ImGuiConfigFlags.ViewportsEnable);
ImGui.getIO().setConfigMacOSXBehaviors(Minecraft.ON_OSX);
imguiGlfw.init(Minecraft.getInstance().getWindow().getWindow(), true, new ImGuiIO(ImGui.getIO().ptr));
imguiGl3.init("#version 150");
contentScale = imguiGlfw.contentScale;
initFonts(languageCode);
ReplayUIDefaults.applyStyle(ImGui.getStyle());
ImGuiContext currentContext = ImGui.getCurrentContext();
currentContext.ptr = oldImGuiContext;
ImGui.setCurrentContext(currentContext);
}
public static void initFonts(String languageCode) {
if (languageCode != null) {
ReplayUI.languageCode = languageCode;
} else {
languageCode = "en_us";
}
if (!initialized) {
return;
}
ImGuiIO io = ImGui.getIO();
ImFontAtlas fonts = io.getFonts();
fonts.clear();
int size = (int)(16 * getUiScale());
ImFontGlyphRangesBuilder rangesBuilder = new ImFontGlyphRangesBuilder();
rangesBuilder.addRanges(fonts.getGlyphRangesDefault());
if (languageCode.startsWith("uk") || languageCode.startsWith("ru") || languageCode.startsWith("bg")) {
rangesBuilder.addRanges(fonts.getGlyphRangesCyrillic());
} else if (languageCode.startsWith("tr")) {
rangesBuilder.addText("ÇçĞğİıÖöŞşÜü");
} else if (languageCode.startsWith("pl")) {
rangesBuilder.addRanges(new short[]{0x0100, 0x017F, 0});
} else if (languageCode.startsWith("cs")) {
rangesBuilder.addText("ÁáČčĎďÉéĚěÍíŇňÓóŘřŠšŤťÚúŮůÝýŽž");
}
rangesBuilder.addChar('\u2318'); // Mac CMD
rangesBuilder.addChar('\u2303'); // CTRL
rangesBuilder.addChar('\u2387'); // Alt
rangesBuilder.addChar('\u21E7'); // Shift (up arrow)
rangesBuilder.addChar('\u2756'); // Super
rangesBuilder.addChar('\u26A0'); // Warning symbol
rangesBuilder.addChar('\u2190'); // Left Arrow
rangesBuilder.addChar('\u2191'); // Up Arrow
rangesBuilder.addChar('\u2192'); // Right Arrow
rangesBuilder.addChar('\u2193'); // Down Arrow
// Make sure every printable key on the keyboard is present
for (int i = GLFW.GLFW_KEY_SPACE; i <= GLFW.GLFW_KEY_LAST; i++) {
int scancode = GLFW.glfwGetKeyScancode(i);
if (scancode != -1) {
String key = GLFW.glfwGetKeyName(i, -1);
if (key != null) {
rangesBuilder.addText(key);
rangesBuilder.addText(key.toLowerCase());
rangesBuilder.addText(key.toUpperCase());
rangesBuilder.addText(key.toLowerCase(Locale.ROOT));
rangesBuilder.addText(key.toUpperCase(Locale.ROOT));
}
}
}
short[] glyphRanges = rangesBuilder.buildRanges();
// Font config for additional fonts
final ImFontConfig fontConfig = new ImFontConfig();
fontConfig.setOversampleH(2);
fontConfig.setOversampleV(2);
fontConfig.setName("Inter (Medium), 16px");
font = fonts.addFontFromMemoryTTF(loadFont("inter-medium.ttf"), size, fontConfig, glyphRanges);
// Merge in Japanese/Korean/Chinese/etc. characters if needed
fontConfig.setMergeMode(true);
if (languageCode.startsWith("he")) {
short[] hebrewRanges = new short[]{(short)'\u0590', (short)'\u05FF', (short)'\uFB1D', (short)'\uFB4F', 0};
io.getFonts().addFontFromMemoryTTF(loadFont("heebo-medium.ttf"), size, fontConfig, hebrewRanges);
} else if (languageCode.startsWith("ja")) {
io.getFonts().addFontFromMemoryTTF(loadFont("notosansjp-medium.ttf"), size,
fontConfig, GlyphRanges.getJapaneseRanges());
} else if (languageCode.startsWith("zh")) {
io.getFonts().addFontFromMemoryTTF(loadFont("notosanssc-medium.otf"), size,
fontConfig, GlyphRanges.getChineseFullRanges());
io.getFonts().addFontFromMemoryTTF(loadFont("notosanstc-medium.otf"), size,
fontConfig, GlyphRanges.getChineseFullRanges());
}
fontConfig.setMergeMode(false);
fonts.build();
imguiGl3.updateFontsTexture();
fontConfig.destroy();
fonts.clearTexData();
}
private static byte[] loadFont(String name) {
try {
var resource = Minecraft.getInstance().getResourceManager().getResource(Flashback.createResourceLocation(name));
if (resource.isEmpty()) throw new MissingResourceException("Missing font: " + name, "Font", "");
try (InputStream is = resource.get().open()) {
return is.readAllBytes();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Vec3 getMouseForwardsVector() {
return getMouseForwardsVector(ImGui.getMousePosX(), ImGui.getMousePosY());
}
public static Vec3 getMouseForwardsVector(float mouseX, float mouseY) {
if (!isActive() || (!isFrameHovered && !isMovingCamera()) || lastProjectionMatrix == null || lastViewQuaternion == null) return null;
return getForwardsVector(mouseX, mouseY);
}
public static Vec2 getMouseViewportFraction() {
float x = (ImGui.getMousePosX() - ImGui.getMainViewport().getPosX() - frameX) / frameWidth;
float y = (ImGui.getMousePosY() - ImGui.getMainViewport().getPosY() - frameY) / frameHeight;
return new Vec2(x, y);
}
public static Vec2 getMouseViewportFraction(float mouseX, float mouseY) {
float x = (mouseX - ImGui.getMainViewport().getPosX() - frameX) / frameWidth;
float y = (mouseY - ImGui.getMainViewport().getPosY() - frameY) / frameHeight;
return new Vec2(x, y);
}
public static Vec3 getForwardsVector(float mouseX, float mouseY) {
float x = (mouseX - ImGui.getMainViewport().getPosX() - frameX) / frameWidth * 2 - 1;
float y = (mouseY - ImGui.getMainViewport().getPosY() - frameY) / frameHeight * 2 - 1;
return getForwardsVectorRaw(x, y);
}
public static Vec3 getForwardsVectorRaw(float x, float y) {
if (!isMovingCamera() && (x < -1 || x > 1 || y < -1 || y > 1)) return null;
var matrix = new Matrix4f(lastProjectionMatrix);
matrix.invert();
// Apply inverse projection matrix to get forwards vector
var forwards = new Vector4f(x, y, 0f, 1f);
forwards.mul(matrix);
// Negate and normalize to match MC coordinate space
return new Vec3(forwards.x(), -forwards.y(), forwards.z()).normalize();
}
@Nullable
public static Vec3 getMouseLookVectorFromForwards(Vec3 forwards) {
if (forwards == null) return null;
// Apply the view quaternion to forwards vector to get view vector
var view = forwards.toVector3f();
view.rotate(lastViewQuaternion);
return new Vec3(view.x(), view.y(), view.z()).normalize();
}
@Nullable
public static Vec3 getMouseLookVector(float mouseX, float mouseY) {
return getMouseLookVectorFromForwards(getMouseForwardsVector(mouseX, mouseY));
}
@Nullable
public static Vec3 getMouseLookVector() {
return getMouseLookVectorFromForwards(getMouseForwardsVector());
}
public static boolean isEntitySelected(int entityId) {
return isActive() && selectedEntity == entityId;
}
public static boolean isMovingCamera() {
return imguiGlfw.isGrabbed() && imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME;
}
public static void setInfoOverlay(String text) {
infoOverlayText = text;
infoOverlayStartMillis = System.currentTimeMillis();
}
public static void setupMainViewport() {
var window = Minecraft.getInstance().getWindow();
int frameBottom = window.height - (frameY + frameHeight);
GlStateManager._viewport(frameX * window.getWidth() / window.getScreenWidth(),
frameBottom * window.getHeight() / window.getScreenHeight(),
Math.max(1, frameWidth * window.getWidth() / window.getScreenWidth()),
Math.max(1, frameHeight * window.getHeight() / window.getScreenHeight()));
}
public static float getUiScale() {
return globalScale * contentScale;
}
public static double getNewMouseX(double x) {
return x - frameX;
}
public static double getNewMouseY(double y) {
return y - frameY;
}
public static int getNewGameWidth(float scale) {
return Math.max(1, Math.round(frameWidth * scale));
}
public static int getNewGameHeight(float scale) {
return Math.max(1, Math.round(frameHeight * scale));
}
private static boolean isActiveInternal() {
if (!Flashback.isInReplay()) {
return false;
}
if (Flashback.EXPORT_JOB != null) {
return false;
}
if (Minecraft.getInstance().options.hideGui) {
return false;
}
MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode;
if (gameMode == null) return false;
if (gameMode.getPlayerMode() != GameType.SPECTATOR) return false;
if (Minecraft.getInstance().level == null) return false;
if (Minecraft.getInstance().player == null) return false;
if (Minecraft.getInstance().getOverlay() != null) return false;
return true;
}
public static void deferredCloseTextureId(int textureId) {
deferredCloseLock.lock();
try {
deferredCloseTextureIds.add(textureId);
} finally {
deferredCloseLock.unlock();
}
}
public static void deferredClose(AutoCloseable autoCloseable) {
deferredCloseLock.lock();
try {
deferredClose.add(autoCloseable);
} finally {
deferredCloseLock.unlock();
}
}
public static boolean isActive() {
return activeLastFrame;
}
private static void transitionActiveState(boolean active) {
if (activeLastFrame == active) return;
activeLastFrame = active;
// Recalculate the size of the gameplay window
Window window = Minecraft.getInstance().getWindow();
if (window.getWidth() > 0 && window.getWidth() <= 32768 && window.getHeight() > 0 && window.getHeight() <= 32768) {
Minecraft.getInstance().resizeDisplay();
}
imguiGlfw.ungrab();
if (!activeLastFrame) {
// Make sure the vanilla grab state is correct
if (Minecraft.getInstance().gameMode != null) {
if (Minecraft.getInstance().screen == null) {
Minecraft.getInstance().mouseHandler.releaseMouse();
Minecraft.getInstance().mouseHandler.grabMouse();
} else {
Minecraft.getInstance().mouseHandler.grabMouse();
Minecraft.getInstance().mouseHandler.releaseMouse();
}
Minecraft.getInstance().mouseHandler.setIgnoreFirstMove();
}
} else {
// Forcefully ungrab the cursor
long handle = ImGui.getMainViewport().getPlatformHandle();
if (GLFW.glfwGetInputMode(handle, GLFW.GLFW_CURSOR) != GLFW.GLFW_CURSOR_NORMAL) {
GLFW.glfwSetInputMode(handle, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL);
GLFW.glfwSetCursorPos(handle, ImGui.getMainViewport().getSizeX()/2f, ImGui.getMainViewport().getSizeY()/2f);
}
}
imguiGlfw.setViewportWindowsHidden(!activeLastFrame);
}
public static void drawOverlay() {
long oldImGuiContext = ImGui.getCurrentContext().ptr;
ImGui.setCurrentContext(imGuiContext);
try {
drawOverlayInternal();
} finally {
ImGuiContext currentContext = ImGui.getCurrentContext();
currentContext.ptr = oldImGuiContext;
ImGui.setCurrentContext(currentContext);
}
}
public static void drawOverlayInternal() {
int oldFrameX = frameX;
int oldFrameY = frameY;
int oldFrameWidth = frameWidth;
int oldFrameHeight = frameHeight;
if (!initialized) {
throw new IllegalStateException("Tried to use EditorUI while it was not initialized");
}
deferredCloseLock.lock();
try {
for (int id : deferredCloseTextureIds) {
TextureUtil.releaseTextureId(id);
}
deferredCloseTextureIds.clear();
for (AutoCloseable closeable : deferredClose) {
try {
closeable.close();
} catch (Exception e) {}
}
deferredClose.clear();
} finally {
deferredCloseLock.unlock();
}
if (Minecraft.getInstance().screen instanceof ProgressScreen || Minecraft.getInstance().screen instanceof ReceivingLevelScreen) {
return;
}
if (!isActiveInternal()) {
transitionActiveState(false);
imguiGlfw.updateReleaseAllKeys(true);
return;
} else {
imguiGlfw.updateReleaseAllKeys(false);
}
if (!ImGui.isAnyMouseDown()) {
newGlobalScale = ((int)(newGlobalScale * 16))/16f;
if (newGlobalScale < 0.25) newGlobalScale = 0.25f;
if (newGlobalScale > 4) newGlobalScale = 4f;
float newContentScale = ((int)(imguiGlfw.contentScale * 16))/16f;
if (newContentScale < 0.125) newContentScale = 0.125f;
if (newContentScale > 8) newContentScale = 8f;
if (globalScale != newGlobalScale || contentScale != newContentScale) {
int oldFontSize = (int)(16 * getUiScale());
globalScale = newGlobalScale;
contentScale = newContentScale;
if (oldFontSize != (int)(16 * getUiScale())) {
initFonts(languageCode);
}
}
}
imguiGlfw.newFrame();
ImGui.newFrame();
navClose = ImGui.getIO().getNavInputs(ImGuiNavInput.Cancel) != 0;
if (wasNavClose != navClose) {
wasNavClose = navClose;
} else if (wasNavClose) {
navClose = false;
}
if (ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) {
ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
} else {
ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
}
char controlIcon = Minecraft.ON_OSX ? '\u2318' : '\u2303';
MainMenuBar.render();
// Setup docking
ImGui.setNextWindowBgAlpha(0);
int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode);
imgui.internal.ImGui.dockBuilderGetCentralNode(mainDock).addLocalFlags(imgui.internal.flag.ImGuiDockNodeFlags.NoTabBar);
isFrameHovered = false;
ImGui.setNextWindowDockID(mainDock);
ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0);
boolean fireCancelNavInput = false;
if (ImGui.begin("Main", ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoNavInputs | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoSavedSettings)) {
ImGuiHelper.popStyleVar();
float minX = ImGui.getWindowContentRegionMinX();
float maxX = ImGui.getWindowContentRegionMaxX();
float minY = ImGui.getWindowContentRegionMinY();
float maxY = ImGui.getWindowContentRegionMaxY();
if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {
frameX = (int) (ImGui.getWindowPosX() - ImGui.getWindowViewport().getPosX() + minX);
frameY = (int) (ImGui.getWindowPosY() - ImGui.getWindowViewport().getPosY() + minY);
} else {
frameX = (int) (ImGui.getWindowPosX() + minX);
frameY = (int) (ImGui.getWindowPosY() + minY);
}
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) {
float aspectRatio;
if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO) {
aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY();
} else {
aspectRatio = ReplayVisuals.changeAspectRatio.aspectRatio();
}
float currentAspectRatio = frameWidth / (float) frameHeight;
if (currentAspectRatio < aspectRatio) {
int newHeight = (int)(frameWidth / aspectRatio);
frameY += (frameHeight - newHeight)/2;
frameHeight = newHeight;
} else if (currentAspectRatio > aspectRatio) {
int newWidth = (int)(frameHeight * aspectRatio);
frameX += (frameWidth - newWidth)/2;
frameWidth = newWidth;
}
}
if (infoOverlayText != null) {
long currentMillis = System.currentTimeMillis();
if (currentMillis < infoOverlayStartMillis || currentMillis > infoOverlayStartMillis + 5000) {
infoOverlayText = null;
} 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);
ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowBorderSize, 2);
ImGuiHelper.pushStyleColor(ImGuiCol.Border, 0xFF00FFFF);
if (ImGui.begin("##InfoOverlay", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing |
ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoSavedSettings)) {
ImGui.text(infoOverlayText);
}
ImGui.end();
ImGuiHelper.popStyleColor();
ImGuiHelper.popStyleVar();
}
}
if (ReplayVisuals.sizing == Sizing.UNDERLAY) {
frameX = 0;
frameY = 0;
frameWidth = Minecraft.getInstance().getWindow().getScreenWidth();
frameHeight = Minecraft.getInstance().getWindow().getScreenHeight();
}
if (frameX != oldFrameX || frameY != oldFrameY || frameWidth != oldFrameWidth || frameHeight != oldFrameHeight) {
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 (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 (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) {
selectedEntity = Integer.MIN_VALUE;
} else if (!(entity instanceof Player) && !ReplayVisuals.renderEntities) {
selectedEntity = Integer.MIN_VALUE;
} else {
if (openSelectedEntityPopup) {
ImGui.openPopup("###EntityPopup");
}
if (ImGuiHelper.beginPopup("###EntityPopup")) {
ImGui.text("Entity: " + entity.getUUID());
ImGui.separator();
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());
// }
// ImGui.sameLine();
// ImGui.button("Track Entity");
//
// ImGui.checkbox("Hide During Export", false);
//
// ImGui.checkbox("Force Glowing", false);
// ImGui.sameLine();
// ImGui.colorButton("Glow Colour", new float[4]);
// ImGui.sameLine();
// ImGui.text("Glow Colour");
//
// if (entity instanceof LivingEntity) {
// ImGui.checkbox("Show Nametag", true);
// ImGui.checkbox("Override Nametag", false);
// }
// if (entity instanceof Player) {
// ImGui.checkbox("Override Skin", false);
// }
ImGui.endPopup();
}
if (!ImGui.isPopupOpen("###EntityPopup")) {
selectedEntity = Integer.MIN_VALUE;
}
}
}
openSelectedEntityPopup = false;
if (ImGui.isWindowHovered() && ImGui.getMousePosY() > ImGui.getWindowPosY()) {
isFrameHovered = true;
if (Minecraft.getInstance().screen != null) {
ImGui.captureMouseFromApp(false);
} else if (isMovingCamera()) {
LocalPlayer player = Minecraft.getInstance().player;
if (player != null) {
int wheelY = (int) Math.signum(ImGui.getIO().getMouseWheel());
if (wheelY != 0) {
final float defaultFlyingSpeed = 0.05f;
float flyingSpeed = Mth.clamp(player.getAbilities().getFlyingSpeed() + (float)wheelY * defaultFlyingSpeed / 10f,
defaultFlyingSpeed / 10f, defaultFlyingSpeed * 5.0f);
setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed));
player.getAbilities().setFlyingSpeed(flyingSpeed);
}
}
} else if (ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) {
fireCancelNavInput |= handleBasicInputs();
}
}
} else {
ImGuiHelper.popStyleVar();
}
ImGui.end();
VisualsWindow.render();
TimelineWindow.render();
StartExportWindow.render();
popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup);
ImGui.render();
ImGuiHelper.endFrame();
if (fireCancelNavInput) {
ImGui.getIO().setNavInputs(ImGuiNavInput.Input, 1.0f);
ImGui.getIO().setNavInputs(ImGuiNavInput.Cancel, 1.0f);
}
long ctx = GLFW.glfwGetCurrentContext();
ImGui.updatePlatformWindows();
ImGui.renderPlatformWindowsDefault();
GLFW.glfwMakeContextCurrent(ctx);
var drawData = ImGui.getDrawData();
if (drawData != null) {
imguiGl3.renderDrawData(drawData);
}
transitionActiveState(true);
}
public static boolean isMainFrameHovered() {
return isFrameHovered;
}
private static boolean handleBasicInputs() {
// if (ImGui.isMouseClicked(ImGuiMouseButton.Left) && UserAction.LEFT_MOUSE.call(null) == UserAction.ActionResult.USED_STOP) {
// return true;
// }
if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_RIGHT)) {
HitResult result = getLookTarget();
if (result instanceof EntityHitResult entityHitResult) {
if (Minecraft.getInstance().player == Minecraft.getInstance().cameraEntity) {
Minecraft.getInstance().player.setDeltaMovement(Vec3.ZERO);
}
selectedEntity = entityHitResult.getEntity().getId();
openSelectedEntityPopup = true;
}
return true;
}
if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_LEFT)) {
int key = -GLFW.GLFW_MOUSE_BUTTON_LEFT-1;
if (key != 0) {
imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f);
}
return true;
}
// if (Keybinds.ADJUST_RADIUS.isPressed(false)) {
// if (ToolManager.isToolActive() && ToolManager.getCurrentTool().initiateAdjustment()) {
// int key = Keybinds.ADJUST_RADIUS.getKey();
// if (key != 0) {
// imguiGlfw.setGrabbed(false, key, -1, -1);
// }
//
// adjustingTool = true;
// adjustingToolOffsetX = 0;
// adjustingToolOffsetY = 0;
//
// return true;
// }
// } else if (Keybinds.ROTATE_CAMERA.isPressed(false)) {
// movementControls = EditorMovementControls.rotate();
// return true;
// } else if (Keybinds.PICK_BLOCK.isPressed(false)) {
// RayCaster.RaycastResult result = Tool.raycastBlock();
// if (result != null) {
// BlockState blockState = Minecraft.getInstance().level.getBlockState(result.blockPos());
// CustomBlockState customBlockState = ServerCustomBlocks.getCustomStateFor(blockState);
// activeBlockHistory.setActive(Objects.requireNonNullElse(customBlockState, (CustomBlockState) blockState));
// return true;
// }
// } else if (Keybinds.USE_TOOL.isPressed(false)) {
// if (UserAction.RIGHT_MOUSE.call(null) != UserAction.ActionResult.NOT_HANDLED || ToolManager.isToolActive()) {
// return true;
// }
// } else if (Keybinds.ARCBALL_CAMERA.isPressed(false)) {
// Tool currentTool = ToolManager.isToolActive() ? ToolManager.getCurrentTool() : null;
// if (currentTool instanceof RulerTool || currentTool instanceof ModifyTool || Configuration.keybind.useCenterOfScreenForArcball) {
// movementControls = EditorMovementControls.arcballFromRaycast();
// if (movementControls != EditorMovementControls.none()) {
// int key = Keybinds.ARCBALL_CAMERA.getKey();
// if (key != 0) {
// imguiGlfw.setGrabbed(false, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f);
// }
// return true;
// }
// } else {
// pendingDepthActions.add(PendingDepthAction.ARCBALL);
// return true;
// }
// } else if (Keybinds.PAN_CAMERA.isPressed(false)) {
// movementControls = EditorMovementControls.pan();
// return true;
// }
// if (Keybinds.CROSSHAIR_CAMERA.isPressed(false)) {
// int key = Keybinds.CROSSHAIR_CAMERA.getKey();
// if (key != 0) {
// imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f);
// }
// return true;
// }
return false;
}
@Nullable
private static HitResult getLookTarget() {
Vec3 look = getMouseLookVector();
if (look == null) {
return null;
}
Entity cameraEntity = Minecraft.getInstance().cameraEntity;
if (cameraEntity == null) {
return null;
}
float distance = 64f;
Vec3 from = cameraEntity.getEyePosition();
Vec3 to = from.add(look.scale(distance));
BlockHitResult blockResult = null;
EntityHitResult entityResult = null;
if (ReplayVisuals.renderBlocks) {
ClipContext clipContext = new ClipContext(from, to, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, CollisionContext.empty());
blockResult = Minecraft.getInstance().level.clip(clipContext);
if (blockResult.getType() != HitResult.Type.MISS) {
distance = (float) blockResult.getLocation().distanceTo(from);
}
}
if (ReplayVisuals.renderEntities || 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) {
predicate = entity -> true;
} else if (ReplayVisuals.renderPlayers) {
predicate = entity -> entity instanceof Player;
} else if (ReplayVisuals.renderEntities) {
predicate = entity -> !(entity instanceof Player);
} else {
throw new IllegalStateException();
}
entityResult = ProjectileUtil.getEntityHitResult(cameraEntity, from, from.add(look.scale(distance)),
boundingBox, predicate, distance*distance);
}
if (entityResult != null && entityResult.getLocation().distanceTo(from) < distance) {
return entityResult;
} else if (blockResult != null && blockResult.getType() != HitResult.Type.MISS) {
return blockResult;
} else {
return null;
}
}
public static boolean consumeNavClose() {
boolean navClose = ReplayUI.navClose;
ReplayUI.navClose = false;
return navClose;
}
public static boolean isMoveQuickDown() {
return ImGui.isKeyDown(Minecraft.getInstance().options.keySprint.key.getValue());
}
public static boolean isCtrlOrCmdDown() {
return Minecraft.ON_OSX ? ImGui.getIO().getKeySuper() : ImGui.getIO().getKeyCtrl();
}
}
@@ -0,0 +1,113 @@
package com.moulberry.flashback.editor.ui;
import imgui.ImGui;
import imgui.ImGuiStyle;
import imgui.flag.ImGuiCol;
import net.minecraft.client.Minecraft;
import net.minecraft.util.FastColor;
import org.lwjgl.glfw.GLFW;
public class ReplayUIDefaults {
public static final String LAYOUT = """
[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
DockNode ID=0x00000003 Parent=0x00000001 SizeRef=1670,830 CentralNode=1 NoTabBar=1 Selected=0x1F1A625A
DockNode ID=0x00000004 Parent=0x00000001 SizeRef=250,830 Selected=0x595032EA
DockNode ID=0x00000002 Parent=0x8B93E3BD SizeRef=1920,250 Selected=0xBF88A430
""";
public static void applyStyle(ImGuiStyle style) {
ImGui.styleColorsDark(style);
// for (int i = 0; i < ImGuiCol.COUNT; i++) {
// style.setColor(i, 0xFF0000FF);
// }
style.setColor(ImGuiCol.Text, 0xFFFFFFFF);
style.setColor(ImGuiCol.TextDisabled, 0xFFAAAAAA);
style.setColor(ImGuiCol.Separator, 0xFFAAAAAA);
int windowBg = 0xCC282020;
style.setColor(ImGuiCol.WindowBg, windowBg);
style.setColor(ImGuiCol.Border, brighten(windowBg, 150));
int titleBg = 0xFF1b1515;
style.setColor(ImGuiCol.TitleBg, titleBg);
style.setColor(ImGuiCol.TitleBgActive, brighten(titleBg, 140));
int popupBg = 0xFF382828;
style.setColor(ImGuiCol.PopupBg, popupBg);
int frameBg = 0xAA3F3838;
style.setColor(ImGuiCol.FrameBg, frameBg);
style.setColor(ImGuiCol.FrameBgActive, darken(frameBg));
style.setColor(ImGuiCol.FrameBgHovered, brighten(frameBg));
int button = 0xFFCB6800;
style.setColor(ImGuiCol.Button, button);
style.setColor(ImGuiCol.ButtonActive, darken(button));
style.setColor(ImGuiCol.ButtonHovered, brighten(button));
style.setColor(ImGuiCol.CheckMark, 0xFFFB8800);
int header = 0x80BB5F00;
style.setColor(ImGuiCol.Header, header);
style.setColor(ImGuiCol.HeaderActive, darken(header));
style.setColor(ImGuiCol.HeaderHovered, brighten(header));
style.setColor(ImGuiCol.MenuBarBg, windowBg);
style.setColor(ImGuiCol.TabUnfocusedActive, 0xCC383030);
style.setColor(ImGuiCol.TabActive, 0xFF484040);
style.setColor(ImGuiCol.ModalWindowDimBg, 0x58CCCCCC);
if (GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_K) != 0) {
ImGui.styleColorsDark(style);
}
}
private static int brighten(int abgr) {
return brighten(abgr, 120);
}
private static int brighten(int abgr, int percentage) {
int alpha = (abgr >> 24) & 0xFF;
int blue = (abgr >> 16) & 0xFF;
int green = (abgr >> 8) & 0xFF;
int red = abgr & 0xFF;
blue = Math.min(0xFF, blue * percentage/100);
green = Math.min(0xFF, green * percentage/100);
red = Math.min(0xFF, red * percentage/100);
return FastColor.ABGR32.color(alpha, blue, green, red);
}
private static int darken(int abgr) {
int alpha = (abgr >> 24) & 0xFF;
int blue = (abgr >> 16) & 0xFF;
int green = (abgr >> 8) & 0xFF;
int red = abgr & 0xFF;
blue = Math.min(0xFF, blue * 4/5);
green = Math.min(0xFF, green * 4/5);
red = Math.min(0xFF, red * 4/5);
return FastColor.ABGR32.color(alpha, blue, green, red);
}
}
@@ -0,0 +1,17 @@
package com.moulberry.flashback.editor.ui.windows;
import imgui.ImGui;
public class MainMenuBar {
public static void render() {
if (ImGui.beginMainMenuBar()) {
if (ImGui.menuItem("Export")) {
StartExportWindow.open();
}
ImGui.endMainMenuBar();
}
}
}
@@ -0,0 +1,232 @@
package com.moulberry.flashback.editor.ui.windows;
import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback;
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.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
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.ImGuiWindowFlags;
import imgui.type.ImFloat;
import imgui.type.ImString;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import java.nio.file.Path;
import java.util.List;
public class StartExportWindow {
private static boolean open = 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 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 boolean useMaximumBitrate = false;
private static final ImString bitrate = ImGuiHelper.createResizableImString("20m");
static {
bitrate.inputData.allowedChars = "0123456789kmb";
}
public static void render() {
if (open) {
ImGui.openPopup("###StartExport");
Window window = Minecraft.getInstance().getWindow();
// Only update the resolution if the framebuffer size changes
// This way, when users input custom resolutions it persists between opens
if (window.framebufferWidth != lastFramebufferSize[0] || window.framebufferHeight != lastFramebufferSize[1]) {
resolution[0] = window.framebufferWidth;
resolution[1] = window.framebufferHeight;
lastFramebufferSize[0] = window.framebufferWidth;
lastFramebufferSize[1] = window.framebufferHeight;
}
open = false;
}
if (ImGuiHelper.beginPopupModalCloseable("Export to video###StartExport", ImGuiWindowFlags.AlwaysAutoResize)) {
ImGuiHelper.separatorWithText("Capture Options");
ImGui.inputInt2("Resolution", resolution);
if (ImGui.inputInt2("Start/end tick", startEndTick)) {
EditorState editorState = EditorStateCache.getCurrent();
ReplayServer replayServer = Flashback.getReplayServer();
if (editorState != null && replayServer != null) {
editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks());
}
}
ImGui.inputFloat("Framerate", framerate);
ImGuiHelper.separatorWithText("Video Options");
VideoContainer newContainer = ImGuiHelper.enumCombo("Container", container);
if (newContainer != container) {
container = newContainer;
boolean supported = false;
for (VideoCodec supportedCodec : container.getSupportedCodecs()) {
if (codec == supportedCodec) {
supported = true;
break;
}
}
if (!supported) {
codec = container.getSupportedCodecs()[0];
}
}
VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", codec, container.getSupportedCodecs());
if (newCodec != codec) {
codec = newCodec;
selectedEncoder[0] = 0;
}
String[] encoders = codec.getEncoders();
if (encoders.length > 1) {
ImGuiHelper.combo("Encoder", selectedEncoder, 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;
}
if (!useMaximumBitrate) {
ImGui.inputText("Bitrate", bitrate);
if (ImGui.isItemDeactivatedAfterEdit()) {
int numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
bitrate.set(bitrateToString(numBitrate));
}
}
if (ImGui.button("Begin")) {
int numBitrate;
if (useMaximumBitrate) {
numBitrate = 0;
} else {
numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
}
String encoder = codec.getEncoders()[selectedEncoder[0]];
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]);
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);
Flashback.EXPORT_JOB = new ExportJob(settings);
}
});
ImGui.closeCurrentPopup();
}
ImGuiHelper.endPopupModalCloseable();
}
}
private static int stringToBitrate(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 == 'k') {
modifier *= 1000;
} else if (c == 'm') {
modifier *= 1000000;
} else if (c == 'b') {
modifier *= 1000000000;
}
}
total += number * modifier;
return total;
}
private static String bitrateToString(int bitrate) {
if (bitrate >= 1000000000 && bitrate == (bitrate/1000000000)*1000000000) {
return (bitrate/1000000000) + "b";
} else if (bitrate >= 1000000 && bitrate == (bitrate/1000000)*1000000) {
return (bitrate/1000000) + "m";
} else if (bitrate >= 1000 && bitrate == (bitrate/1000)*1000) {
return (bitrate/1000) + "k";
} else {
return String.valueOf(bitrate);
}
}
public static void open() {
open = true;
EditorState editorState = EditorStateCache.getCurrent();
if (editorState != null && editorState.exportStartTicks >= 0) {
startEndTick[0] = editorState.exportStartTicks;
} else {
startEndTick[0] = 0;
}
if (editorState != null && editorState.exportEndTicks >= 0) {
startEndTick[1] = editorState.exportEndTicks;
} else {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
startEndTick[1] = startEndTick[0] + 100;
} else {
startEndTick[1] = replayServer.getTotalReplayTicks();
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
public class VisualsWindow {
private static final float[] floatBuffer = new float[]{0};
private static final int[] intBuffer = new int[]{0};
public static void render() {
if (ImGui.begin("Visuals")) {
ImGuiHelper.separatorWithText("GUI");
if (ImGui.checkbox("Chat", ReplayVisuals.showChat)) {
ReplayVisuals.showChat = !ReplayVisuals.showChat;
}
if (ImGui.checkbox("Boss Bar", ReplayVisuals.showBossBar)) {
ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar;
}
if (ImGui.checkbox("Title Text", ReplayVisuals.showTitleText)) {
ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText;
}
if (ImGui.checkbox("Scoreboard", ReplayVisuals.showScoreboard)) {
ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard;
}
if (ImGui.checkbox("Action Bar", ReplayVisuals.showActionBar)) {
ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar;
}
ImGuiHelper.separatorWithText("World");
if (ImGui.checkbox("Render Blocks", ReplayVisuals.renderBlocks)) {
ReplayVisuals.renderBlocks = !ReplayVisuals.renderBlocks;
}
if (ImGui.checkbox("Render Entities", ReplayVisuals.renderEntities)) {
ReplayVisuals.renderEntities = !ReplayVisuals.renderEntities;
}
if (ImGui.checkbox("Render Players", ReplayVisuals.renderPlayers)) {
ReplayVisuals.renderPlayers = !ReplayVisuals.renderPlayers;
}
if (ImGui.checkbox("Render Particles", ReplayVisuals.renderParticles)) {
ReplayVisuals.renderParticles = !ReplayVisuals.renderParticles;
}
if (ImGui.checkbox("Render Sky", ReplayVisuals.renderSky)) {
ReplayVisuals.renderSky = !ReplayVisuals.renderSky;
}
if (ImGui.checkbox("Render Nametags", ReplayVisuals.renderNametags)) {
ReplayVisuals.renderNametags = !ReplayVisuals.renderNametags;
}
ImGuiHelper.separatorWithText("Overrides");
// Fog distance
if (ImGui.checkbox("Override Fog", ReplayVisuals.overrideFog)) {
ReplayVisuals.overrideFog = !ReplayVisuals.overrideFog;
}
if (ReplayVisuals.overrideFog) {
floatBuffer[0] = ReplayVisuals.overrideFogStart;
if (ImGui.sliderFloat("Start", floatBuffer, 0.0f, 512.0f)) {
ReplayVisuals.overrideFogStart = floatBuffer[0];
}
floatBuffer[0] = ReplayVisuals.overrideFogEnd;
if (ImGui.sliderFloat("End", floatBuffer, 0.0f, 512.0f)) {
ReplayVisuals.overrideFogEnd = floatBuffer[0];
}
}
// FOV
if (ImGui.checkbox("Override FOV", ReplayVisuals.overrideFov)) {
ReplayVisuals.overrideFov = !ReplayVisuals.overrideFov;
}
if (ReplayVisuals.overrideFov) {
floatBuffer[0] = ReplayVisuals.overrideFovAmount;
if (ImGui.sliderFloat("FOV", floatBuffer, 0.1f, 110.0f, "%.1f")) {
ReplayVisuals.setFov(floatBuffer[0]);
}
}
// Time
if (ImGui.checkbox("Override Time", ReplayVisuals.overrideTimeOfDay >= 0)) {
if (ReplayVisuals.overrideTimeOfDay >= 0) {
ReplayVisuals.overrideTimeOfDay = -1;
} else {
ReplayVisuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000);
}
}
if (ReplayVisuals.overrideTimeOfDay >= 0) {
intBuffer[0] = (int) ReplayVisuals.overrideTimeOfDay;
if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) {
ReplayVisuals.overrideTimeOfDay = intBuffer[0];
}
}
ImGuiHelper.separatorWithText("Other");
if (ImGui.checkbox("Rule of Thirds Guide", ReplayVisuals.ruleOfThirdsGuide)) {
ReplayVisuals.ruleOfThirdsGuide = !ReplayVisuals.ruleOfThirdsGuide;
}
if (ImGui.checkbox("Center Guide", ReplayVisuals.centerGuide)) {
ReplayVisuals.centerGuide = !ReplayVisuals.centerGuide;
}
ReplayVisuals.sizing = ImGuiHelper.enumCombo("Sizing", ReplayVisuals.sizing);
if (ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) {
ReplayVisuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", ReplayVisuals.changeAspectRatio);
}
}
ImGui.end();
}
}
@@ -0,0 +1,11 @@
package com.moulberry.flashback.exception;
import net.minecraft.network.protocol.Packet;
public class UnsupportedPacketException extends RuntimeException {
public UnsupportedPacketException(Packet<?> packet) {
super("Packet " + packet.type().id() + " is not supported");
}
}
@@ -0,0 +1,205 @@
package com.moulberry.flashback.exporting;
import net.minecraft.client.Minecraft;
import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.util.nfd.NFDFilterItem;
import org.lwjgl.util.nfd.NativeFileDialog;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncFileDialogs {
private static CompletableFuture<String> currentSaveOrOpenFileDialog = null;
private static final ExecutorService dialogThread = Executors.newSingleThreadExecutor();
private static boolean initializedNfd = false;
public static boolean hasDialog() {
return currentSaveOrOpenFileDialog != null;
}
public static CompletableFuture<String> saveFileDialog(String defaultPath, String defaultName, String filterDescription, String... filters) {
if (hasDialog()) return CompletableFuture.completedFuture(null);
currentSaveOrOpenFileDialog = new CompletableFuture<>();
CompletableFuture<String> future = currentSaveOrOpenFileDialog;
boolean initializedNfd = AsyncFileDialogs.initializedNfd;
AsyncFileDialogs.initializedNfd = true;
Runnable runnable = () -> {
if (!initializedNfd) {
NativeFileDialog.NFD_Init();
}
try (MemoryStack stack = MemoryStack.stackPush()) {
PointerBuffer out = stack.callocPointer(1);
StringBuilder filterBuilder = new StringBuilder();
for (String filter : filters) {
if (!filterBuilder.isEmpty()) filterBuilder.append(",");
filterBuilder.append(filter(filter));
}
NFDFilterItem.Buffer filtersBuffer = NFDFilterItem.malloc(1);
filtersBuffer.get(0)
.name(stack.UTF8(filter(filterDescription)))
.spec(stack.UTF8(filterBuilder.toString()));
int result = NativeFileDialog.NFD_SaveDialog(out, filtersBuffer, filter(defaultPath), filter(defaultName));
if (result != NativeFileDialog.NFD_OKAY) {
currentSaveOrOpenFileDialog.complete(null);
currentSaveOrOpenFileDialog = null;
} else {
currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0));
currentSaveOrOpenFileDialog = null;
NativeFileDialog.NFD_FreePath(out.get(0));
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (currentSaveOrOpenFileDialog != null) {
currentSaveOrOpenFileDialog.complete(null);
currentSaveOrOpenFileDialog = null;
}
}
};
if (Minecraft.ON_OSX) {
// MacOS needs dialogs to be run from the main thread
Minecraft.getInstance().submit(runnable);
} else {
dialogThread.submit(runnable);
}
return future;
}
public static CompletableFuture<String> openFileDialog(String defaultPath, String filterDescription, String... filters) {
if (hasDialog()) return CompletableFuture.completedFuture(null);
currentSaveOrOpenFileDialog = new CompletableFuture<>();
CompletableFuture<String> future = currentSaveOrOpenFileDialog;
boolean initializedNfd = AsyncFileDialogs.initializedNfd;
AsyncFileDialogs.initializedNfd = true;
Runnable runnable = () -> {
if (!initializedNfd) {
NativeFileDialog.NFD_Init();
}
try (MemoryStack stack = MemoryStack.stackPush()) {
PointerBuffer out = stack.callocPointer(1);
StringBuilder filterBuilder = new StringBuilder();
for (String filter : filters) {
if (!filterBuilder.isEmpty()) filterBuilder.append(",");
filterBuilder.append(filter(filter));
}
NFDFilterItem.Buffer filtersBuffer = NFDFilterItem.malloc(1);
filtersBuffer.get(0)
.name(stack.UTF8(filter(filterDescription)))
.spec(stack.UTF8(filterBuilder.toString()));
int result = NativeFileDialog.NFD_OpenDialog(out, filtersBuffer, filter(defaultPath));
if (result != NativeFileDialog.NFD_OKAY) {
currentSaveOrOpenFileDialog.complete(null);
currentSaveOrOpenFileDialog = null;
} else {
currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0));
currentSaveOrOpenFileDialog = null;
NativeFileDialog.NFD_FreePath(out.get(0));
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (currentSaveOrOpenFileDialog != null) {
currentSaveOrOpenFileDialog.complete(null);
currentSaveOrOpenFileDialog = null;
}
}
};
if (Minecraft.ON_OSX) {
// MacOS needs dialogs to be run from the main thread
Minecraft.getInstance().submit(runnable);
} else {
dialogThread.submit(runnable);
}
return future;
}
public static CompletableFuture<String> openFolderDialog(String defaultPath) {
if (hasDialog()) return CompletableFuture.completedFuture(null);
currentSaveOrOpenFileDialog = new CompletableFuture<>();
CompletableFuture<String> future = currentSaveOrOpenFileDialog;
boolean initializedNfd = AsyncFileDialogs.initializedNfd;
AsyncFileDialogs.initializedNfd = true;
Runnable runnable = () -> {
if (!initializedNfd) {
NativeFileDialog.NFD_Init();
}
try (MemoryStack stack = MemoryStack.stackPush()) {
PointerBuffer out = stack.callocPointer(1);
int result = NativeFileDialog.NFD_PickFolder(out, filter(defaultPath));
if (result != NativeFileDialog.NFD_OKAY) {
currentSaveOrOpenFileDialog.complete(null);
currentSaveOrOpenFileDialog = null;
} else {
currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0));
currentSaveOrOpenFileDialog = null;
NativeFileDialog.NFD_FreePath(out.get(0));
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (currentSaveOrOpenFileDialog != null) {
currentSaveOrOpenFileDialog.complete(null);
currentSaveOrOpenFileDialog = null;
}
}
};
if (Minecraft.ON_OSX) {
// MacOS needs dialogs to be run from the main thread
Minecraft.getInstance().submit(runnable);
} else {
dialogThread.submit(runnable);
}
return future;
}
public static String filter(CharSequence in) {
return filterLT20(in.toString()
.replace("'", "")
.replace("\"", "")
.replace("$", "")
.replace("`", ""));
}
public static String filterLT20(CharSequence in) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
if (c >= 32 || c == '\n') builder.append(c);
}
return builder.toString();
}
}
@@ -0,0 +1,377 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.mixin.record.MixinFFmpegFrameRecorder;
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.avutil;
import org.bytedeco.ffmpeg.global.swscale;
import org.bytedeco.ffmpeg.swscale.SwsContext;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.PointerPointer;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.FFmpegLogCallback;
import org.bytedeco.javacv.Frame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import static org.bytedeco.ffmpeg.global.avutil.*;
import static org.bytedeco.ffmpeg.global.swscale.SWS_BILINEAR;
import static org.bytedeco.ffmpeg.global.swscale.sws_freeContext;
public class AsyncVideoEncoder implements AutoCloseable {
@Nullable
private final ArrayBlockingQueue<ImageFrame> rescaleQueue;
private final ArrayBlockingQueue<ImageFrame> encodeQueue;
@Nullable
private final ArrayBlockingQueue<Long> reusePictureData;
private final AtomicBoolean finishRescaleThread = new AtomicBoolean(false);
private final AtomicBoolean finishEncodeThread = new AtomicBoolean(false);
private final AtomicBoolean finishedWriting = new AtomicBoolean(false);
private final AtomicReference<Throwable> threadedError = new AtomicReference<>(null);
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 {
public void close() {
MemoryUtil.nmemFree(this.pointer);
}
}
public AsyncVideoEncoder(ExportSettings settings, String filename) {
int width = settings.resolutionX();
int height = settings.resolutionY();
final int maxResolutionArea = 3840 * 2160;
if (width*height > maxResolutionArea) {
double factor = (width*height) / (double) maxResolutionArea;
factor = Math.sqrt(factor);
width = (int) Math.floor(width / factor);
height = (int) Math.floor(height / factor);
}
int maxBitrate = Math.min(288_000_000, 5000 + (int) Math.ceil(width * height * settings.framerate()));
int bitrate;
if (settings.bitrate() <= 0) {
bitrate = maxBitrate;
} else {
bitrate = Math.min(settings.bitrate(), maxBitrate);
}
double fps = settings.framerate();
String extension = settings.container().extension();
try {
if (FabricLoader.getInstance().isDevelopmentEnvironment() || true) {
FFmpegLogCallback.set();
}
int dstPixelFormat = PixelFormatHelper.getBestPixelFormat(settings.encoder());
boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat;
final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
filename, width, height, 0);
recorder.setVideoBitrate(bitrate);
recorder.setVideoCodec(settings.codec().codecId());
recorder.setVideoCodecName(settings.encoder());
recorder.setFormat(extension);
recorder.setFrameRate(fps);
recorder.setPixelFormat(dstPixelFormat);
recorder.setGopSize((int) Math.ceil(fps * 2));
recorder.start();
this.encodeQueue = new ArrayBlockingQueue<>(needsRescale ? 24 : 32);
this.rescaleQueue = needsRescale ? new ArrayBlockingQueue<>(8) : null;
this.reusePictureData = needsRescale ? new ArrayBlockingQueue<>(32) : null;
Thread encodeThread = createEncodeThread(recorder);
if (needsRescale) {
Thread rescaleThread = createRescaleThread(width, height, dstPixelFormat);
rescaleThread.start();
}
encodeThread.start();
} catch (IOException e) {
throw SneakyThrow.sneakyThrow(e);
}
}
private @NotNull Thread createEncodeThread(FFmpegFrameRecorder recorder) {
Thread encodeThread = new Thread(() -> {
while (true) {
ImageFrame src;
try {
src = this.encodeQueue.poll(10, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw SneakyThrow.sneakyThrow(e);
}
try {
if (src == null) {
if (this.finishEncodeThread.get()) {
recorder.stop();
recorder.close();
this.finishedWriting.set(true);
return;
} else {
continue;
}
}
int size = src.height * src.stride * Frame.pixelSize(src.imageDepth);
ByteBuffer buffer = MemoryUtil.memByteBuffer(src.pointer, size);
recorder.recordImage(src.width, src.height, src.imageDepth, src.channels,
src.stride, src.pixelFormat, buffer);
if (this.reusePictureData != null) {
if (this.reusePictureData.offer(src.pointer)) { // try adding to the reuse queue, ignore if full
src = null; // don't deallocate
}
}
} catch (Throwable t) {
try {
recorder.release();
} catch (FFmpegFrameRecorder.Exception e) {
e.printStackTrace();
}
this.threadedError.set(t);
this.finishRescaleThread.set(true);
this.finishEncodeThread.set(true);
this.finishedWriting.set(true);
return;
} finally {
if (src != null) {
src.close();
}
}
}
});
encodeThread.setName("Video Encode Thread");
return encodeThread;
}
private Thread createRescaleThread(int dstWidth, int dstHeight, int dstPixelFormat) {
int dstSize = av_image_get_buffer_size(dstPixelFormat, dstWidth, dstHeight, 1);
int dstDepth = dstSize * 8 / dstWidth / dstHeight;
int dstChannels;
try (AVPixFmtDescriptor descriptor = av_pix_fmt_desc_get(dstPixelFormat)) {
dstChannels = descriptor.nb_components();
}
AVFrame picture = avutil.av_frame_alloc();
if (picture == null) {
throw new RuntimeException("av_frame_alloc() error: Could not allocate picture.");
}
AVFrame tmp_picture = avutil.av_frame_alloc();
if (tmp_picture == null) {
throw new RuntimeException("av_frame_alloc() error: Could not allocate tmp_picture.");
}
PointerPointer<AVFrame> tmp_picture_ptr = new PointerPointer<>(tmp_picture);
PointerPointer<AVFrame> picture_ptr = new PointerPointer<>(picture);
Thread scaleThread = new Thread(() -> {
SwsContext img_convert_ctx = null;
while (true) {
try (ImageFrame src = this.rescaleQueue.poll(10, TimeUnit.MILLISECONDS)) {
if (src == null) {
if (this.finishRescaleThread.get()) {
av_frame_free(picture);
av_frame_free(tmp_picture);
sws_freeContext(img_convert_ctx);
this.finishEncodeThread.set(true);
return;
} else {
continue;
}
}
img_convert_ctx = swscale.sws_getCachedContext(img_convert_ctx, src.width, src.height, src.pixelFormat,
dstWidth, dstHeight, dstPixelFormat, swscale.SWS_BILINEAR,
null, null, (DoublePointer) null);
if (img_convert_ctx == null) {
throw new RuntimeException("sws_getCachedContext() error: Cannot initialize the conversion context.");
}
BytePointer data = new BytePointer() {{
this.address = src.pointer;
this.position = 0;
this.limit = src.size;
this.capacity = src.size;
}};
Long tempPointerAddressLong = this.reusePictureData.poll();
if (tempPointerAddressLong == null) {
tempPointerAddressLong = MemoryUtil.nmemAlloc(dstSize);
if (tempPointerAddressLong == 0) {
throw new OutOfMemoryError();
}
}
// Bit of a hack to create a BytePointer for this library
long tempPointerAddress = tempPointerAddressLong;
BytePointer tempPointer = new BytePointer() {{
this.address = tempPointerAddress;
this.position = 0;
this.limit = dstSize;
this.capacity = dstSize;
}};
av_image_fill_arrays(tmp_picture_ptr, tmp_picture.linesize(), data, src.pixelFormat, src.width, src.height, 1);
av_image_fill_arrays(picture_ptr, picture.linesize(), tempPointer, dstPixelFormat, dstWidth, dstHeight, 1);
int step = src.stride * Math.abs(src.imageDepth) / 8;
tmp_picture.linesize(0, step);
tmp_picture.format(src.pixelFormat);
tmp_picture.width(src.width);
tmp_picture.height(src.height);
picture.format(dstPixelFormat);
picture.width(dstWidth);
picture.height(dstHeight);
swscale.sws_scale(img_convert_ctx, tmp_picture_ptr, tmp_picture.linesize(),
0, src.height, picture_ptr, picture.linesize());
this.encodeQueue.put(new ImageFrame(tempPointerAddress, dstSize, dstWidth, dstHeight, dstChannels, dstDepth,
dstWidth, dstPixelFormat));
} catch (Throwable t) {
try {
av_frame_free(picture);
av_frame_free(tmp_picture);
sws_freeContext(img_convert_ctx);
} catch (Exception e) {
e.printStackTrace();
}
this.threadedError.set(t);
this.finishRescaleThread.set(true);
this.finishEncodeThread.set(true);
this.finishedWriting.set(true);
return;
}
}
});
scaleThread.setName("Image Rescale Thread");
return scaleThread;
}
private void checkEncodeError(@Nullable AutoCloseable closeable) {
Throwable t = this.threadedError.get();
if (t != null) {
this.finishRescaleThread.set(true);
this.finishEncodeThread.set(true);
this.finishedWriting.set(true);
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
Flashback.LOGGER.error("Error while trying to close passed AutoClosable", e);
}
}
SneakyThrow.sneakyThrow(t);
}
}
public void encode(NativeImage src) {
checkEncodeError(src);
if (this.finishRescaleThread.get() || this.finishEncodeThread.get() || this.finishedWriting.get()) {
src.close();
throw new IllegalStateException("Cannot encode after finish()");
}
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);
if (this.rescaleQueue != null) {
this.rescaleQueue.put(imageFrame);
} else {
this.encodeQueue.put(imageFrame);
}
break;
} catch (InterruptedException ignored) {}
checkEncodeError(src);
}
}
public void finish() {
checkEncodeError(null);
if (this.rescaleQueue != null) {
while (!this.rescaleQueue.isEmpty()) {
checkEncodeError(null);
LockSupport.parkNanos("waiting for rescale queue to empty", 100000L);
}
}
while (!this.encodeQueue.isEmpty()) {
checkEncodeError(null);
LockSupport.parkNanos("waiting for encode queue to empty", 100000L);
}
this.finishRescaleThread.set(true);
if (this.rescaleQueue == null) {
this.finishEncodeThread.set(true);
}
while (!this.finishedWriting.get()) {
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
}
checkEncodeError(null);
}
@Override
public void close() {
if (this.rescaleQueue != null) {
for (ImageFrame src : this.rescaleQueue) {
src.close();
}
}
for (ImageFrame src : this.encodeQueue) {
src.close();
}
this.finishRescaleThread.set(true);
this.finishEncodeThread.set(true);
while (!this.finishedWriting.get()) {
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
}
if (this.reusePictureData != null) {
for (Long address : this.reusePictureData) {
if (address != 0) {
MemoryUtil.nmemFree(address);
}
}
}
}
}
@@ -0,0 +1,222 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import io.humble.ferry.Buffer;
import io.humble.ferry.JNIReference;
import io.humble.video.Codec;
import io.humble.video.Encoder;
import io.humble.video.MediaPacket;
import io.humble.video.MediaPicture;
import io.humble.video.MediaPictureResampler;
import io.humble.video.Muxer;
import io.humble.video.MuxerFormat;
import io.humble.video.PixelFormat;
import io.humble.video.Rational;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
public class AsyncVideoEncoder {
private final Muxer muxer;
private final Encoder encoder;
private final MediaPictureResampler resampler;
private final MediaPacket packet;
private final ArrayBlockingQueue<NativeImage> inputQueue;
private final AtomicBoolean shouldEnd = new AtomicBoolean(false);
private final AtomicBoolean finishedWriting = new AtomicBoolean(false);
public AsyncVideoEncoder(int fps) {
this.inputQueue = new ArrayBlockingQueue<>(32);
final Rational framerate = Rational.make(1, fps);
this.muxer = Muxer.make("new_output.mp4", null, "mp4");
final MuxerFormat format = this.muxer.getFormat();
Codec codec = Codec.findEncodingCodec(format.getDefaultVideoCodecId());
this.encoder = Encoder.make(codec);
this.encoder.setWidth(1920);
this.encoder.setHeight(1060);
final PixelFormat.Type pixelformat = PixelFormat.Type.PIX_FMT_YUV420P;
this.encoder.setPixelFormat(pixelformat);
this.encoder.setTimeBase(framerate);
if (format.getFlag(MuxerFormat.Flag.GLOBAL_HEADER)) {
this.encoder.setFlag(Encoder.Flag.FLAG_GLOBAL_HEADER, true);
}
this.encoder.open(null, null);
this.muxer.addNewStream(this.encoder);
try {
this.muxer.open(null, null);
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
this.resampler = MediaPictureResampler.make(
this.encoder.getWidth(), this.encoder.getHeight(), pixelformat,
this.encoder.getWidth(), this.encoder.getHeight(), PixelFormat.Type.PIX_FMT_RGBA, 0);
this.resampler.open();
this.packet = MediaPacket.make();
record Pictures(MediaPicture picture, MediaPicture pictureRgba) {}
ArrayBlockingQueue<Pictures> pictureInputQueue = new ArrayBlockingQueue<>(32);
ArrayBlockingQueue<Pictures> pictureOutputQueue = new ArrayBlockingQueue<>(32);
for (int i = 0; i < 32; i++) {
MediaPicture picture = MediaPicture.make(
this.encoder.getWidth(),
this.encoder.getHeight(),
pixelformat
);
picture.setTimeBase(framerate);
MediaPicture pictureRgba = MediaPicture.make(
this.encoder.getWidth(),
this.encoder.getHeight(),
PixelFormat.Type.PIX_FMT_RGBA
);
pictureInputQueue.add(new Pictures(picture, pictureRgba));
}
AtomicBoolean shouldEndEncoderThread = new AtomicBoolean(false);
new Thread(() -> {
int currentFrame = 0;
while (true) {
try {
Pictures pictures = pictureInputQueue.poll(10, TimeUnit.MILLISECONDS);
if (pictures == null) {
if (this.shouldEnd.get()) {
shouldEndEncoderThread.set(true);
return;
} else {
continue;
}
}
NativeImage src = this.inputQueue.poll(10, TimeUnit.MILLISECONDS);
if (src == null) {
if (this.shouldEnd.get()) {
shouldEndEncoderThread.set(true);
return;
} else {
pictureInputQueue.put(pictures);
continue;
}
}
final AtomicReference<JNIReference> ref = new AtomicReference<JNIReference>(
null);
Buffer buffer = pictures.pictureRgba.getData(0);
int size = pictures.pictureRgba.getDataPlaneSize(0);
ByteBuffer pictureByteBuffer = buffer.getByteBuffer(0,
size, ref);
buffer.delete();
pictureByteBuffer.order(ByteOrder.nativeOrder());
for (int pixel : src.getPixelsRGBA()) {
pictureByteBuffer.putInt(pixel);
}
src.close();
pictures.pictureRgba.setTimeStamp(currentFrame++);
pictures.pictureRgba.setComplete(true);
this.resampler.resample(pictures.picture, pictures.pictureRgba);
if (ref.get() != null) {
ref.get().delete();
}
pictureOutputQueue.put(pictures);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
while (true) {
try {
Pictures pictures = pictureOutputQueue.poll(10, TimeUnit.MILLISECONDS);
if (pictures == null) {
if (shouldEndEncoderThread.get()) {
do {
this.encoder.encode(this.packet, null);
if (this.packet.isComplete()) {
this.muxer.write(this.packet, false);
}
} while (this.packet.isComplete());
this.muxer.close();
this.muxer.delete();
this.encoder.delete();
this.resampler.delete();
this.packet.delete();
this.finishedWriting.set(true);
pictures = pictureInputQueue.poll();
while (pictures != null) {
pictures.picture.delete();
pictures.pictureRgba.delete();
pictures = pictureInputQueue.poll();
}
return;
} else {
continue;
}
}
do {
this.encoder.encode(this.packet, pictures.picture);
if (this.packet.isComplete()) {
this.muxer.write(this.packet, false);
}
} while (this.packet.isComplete());
if (shouldEndEncoderThread.get()) {
pictures.picture.delete();
pictures.pictureRgba.delete();
} else {
pictureInputQueue.put(pictures);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void encode(NativeImage src) {
while (true) {
try {
this.inputQueue.put(src);
return;
} catch (InterruptedException ignored) {}
}
}
public void finish() {
while (!this.inputQueue.isEmpty()) {
LockSupport.parkNanos("waiting for image queue to empty", 100000L);
}
this.shouldEnd.set(true);
while (!this.finishedWriting.get()) {
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
}
}
}
@@ -0,0 +1,479 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.pipeline.TextureTarget;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.platform.Window;
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.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.FogRenderer;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.client.sounds.SoundEngine;
import org.joml.Matrix4f;
import org.lwjgl.glfw.GLFW;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
public class ExportJob {
private final ExportSettings settings;
private boolean running = false;
private boolean shouldChangeFramebufferSize = false;
private long lastRenderMillis;
private long escapeCancelStartMillis = -1;
private long renderStartTime;
private boolean showingDebug = false;
private boolean pressedDebugKey = false;
private long serverTickTimeNanos = 0;
private long clientTickTimeNanos = 0;
private long renderTimeNanos = 0;
private long encodeTimeNanos = 0;
private long downloadTimeNanos = 0;
private final AtomicBoolean finishedServerTick = new AtomicBoolean(false);
public ExportJob(ExportSettings settings) {
this.settings = settings;
}
public boolean isRunning() {
return this.running;
}
public void onFinishedServerTick() {
this.finishedServerTick.set(true);
}
public boolean shouldChangeFramebufferSize() {
return this.running && this.shouldChangeFramebufferSize;
}
public int getWidth() {
return this.settings.resolutionX();
}
public int getHeight() {
return this.settings.resolutionY();
}
public void run() {
ReplayServer replayServer = Flashback.getReplayServer();
if (this.running || replayServer == null) {
throw new IllegalStateException("run() called twice");
}
this.running = true;
UUID uuid = UUID.randomUUID();
String tempFileName = "replay_export_temp/" + uuid + "." + this.settings.container().extension();
Path exportTempFile = Path.of(tempFileName);
Path exportTempFolder = exportTempFile.getParent();
TextureTarget infoRenderTarget = null;
try {
Files.createDirectories(exportTempFolder);
RenderTarget mainTarget = Minecraft.getInstance().mainRenderTarget;
infoRenderTarget = new TextureTarget(mainTarget.width, mainTarget.height, false, Minecraft.ON_OSX);
try (AsyncVideoEncoder encoder = new AsyncVideoEncoder(this.settings, tempFileName);
SaveableFramebufferQueue downloader = new SaveableFramebufferQueue(this.settings.resolutionX(), this.settings.resolutionY())) {
doExport(encoder, downloader, infoRenderTarget);
}
Files.move(exportTempFile, this.settings.output(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
this.running = false;
this.shouldChangeFramebufferSize = false;
Minecraft.getInstance().resizeDisplay();
try {
Files.deleteIfExists(exportTempFile);
} catch (IOException ignored) {}
try {
boolean empty;
try (var stream = Files.newDirectoryStream(exportTempFolder)) {
empty = !stream.iterator().hasNext();
}
if (empty) {
Files.deleteIfExists(exportTempFolder);
}
} catch (IOException ignored) {}
if (infoRenderTarget != null) {
infoRenderTarget.destroyBuffers();
}
}
}
private void doExport(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, TextureTarget infoRenderTarget) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
return;
}
this.setup(replayServer);
shouldChangeFramebufferSize = true;
Minecraft.getInstance().resizeDisplay();
double framesPerTick = this.settings.framerate() / 20.0;
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);
while (currentFrame <= totalFrames) {
double currentTickDouble = currentFrame / framesPerTick;
int currentTick = (int) currentTickDouble;
double partialTick = currentTickDouble - currentTick;
int targetServerTick = this.settings.startTick() + currentTick;
// Wait until server is on correct replay tick
long start = System.nanoTime();
this.setServerTickAndWait(replayServer, targetServerTick, false);
serverTickTimeNanos += System.nanoTime() - start;
// Tick client
while (clientTickCount < currentTick) {
start = System.nanoTime();
this.runClientTick();
clientTickTimeNanos += System.nanoTime() - start;
clientTickCount += 1;
}
long pauseScreenStart = System.currentTimeMillis();
while (Minecraft.getInstance().getOverlay() != null || Minecraft.getInstance().screen != null) {
this.runClientTick();
Window window = Minecraft.getInstance().getWindow();
RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget;
renderTarget.bindWrite(true);
RenderSystem.clear(16640, Minecraft.ON_OSX);
Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(0.0f, 0.0f), true);
renderTarget.unbindWrite();
this.shouldChangeFramebufferSize = false;
renderTarget.blitToScreen(window.getWidth(), window.getHeight(), false);
window.updateDisplay();
this.shouldChangeFramebufferSize = true;
LockSupport.parkNanos("waiting for pause overlay to disappear", 50_000_000L);
// Force remove screens/overlays after 5s/15s respectively
long currentTime = System.currentTimeMillis();
if (pauseScreenStart > currentTime) {
pauseScreenStart = currentTime;
}
if (currentTime - pauseScreenStart > 5000) {
Minecraft.getInstance().setScreen(null);
}
if (currentTime - pauseScreenStart > 15000) {
Minecraft.getInstance().setOverlay(null);
}
}
this.tryUnfreezeClient();
editorState.applyKeyframes(Minecraft.getInstance(), (float)(this.settings.startTick() + currentTickDouble));
RenderTarget oldTarget = Minecraft.getInstance().getMainRenderTarget();
SaveableFramebuffer saveable = downloader.take();
RenderTarget renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY());
Minecraft.getInstance().mainRenderTarget = renderTarget;
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.deltaTickResidual = (float) partialTick;
Minecraft.getInstance().timer.pausedDeltaTickResidual = (float) partialTick;
start = System.nanoTime();
Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(1 / (float) framesPerTick, (float) partialTick), true);
renderTimeNanos += System.nanoTime() - start;
renderTarget.unbindWrite();
Minecraft.getInstance().mainRenderTarget = oldTarget;
this.shouldChangeFramebufferSize = false;
boolean cancel = finishFrame(renderTarget, infoRenderTarget, currentFrame, totalFrames);
this.shouldChangeFramebufferSize = true;
submitDownloadedFrames(encoder, downloader, false);
downloader.startDownload(saveable);
if (cancel) {
break;
}
currentFrame += 1;
}
submitDownloadedFrames(encoder, downloader, true);
encoder.finish();
}
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
this.setServerTickAndWait(replayServer, currentTick, true);
this.runClientTick();
// Advance until tick is at start
while (currentTick < this.settings.startTick()) {
this.setServerTickAndWait(replayServer, currentTick, true);
this.runClientTick();
currentTick += 1;
}
// Ensured replay server is paused at startTick
this.setServerTickAndWait(replayServer, this.settings.startTick(), true);
this.runClientTick();
// Remove screen
minecraft.setScreen(null);
}
private void setServerTickAndWait(ReplayServer replayServer, int targetTick, boolean force) {
if (force || replayServer.getReplayTick() != targetTick) {
this.finishedServerTick.set(false);
replayServer.jumpToTick = targetTick;
replayServer.replayPaused = true;
replayServer.sendFinishedServerTick.set(true);
while (!this.finishedServerTick.compareAndExchange(true, false)) {
LockSupport.parkNanos("waiting for server thread", 100000L);
}
}
}
private void runClientTick() {
this.tryUnfreezeClient();
while (Minecraft.getInstance().pollTask()) {}
Minecraft.getInstance().tick();
this.tryUnfreezeClient();
}
private void tryUnfreezeClient() {
ClientLevel level = Minecraft.getInstance().level;
if (level != null) {
level.tickRateManager().setFrozen(false);
}
}
private void submitDownloadedFrames(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, boolean drain) {
NativeImage image;
while (true) {
long start = System.nanoTime();
image = downloader.finishDownload(drain);
downloadTimeNanos += System.nanoTime() - start;
if (image == null) {
break;
}
start = System.nanoTime();
encoder.encode(image);
encodeTimeNanos += System.nanoTime() - start;
}
}
private boolean finishFrame(RenderTarget framebuffer, RenderTarget infoRenderTarget, int currentFrame, int totalFrames) {
boolean cancel = false;
long currentTime = System.currentTimeMillis();
if (currentTime - this.lastRenderMillis > 1000/60 || currentFrame == totalFrames) {
Window window = Minecraft.getInstance().getWindow();
{
GlStateManager._colorMask(true, true, true, false);
GlStateManager._disableDepthTest();
GlStateManager._depthMask(false);
GlStateManager._viewport(0, 0, window.getWidth(), window.getHeight());
GlStateManager._disableBlend();
Minecraft minecraft = Minecraft.getInstance();
ShaderInstance shaderInstance = Objects.requireNonNull(minecraft.gameRenderer.blitShader, "Blit shader not loaded");
shaderInstance.setSampler("DiffuseSampler", framebuffer.colorTextureId);
shaderInstance.apply();
BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN);
bufferBuilder.addVertex(0.0F, 0.0F, 0.0F);
bufferBuilder.addVertex(1.0F, 0.0F, 0.0F);
bufferBuilder.addVertex(1.0F, 1.0F, 0.0F);
bufferBuilder.addVertex(0.0F, 1.0F, 0.0F);
BufferUploader.draw(bufferBuilder.buildOrThrow());
shaderInstance.clear();
GlStateManager._depthMask(true);
GlStateManager._colorMask(true, true, true, true);
}
this.lastRenderMillis = currentTime;
Font font = Minecraft.getInstance().font;
var bufferSource = Minecraft.getInstance().renderBuffers().bufferSource();
bufferSource.endBatch();
infoRenderTarget.bindWrite(true);
RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0f);
RenderSystem.clear(16640, Minecraft.ON_OSX);
int guiScale = 4;
int scaledWidth = (int) Math.ceil(infoRenderTarget.width / guiScale);
int scaledHeight = (int) Math.ceil(infoRenderTarget.height / guiScale);
Matrix4f matrix4f = new Matrix4f().setOrtho(0.0f, scaledWidth, scaledHeight, 0.0f, 1000.0f, 21000.0f);
RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z);
Matrix4f matrix = new Matrix4f();
matrix.translate(0.0f, 0.0f, -11000.0f);
RenderSystem.disableDepthTest();
List<String> lines = new ArrayList<>();
lines.add("Exported Frames: " + currentFrame + "/" + totalFrames);
long elapsed = currentTime - this.renderStartTime;
lines.add("Time elapsed: " + formatTime(elapsed));
if (currentFrame >= this.settings.framerate()) {
long estimatedRemaining = (currentTime - this.renderStartTime) * (totalFrames - currentFrame) / currentFrame;
lines.add("Estimated time remaining: " + formatTime(estimatedRemaining));
}
lines.add("");
boolean debugPressed = GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_F3) != GLFW.GLFW_RELEASE;
if (pressedDebugKey != debugPressed) {
pressedDebugKey = debugPressed;
if (pressedDebugKey) {
showingDebug = !showingDebug;
}
}
if (showingDebug) {
lines.add("ST: " + serverTickTimeNanos/1000000 + ", CT: " + clientTickTimeNanos/1000000);
lines.add("RT: " + renderTimeNanos/1000000 + ", ET: " + encodeTimeNanos/1000000);
lines.add("DT: " + downloadTimeNanos/1000000);
} else {
lines.add("Press [F3] to show debug info");
}
lines.add("");
if (currentFrame == totalFrames) {
lines.add("Saving...");
} else if (GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_ESCAPE) != GLFW.GLFW_RELEASE) {
long current = System.currentTimeMillis();
if (this.escapeCancelStartMillis <= 0 || current < this.escapeCancelStartMillis) {
this.escapeCancelStartMillis = current;
}
if (current - this.escapeCancelStartMillis > 3000) {
cancel = true;
lines.add("Saving...");
} else {
long remainingSeconds = 3 - (current - this.escapeCancelStartMillis) / 1000;
lines.add("Hold [ESC] to cancel (" + remainingSeconds + "s)");
}
} else {
lines.add("Hold [ESC] to cancel");
this.escapeCancelStartMillis = -1;
}
int x = scaledWidth / 2;
int y = scaledHeight / 2 - font.lineHeight * (lines.size() + 1)/2;
for (String line : lines) {
if (line.isEmpty()) {
y += font.lineHeight / 2 + 1;
} else {
font.drawInBatch(line, x - font.width(line)/2f, y,
-1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0);
y += font.lineHeight;
}
}
bufferSource.endBatch();
RenderSystem.enableDepthTest();
infoRenderTarget.unbindWrite();
RenderSystem.defaultBlendFunc();
RenderSystem.enableBlend();
infoRenderTarget.blitToScreen(window.getWidth(), window.getHeight(), false);
Minecraft.getInstance().getWindow().updateDisplay();
}
return cancel;
}
private String formatTime(long millis) {
long seconds = (millis / 1000) % 60;
long minutes = (millis / 1000 / 60) % 60;
long hours = millis / 1000 / 60 / 60;
if (hours > 0) {
return hours + "h " + minutes + "m " + seconds + "s";
} else if (minutes > 0) {
return minutes + "m " + seconds + "s";
} else {
return seconds + "s";
}
}
}
@@ -0,0 +1,11 @@
package com.moulberry.flashback.exporting;
import com.moulberry.flashback.combo_options.VideoCodec;
import com.moulberry.flashback.combo_options.VideoContainer;
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) {
}
@@ -0,0 +1,13 @@
package com.moulberry.flashback.exporting;
import java.util.function.Consumer;
import java.util.function.Function;
public class FrexFlawlessFramesIntegration implements Consumer<Function<String, Consumer<Boolean>>> {
@Override
public void accept(Function<String, Consumer<Boolean>> flawlessFrames) {
PerfectFrames.frexFlawlessFrames.add(flawlessFrames.apply("flashback"));
}
}
@@ -0,0 +1,87 @@
package com.moulberry.flashback.exporting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.resources.SkinManager;
import java.util.*;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
public class PerfectFrames {
private static boolean isEnabled = false;
static List<Consumer<Boolean>> frexFlawlessFrames = new ArrayList<>();
private static final Set<UUID> ignoreSkinLoading = new HashSet<>();
public static void enable() {
isEnabled = true;
ignoreSkinLoading.clear();
for (Consumer<Boolean> frexFlawlessFramesConsumer : frexFlawlessFrames) {
frexFlawlessFramesConsumer.accept(true);
}
}
public static void disable() {
isEnabled = false;
ignoreSkinLoading.clear();
for (Consumer<Boolean> frexFlawlessFramesConsumer : frexFlawlessFrames) {
frexFlawlessFramesConsumer.accept(false);
}
}
public static boolean isEnabled() {
return isEnabled;
}
public static void waitUntilFrameReady() {
long start = System.currentTimeMillis();
while (!isFrameReady(start)) {
LockSupport.parkNanos("waiting for frame to be ready", 100000L);
while (Minecraft.getInstance().pollTask()) {}
}
}
private static boolean isFrameReady(long start) {
long current = System.currentTimeMillis();
boolean forceFrameReady = current - start > 15000;
ClientLevel level = Minecraft.getInstance().level;
SkinManager skinManager = Minecraft.getInstance().getSkinManager();
if (level != null) {
if (forceFrameReady) {
System.err.println("Waiting for skin loading took too long, ignoring...");
for (AbstractClientPlayer player : level.players()) {
if (player == Minecraft.getInstance().player) {
continue;
}
PlayerInfo playerInfo = player.getPlayerInfo();
if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) {
System.err.println("Took too long to load skin for " + player.getUUID());
ignoreSkinLoading.add(player.getUUID());
}
}
} else {
for (AbstractClientPlayer player : level.players()) {
if (player == Minecraft.getInstance().player) {
continue;
}
if (ignoreSkinLoading.contains(player.getUUID())) {
continue;
}
PlayerInfo playerInfo = player.getPlayerInfo();
if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) {
return false;
}
}
}
}
return true;
}
}
@@ -0,0 +1,71 @@
package com.moulberry.flashback.exporting;
import com.moulberry.flashback.Flashback;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import org.bytedeco.ffmpeg.avcodec.AVCodec;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.javacpp.IntPointer;
import java.util.HashMap;
import java.util.Map;
public class PixelFormatHelper {
private static final Map<String, Integer> bestPixelFormats = new HashMap<>();
public static int getBestPixelFormat(String codecName) {
if (bestPixelFormats.containsKey(codecName)) {
return bestPixelFormats.get(codecName);
}
int bestPixelFormat = calculateBestPixelFormat(codecName);
if (bestPixelFormat == avutil.AV_PIX_FMT_NONE) {
throw new RuntimeException("Unable to determine best alternate pixel format for " + codecName);
}
if (bestPixelFormat != avutil.AV_PIX_FMT_YUV420P) {
Flashback.LOGGER.info("Chose to use alternate pixel format {} for codec {}", pixelFormatToString(bestPixelFormat), codecName);
}
bestPixelFormats.put(codecName, bestPixelFormat);
return bestPixelFormat;
}
private static int calculateBestPixelFormat(String codecName) {
try (AVCodec codec = avcodec.avcodec_find_encoder_by_name(codecName)) {
IntList supportedFormats = new IntArrayList();
IntPointer pixFmts = codec.pix_fmts();
int index = 0;
while (true) {
int pixFmt = pixFmts.get(index);
if (pixFmt == -1) {
break;
}
if (pixFmt == avutil.AV_PIX_FMT_YUV420P) {
return avutil.AV_PIX_FMT_YUV420P;
}
supportedFormats.add(pixFmt);
index += 1;
}
supportedFormats.add(avutil.AV_PIX_FMT_NONE);
return avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), avutil.AV_PIX_FMT_BGRA, 0, new int[1]);
}
}
private static String pixelFormatToString(int pixelFormat) {
try (BytePointer name = avutil.av_get_pix_fmt_name(pixelFormat)) {
return name.getString();
} catch (Throwable ignored) {}
return "UNKNOWN(" + pixelFormat + ")";
}
}
@@ -0,0 +1,105 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.pipeline.MainTarget;
import com.mojang.blaze3d.platform.NativeImage;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryUtil;
import java.nio.ByteBuffer;
public class SaveableFramebuffer implements AutoCloseable {
private MainTarget framebuffer;
private int pboId;
private boolean isDownloading = false;
public SaveableFramebuffer() {
this.framebuffer = null;
this.pboId = -1;
}
public boolean isDownloading() {
return isDownloading;
}
public MainTarget getFramebuffer(int width, int height) {
if (this.isDownloading) {
throw new IllegalStateException("Can't get the framebuffer for rendering while still downloading");
}
if (this.framebuffer == null) {
this.framebuffer = new MainTarget(width, height);
}
return this.framebuffer;
}
public void startDownload(int width, int height) {
if (this.isDownloading) {
throw new IllegalStateException("Can't start downloading while already downloading");
}
this.isDownloading = true;
if (this.pboId == -1) {
this.pboId = GL30C.glGenBuffers();
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId);
GL30C.glBufferData(GL30C.GL_PIXEL_PACK_BUFFER, (long) width * height * 4, GL30C.GL_STREAM_READ);
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0);
}
this.framebuffer.bindWrite(true);
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId);
GL30C.glReadPixels(0, 0, width, height, GL30C.GL_RGBA, GL30C.GL_UNSIGNED_BYTE, 0);
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0);
this.framebuffer.unbindWrite();
}
public NativeImage finishDownload(int width, int height) {
if (!this.isDownloading) {
throw new IllegalStateException("Can't finish downloading before download has started");
}
this.isDownloading = false;
NativeImage nativeImage = new NativeImage(NativeImage.Format.RGBA, width, height, false);
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId);
ByteBuffer buffer = GL30C.glMapBuffer(GL30C.GL_PIXEL_PACK_BUFFER, GL30C.GL_READ_ONLY);
if (buffer == null) {
throw new IllegalStateException("OpenGL error occurred while mapping buffer");
}
// Copy bytes
MemoryUtil.memCopy(MemoryUtil.memAddress(buffer), nativeImage.pixels, nativeImage.size);
// for (int y = 0; y < nativeImage.getHeight(); ++y) {
// for (int x = 0; x < nativeImage.getWidth(); ++x) {
// int rgba = nativeImage.getPixelRGBA(x, y);
// nativeImage.setPixelRGBA(x, y, (rgba & 0xFFFFFF) | (80 << NativeImage.Format.RGBA.alphaOffset()));
// }
// }
nativeImage.flipY();
GL30C.glUnmapBuffer(GL30C.GL_PIXEL_PACK_BUFFER);
GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0);
return nativeImage;
}
public void close() {
if (this.framebuffer != null) {
this.framebuffer.destroyBuffers();
this.framebuffer = null;
}
if (this.pboId != -1) {
GL30C.glDeleteBuffers(this.pboId);
this.pboId = -1;
}
}
}
@@ -0,0 +1,68 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class SaveableFramebufferQueue implements AutoCloseable {
private final int width;
private final int height;
private static final int CAPACITY = 3;
private final List<SaveableFramebuffer> available = new ArrayList<>();
private final List<SaveableFramebuffer> waiting = new ArrayList<>();
public SaveableFramebufferQueue(int width, int height) {
this.width = width;
this.height = height;
for (int i = 0; i < CAPACITY; i++) {
this.available.add(new SaveableFramebuffer());
}
}
public SaveableFramebuffer take() {
if (this.available.isEmpty()) {
throw new IllegalStateException("No textures available!");
}
return this.available.removeFirst();
}
public void startDownload(SaveableFramebuffer texture) {
texture.startDownload(this.width, this.height);
this.waiting.add(texture);
}
public @Nullable NativeImage finishDownload(boolean drain) {
if (this.waiting.isEmpty()) {
return null;
}
if (!drain && !this.available.isEmpty()) {
return null;
}
SaveableFramebuffer texture = this.waiting.removeFirst();
NativeImage nativeImage = texture.finishDownload(this.width, this.height);
this.available.add(texture);
return nativeImage;
}
@Override
public void close() {
for (SaveableFramebuffer texture : this.waiting) {
texture.close();
}
for (SaveableFramebuffer texture : this.available) {
texture.close();
}
this.waiting.clear();
this.available.clear();
}
}
@@ -0,0 +1,11 @@
package com.moulberry.flashback.ext;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.MultiBufferSource;
public interface ItemInHandRendererExt {
void flashback$renderHandsWithItems(float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, AbstractClientPlayer localPlayer, int i);
}
@@ -0,0 +1,8 @@
package com.moulberry.flashback.ext;
public interface LevelChunkSectionExt {
int flashback$getCachedChunkId();
void flashback$setCachedChunkId(int id);
}
@@ -0,0 +1,16 @@
package com.moulberry.flashback.ext;
import net.minecraft.server.WorldStem;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.storage.LevelStorageSource;
import java.nio.file.Path;
import java.util.UUID;
public interface MinecraftExt {
void flashback$forceClientTick();
void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem, UUID playbackUUID, Path path);
float flashback$getLocalPlayerPartialTick();
}
@@ -0,0 +1,13 @@
package com.moulberry.flashback.ext;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener;
import net.minecraft.server.network.ConfigurationTask;
import java.util.List;
public interface ServerConfigurationPacketListenerImplExt {
void flashback$startConfiguration(List<Packet<? super ClientConfigurationPacketListener>> initialPackets, List<ConfigurationTask> tasks);
}
@@ -0,0 +1,13 @@
package com.moulberry.flashback.ext;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener;
import net.minecraft.server.network.ConfigurationTask;
import java.util.List;
public interface ServerGamePacketListenerImplExt {
void flashback$switchToConfigWithTasks(List<Packet<? super ClientConfigurationPacketListener>> initialPackets, List<ConfigurationTask> tasks);
}
@@ -0,0 +1,7 @@
package com.moulberry.flashback.ext;
public interface ThreadedLevelLightEngineExt {
void flashback$submitPost(int x, int z, Runnable runnable);
}
@@ -0,0 +1,312 @@
package com.moulberry.flashback.io;
import com.mojang.blaze3d.platform.NativeImage;
import com.moulberry.flashback.CachedChunkPacket;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.TempFolderProvider;
import com.moulberry.flashback.action.ActionConfigurationPacket;
import com.moulberry.flashback.action.ActionCreateLocalPlayer;
import com.moulberry.flashback.action.ActionGamePacket;
import com.moulberry.flashback.action.ActionLevelChunkCached;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.network.protocol.game.ClientboundLoginPacket;
import java.io.IOException;
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;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
public class AsyncReplaySaver {
private final ArrayBlockingQueue<Consumer<ReplayWriter>> tasks = new ArrayBlockingQueue<>(256);
private final AtomicReference<Throwable> error = new AtomicReference<>(null);
private final AtomicBoolean shouldStop = new AtomicBoolean(false);
private final AtomicBoolean hasStopped = new AtomicBoolean(false);
private final Path recordFolder;
public AsyncReplaySaver(RegistryAccess registryAccess) {
this.recordFolder = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.RECORDING, UUID.randomUUID());
ReplayWriter replayWriter = new ReplayWriter(registryAccess);
new Thread(() -> {
while (true) {
try {
Consumer<ReplayWriter> task = this.tasks.poll(10, TimeUnit.MILLISECONDS);
if (task == null) {
if (this.shouldStop.get()) {
this.hasStopped.set(true);
return;
} else {
continue;
}
}
task.accept(replayWriter);
} catch (Throwable t) {
this.error.set(t);
this.hasStopped.set(true);
return;
}
}
}).start();
}
public void submit(Consumer<ReplayWriter> consumer) {
this.checkForError();
if (this.hasStopped.get()) {
throw new IllegalStateException("Cannot submit task to AsyncReplayWriter that has already stopped");
}
while (true) {
try {
this.tasks.put(consumer);
break;
} catch (InterruptedException ignored) {}
}
}
private final Int2ObjectMap<List<CachedChunkPacket>> cachedChunkPackets = new Int2ObjectOpenHashMap<>();
private int totalWrittenChunkPackets = 0;
public void writeGamePackets(StreamCodec<ByteBuf, Packet<? super ClientGamePacketListener>> gamePacketCodec,
List<Packet<? super ClientGamePacketListener>> packets) {
List<Packet<? super ClientGamePacketListener>> packetCopy = new ArrayList<>(packets);
this.submit(writer -> {
RegistryFriendlyByteBuf chunkCacheOutput = null;
FriendlyByteBuf customPayloadTempBuffer = null;
for (Packet<? super ClientGamePacketListener> packet : packetCopy) {
if (packet instanceof ClientboundLevelChunkWithLightPacket levelChunkPacket) {
int index = -1;
CachedChunkPacket cachedChunkPacket = new CachedChunkPacket(levelChunkPacket, -1);
int hashCode = cachedChunkPacket.hashCode();
boolean add = true;
List<CachedChunkPacket> cached = this.cachedChunkPackets.get(hashCode);
if (cached == null) {
cached = new ArrayList<>();
this.cachedChunkPackets.put(hashCode, cached);
} else {
for (CachedChunkPacket existingChunkPacket : cached) {
if (existingChunkPacket.equals(cachedChunkPacket)) {
add = false;
index = existingChunkPacket.index;
break;
}
}
}
if (add) {
if (chunkCacheOutput == null) {
chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), writer.registryAccess());
}
// Write placeholder value for size
int startWriterIndex = chunkCacheOutput.writerIndex();
chunkCacheOutput.writeInt(-1);
// Write chunk packet
gamePacketCodec.encode(chunkCacheOutput, packet);
int endWriterIndex = chunkCacheOutput.writerIndex();
// Write real size value
int size = endWriterIndex - startWriterIndex - 4;
chunkCacheOutput.writerIndex(startWriterIndex);
chunkCacheOutput.writeInt(size);
chunkCacheOutput.writerIndex(endWriterIndex);
index = this.totalWrittenChunkPackets;
this.totalWrittenChunkPackets += 1;
cachedChunkPacket.index = index;
cached.add(cachedChunkPacket);
}
writer.startAction(ActionLevelChunkCached.INSTANCE);
writer.friendlyByteBuf().writeVarInt(index);
writer.finishAction(ActionLevelChunkCached.INSTANCE);
continue;
}
if (packet instanceof ClientboundCustomPayloadPacket) {
// Some mods might throw errors when encoding packets, so this
// attempts to encode the packet before starting the action
try {
if (customPayloadTempBuffer == null) {
customPayloadTempBuffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), writer.registryAccess());
}
customPayloadTempBuffer.clear();
gamePacketCodec.encode(customPayloadTempBuffer, packet);
writer.startAction(ActionGamePacket.INSTANCE);
writer.friendlyByteBuf().writeBytes(customPayloadTempBuffer);
writer.finishAction(ActionGamePacket.INSTANCE);
} catch (Exception ignored) {}
} else {
writer.startAction(ActionGamePacket.INSTANCE);
gamePacketCodec.encode(writer.friendlyByteBuf(), packet);
writer.finishAction(ActionGamePacket.INSTANCE);
}
if (packet instanceof ClientboundLoginPacket) {
LocalPlayer localPlayer = Minecraft.getInstance().player;
if (localPlayer != null) {
writer.startAction(ActionCreateLocalPlayer.INSTANCE);
RegistryFriendlyByteBuf registryFriendlyByteBuf = writer.friendlyByteBuf();
registryFriendlyByteBuf.writeUUID(localPlayer.getUUID());
registryFriendlyByteBuf.writeDouble(localPlayer.getX());
registryFriendlyByteBuf.writeDouble(localPlayer.getY());
registryFriendlyByteBuf.writeDouble(localPlayer.getZ());
registryFriendlyByteBuf.writeFloat(localPlayer.getXRot());
registryFriendlyByteBuf.writeFloat(localPlayer.getYRot());
registryFriendlyByteBuf.writeFloat(localPlayer.getYHeadRot());
registryFriendlyByteBuf.writeVec3(localPlayer.getDeltaMovement());
ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, localPlayer.getGameProfile());
registryFriendlyByteBuf.writeVarInt(Minecraft.getInstance().gameMode.getPlayerMode().getId());
writer.finishAction(ActionCreateLocalPlayer.INSTANCE);
}
}
}
if (chunkCacheOutput != null && chunkCacheOutput.writerIndex() > 0) {
try {
byte[] bytes = new byte[chunkCacheOutput.writerIndex()];
chunkCacheOutput.getBytes(0, bytes);
Path levelChunkCachePath = this.recordFolder.resolve("level_chunk_cache");
Files.write(levelChunkCachePath, bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC);
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
}
});
}
public void writeConfigurationPackets(StreamCodec<ByteBuf, Packet<? super ClientConfigurationPacketListener>> configurationPacketCodec,
List<Packet<? super ClientConfigurationPacketListener>> packets) {
List<Packet<? super ClientConfigurationPacketListener>> packetCopy = new ArrayList<>(packets);
this.submit(writer -> {
for (Packet<? super ClientConfigurationPacketListener> packet : packetCopy) {
writer.startAction(ActionConfigurationPacket.INSTANCE);
configurationPacketCodec.encode(writer.friendlyByteBuf(), packet);
writer.finishAction(ActionConfigurationPacket.INSTANCE);
}
});
}
public void writeIcon(NativeImage nativeImage) {
int width = nativeImage.getWidth();
int height = nativeImage.getHeight();
int x = 0;
int y = 0;
if (width > height) {
x = (width - height) / 2;
width = height;
} else {
y = (height - width) / 2;
height = width;
}
try (NativeImage scaledImage = new NativeImage(64, 64, false);){
nativeImage.resizeSubRectTo(x, y, width, height, scaledImage);
scaledImage.writeToFile(this.recordFolder.resolve("icon.png"));
} catch (IOException e) {
Flashback.LOGGER.warn("Couldn't save screenshot", e);
} finally {
nativeImage.close();
}
}
public void writeReplayChunk(String chunkName, String metadata) {
this.submit(writer -> {
try {
Path chunkFile = this.recordFolder.resolve(chunkName);
Files.write(chunkFile, writer.popBytes());
Path metaFile = this.recordFolder.resolve("metadata.json");
if (Files.exists(metaFile)) {
Files.move(metaFile, this.recordFolder.resolve("metadata.json.old"), StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
}
Files.writeString(metaFile, metadata);
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
});
}
private void waitForTasks() {
checkForError();
if (this.hasStopped.get()) {
throw new IllegalStateException("Cannot wait for tasks on AsyncReplayWriter that has already stopped");
}
while (!this.tasks.isEmpty()) {
checkForError();
LockSupport.parkNanos("waiting for async replay writer to finish tasks", 100000L);
}
}
public Path finish() {
this.waitForTasks();
this.shouldStop.set(true);
while (!this.hasStopped.get()) {
checkForError();
LockSupport.parkNanos("waiting for async replay writer to stop", 100000L);
}
checkForError();
return this.recordFolder;
}
private void checkForError() {
Throwable t = error.get();
if (t != null) {
SneakyThrow.sneakyThrow(t);
}
}
}
@@ -0,0 +1,112 @@
package com.moulberry.flashback.io;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.action.Action;
import com.moulberry.flashback.action.ActionRegistry;
import io.netty.buffer.ByteBuf;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
public class ReplayReader {
private final FriendlyByteBuf friendlyByteBuf;
private final int replaySnapshotOffset;
private final int replayActionsOffset;
private RegistryAccess registryAccess;
private Action lastAction = null;
private final Int2ObjectMap<Action> actions = new Int2ObjectOpenHashMap<>();
public ReplayReader(ByteBuf byteBuf, RegistryAccess registryAccess) {
this.friendlyByteBuf = new FriendlyByteBuf(byteBuf);
this.registryAccess = registryAccess;
int magic = this.friendlyByteBuf.readInt();
if (magic != Flashback.MAGIC) {
throw new RuntimeException("Invalid magic");
}
int actions = this.friendlyByteBuf.readVarInt();
for (int i = 0; i < actions; i++) {
ResourceLocation actionName = this.friendlyByteBuf.readResourceLocation();
Action action = ActionRegistry.getAction(actionName);
if (action == null) {
throw new RuntimeException("Missing action: " + actionName);
} else {
this.actions.put(this.actions.size(), action);
}
}
int snapshotSize = this.friendlyByteBuf.readInt();
this.replaySnapshotOffset = this.friendlyByteBuf.readerIndex();
this.friendlyByteBuf.skipBytes(snapshotSize);
this.replayActionsOffset = this.friendlyByteBuf.readerIndex();
}
public void changeRegistryAccess(RegistryAccess registryAccess) {
this.registryAccess = registryAccess;
}
public void resetToStart() {
this.friendlyByteBuf.readerIndex(this.replayActionsOffset);
}
public void handleSnapshot(ReplayServer replayServer) {
this.friendlyByteBuf.readerIndex(this.replaySnapshotOffset);
replayServer.isProcessingSnapshot = true;
while (this.friendlyByteBuf.readerIndex() < this.replayActionsOffset) {
int id = this.friendlyByteBuf.readVarInt();
Action action = this.actions.get(id);
if (action == null) {
throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name());
}
this.lastAction = action;
int size = this.friendlyByteBuf.readInt();
ByteBuf slice = this.friendlyByteBuf.readSlice(size);
RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess);
action.handle(replayServer, registryFriendlyByteBuf);
if (slice.readerIndex() < size) {
throw new RuntimeException("Action " + this.lastAction.name() + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex());
}
}
replayServer.isProcessingSnapshot = false;
}
public boolean handleNextAction(ReplayServer replayServer) {
if (this.friendlyByteBuf.readerIndex() >= this.friendlyByteBuf.writerIndex()) {
return false;
}
if (this.friendlyByteBuf.readerIndex() < this.replayActionsOffset) {
this.friendlyByteBuf.readerIndex(this.replayActionsOffset);
}
int id = this.friendlyByteBuf.readVarInt();
Action action = this.actions.get(id);
if (action == null) {
throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name());
}
this.lastAction = action;
int size = this.friendlyByteBuf.readInt();
ByteBuf slice = this.friendlyByteBuf.readSlice(size);
RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess);
action.handle(replayServer, registryFriendlyByteBuf);
if (slice.readerIndex() < size) {
throw new RuntimeException("Action " + this.lastAction.name() + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex());
}
return true;
}
}
@@ -0,0 +1,179 @@
package com.moulberry.flashback.io;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.action.Action;
import com.moulberry.flashback.action.ActionRegistry;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.RegistryFriendlyByteBuf;
import java.util.List;
import java.util.Objects;
public class ReplayWriter {
private final ByteBuf dataBufferInner;
private RegistryFriendlyByteBuf dataBuffer;
private Reference2IntMap<Action> registeredActions;
private Action writingAction = null;
private RegistryAccess registryAccess;
private int snapshotSizeWriterIndex = -1;
private int actionSizeWriterIndex = -1;
private static final int STATE_EMPTY = 0;
private static final int STATE_WRITING_SNAPSHOT = 1;
private static final int STATE_WRITING_DATA = 2;
private int state = STATE_EMPTY;
public ReplayWriter(RegistryAccess registryAccess) {
this.dataBufferInner = Unpooled.buffer();
this.dataBuffer = new RegistryFriendlyByteBuf(this.dataBufferInner, registryAccess);
this.registryAccess = registryAccess;
this.writeHeader();
}
private void writeHeader() {
this.registeredActions = new Reference2IntOpenHashMap<>();
this.registeredActions.defaultReturnValue(-1);
// Reset to start
this.dataBuffer.writerIndex(0);
// Magic
this.dataBuffer.writeInt(Flashback.MAGIC);
// Actions
List<Action> actions = ActionRegistry.getActions();
this.dataBuffer.writeVarInt(actions.size());
for (Action action : ActionRegistry.getActions()) {
this.dataBuffer.writeResourceLocation(action.name());
this.registeredActions.put(action, this.registeredActions.size());
}
this.state = STATE_EMPTY;
}
public void setRegistryAccess(RegistryAccess registryAccess) {
RegistryFriendlyByteBuf newDataBuffer = new RegistryFriendlyByteBuf(this.dataBufferInner, registryAccess);
newDataBuffer.writerIndex(this.dataBuffer.writerIndex());
newDataBuffer.readerIndex(this.dataBuffer.readerIndex());
this.dataBuffer = newDataBuffer;
this.registryAccess = registryAccess;
}
public void startSnapshot() {
if (this.state == STATE_EMPTY) {
this.state = STATE_WRITING_SNAPSHOT;
this.snapshotSizeWriterIndex = this.dataBuffer.writerIndex();
this.dataBuffer.writeInt(0);
} else {
throw new IllegalStateException("Can only start snapshot in STATE_EMPTY");
}
}
public void endSnapshot() {
if (this.state == STATE_WRITING_SNAPSHOT) {
this.state = STATE_WRITING_DATA;
if (this.snapshotSizeWriterIndex < 0) {
throw new IllegalStateException("Snapshot size index wasn't set (" + this.snapshotSizeWriterIndex + ")");
}
int endPosition = this.dataBuffer.writerIndex();
int written = this.dataBuffer.writerIndex() - this.snapshotSizeWriterIndex - 4;
this.dataBuffer.writerIndex(this.snapshotSizeWriterIndex);
this.dataBuffer.writeInt(written);
this.dataBuffer.writerIndex(endPosition);
this.snapshotSizeWriterIndex = -1;
} else {
throw new IllegalStateException("Can only end snapshot in STATE_WRITING_SNAPSHOT");
}
}
public void startAndFinishAction(Action action) {
Objects.requireNonNull(action);
if (this.writingAction != null) {
throw new RuntimeException("startAndFinishAction() called while still writing " + action.name());
}
int id = this.registeredActions.getInt(action);
if (id >= 0) {
this.dataBuffer.writeVarInt(id);
} else {
throw new RuntimeException("Unknown action: " + action.name());
}
this.dataBuffer.writeInt(0);
this.actionSizeWriterIndex = -1;
}
public void startAction(Action action) {
Objects.requireNonNull(action);
if (this.writingAction != null) {
throw new RuntimeException("startAction() called while still writing " + action.name());
}
this.writingAction = action;
int id = this.registeredActions.getInt(action);
if (id >= 0) {
this.dataBuffer.writeVarInt(id);
} else {
throw new RuntimeException("Unknown action: " + action.name());
}
this.actionSizeWriterIndex = this.dataBuffer.writerIndex();
this.dataBuffer.writeInt(0);
}
public void finishAction(Action action) {
Objects.requireNonNull(action);
if (this.writingAction == null) {
throw new IllegalStateException("finishAction() called before startAction()");
}
if (this.writingAction != action) {
throw new IllegalStateException("finishAction() called with wrong action, expected " + this.writingAction.name() + ", got " + action.name());
}
this.writingAction = null;
if (this.actionSizeWriterIndex < 0) {
throw new IllegalStateException("Action size index wasn't set (" + this.actionSizeWriterIndex + ")");
}
int endPosition = this.dataBuffer.writerIndex();
int written = this.dataBuffer.writerIndex() - this.actionSizeWriterIndex - 4;
this.dataBuffer.writerIndex(this.actionSizeWriterIndex);
this.dataBuffer.writeInt(written);
this.dataBuffer.writerIndex(endPosition);
this.actionSizeWriterIndex = -1;
}
public RegistryFriendlyByteBuf friendlyByteBuf() {
return this.dataBuffer;
}
public RegistryAccess registryAccess() {
return this.registryAccess;
}
public byte[] popBytes() {
if (this.writingAction != null) {
throw new IllegalStateException("popBytes() called while still writing action " + this.writingAction.name());
}
byte[] replay = new byte[this.dataBuffer.writerIndex()];
this.dataBuffer.getBytes(0, replay);
this.writeHeader();
return replay;
}
}
@@ -0,0 +1,73 @@
package com.moulberry.flashback.keyframe;
import com.google.gson.*;
import com.moulberry.flashback.keyframe.impl.CameraKeyframe;
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.interpolation.InterpolationType;
import java.lang.reflect.Type;
public abstract class Keyframe<T> {
public final Class<T> operandClass;
private InterpolationType interpolationType = InterpolationType.SMOOTH;
public Keyframe(Class<T> operandClass) {
this.operandClass = operandClass;
}
public InterpolationType interpolationType() {
return interpolationType;
}
public void interpolationType(InterpolationType interpolationType) {
this.interpolationType = interpolationType;
}
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,
float lerpAmount, boolean lerpFromRight);
public static class TypeAdapter implements JsonSerializer<Keyframe<?>>, JsonDeserializer<Keyframe<?>> {
@Override
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) {
case "camera" -> context.deserialize(json, CameraKeyframe.class);
case "fov" -> context.deserialize(json, FOVKeyframe.class);
case "tickrate" -> context.deserialize(json, TickrateKeyframe.class);
case "time" -> context.deserialize(json, TimeOfDayKeyframe.class);
default -> throw new IllegalStateException("Unknown keyframe type: " + type);
};
keyframe.interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return keyframe;
}
@Override
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());
}
jsonObject.add("interpolation_type", context.serialize(src.interpolationType));
return jsonObject;
}
}
}
@@ -0,0 +1,18 @@
package com.moulberry.flashback.keyframe;
public enum KeyframeType {
CAMERA("Camera"),
FOV("FOV"),
SPEED("Speed"),
TIME_OF_DAY("Time of day");
public static final KeyframeType[] KEYFRAME_TYPES = values();
public final String name;
KeyframeType(String name) {
this.name = name;
}
}
@@ -0,0 +1,132 @@
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.spline.CatmullRom;
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;
public class CameraKeyframe extends Keyframe<Minecraft> {
private final Vector3f position;
private final Quaternionf quaternion;
public CameraKeyframe(Entity entity) {
this(entity.position().toVector3f(), new Quaternionf().rotationYXZ((float) Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), 0.0f));
}
public CameraKeyframe(Vector3f position, Quaternionf quaternion) {
super(Minecraft.class);
this.position = position;
this.quaternion = quaternion;
}
@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);
}
}
@Override
public void applyInterpolated(Minecraft minecraft, Keyframe genericOther, float amount) {
if (!(genericOther instanceof CameraKeyframe other)) {
this.apply(minecraft);
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);
}
}
@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;
}
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
// Calculate position
Vector3f position = CatmullRom.position(this.position,
((CameraKeyframe)p1).position, ((CameraKeyframe)p2).position,
((CameraKeyframe)p3).position, time1, time2, time3, amount);
float x = position.x;
float y = position.y;
float z = position.z;
// Calculate rotation
Quaternionf rotation = CatmullRom.rotation(this.quaternion,
((CameraKeyframe)p1).quaternion, ((CameraKeyframe)p2).quaternion,
((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);
Quaternionf linearQuaternion = Interpolation.linear(((CameraKeyframe)p1).quaternion, ((CameraKeyframe)p2).quaternion, lerpAmount);
if (lerpFromRight) {
x = Interpolation.linear(x, linearX, amount);
y = Interpolation.linear(y, linearY, amount);
z = Interpolation.linear(z, linearZ, amount);
rotation = Interpolation.linear(rotation, linearQuaternion, amount);
} else {
x = Interpolation.linear(linearX, x, amount);
y = Interpolation.linear(linearY, y, amount);
z = Interpolation.linear(linearZ, z, amount);
rotation = Interpolation.linear(linearQuaternion, rotation, amount);
}
}
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);
}
public static class TypeAdapter implements JsonSerializer<CameraKeyframe>, JsonDeserializer<CameraKeyframe> {
@Override
public CameraKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
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);
}
@Override
public JsonElement serialize(CameraKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.add("position", context.serialize(src.position));
jsonObject.add("rotation", context.serialize(src.quaternion));
return jsonObject;
}
}
}
@@ -0,0 +1,82 @@
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.spline.CatmullRom;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import java.lang.reflect.Type;
public class FOVKeyframe extends Keyframe<Minecraft> {
private final int fov;
public FOVKeyframe(int fov) {
super(Minecraft.class);
this.fov = fov;
}
@Override
public void apply(Minecraft minecraft) {
ReplayVisuals.setFov(fov);
}
@Override
public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof FOVKeyframe other)) {
this.apply(minecraft);
return;
}
float fov = Interpolation.linear(this.fov, other.fov, amount);
ReplayVisuals.setFov(fov);
}
@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;
}
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);
if (lerpAmount >= 0) {
float linearFov = Interpolation.linear(((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov, lerpAmount);
if (lerpFromRight) {
fov = Interpolation.linear(fov, linearFov, amount);
} else {
fov = Interpolation.linear(linearFov, fov, amount);
}
}
ReplayVisuals.setFov(fov);
}
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);
}
@Override
public JsonElement serialize(FOVKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("fov", src.fov);
return jsonObject;
}
}
}
@@ -0,0 +1,75 @@
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.spline.CatmullRom;
import java.lang.reflect.Type;
public class TickrateKeyframe extends Keyframe<ReplayServer> {
private float tickrate;
public TickrateKeyframe(float tickrate) {
super(ReplayServer.class);
this.tickrate = tickrate;
}
@Override
public void apply(ReplayServer replayServer) {
replayServer.desiredTickRate = this.tickrate;
}
@Override
public void applyInterpolated(ReplayServer replayServer, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof TickrateKeyframe other)) {
this.apply(replayServer);
return;
}
float tickrate = Interpolation.linear(this.tickrate, other.tickrate, amount);
replayServer.desiredTickRate = 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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
float tickrate = CatmullRom.value(this.tickrate,
((TickrateKeyframe)p1).tickrate, ((TickrateKeyframe)p2).tickrate,
((TickrateKeyframe)p3).tickrate, time1, time2, time3, amount);
if (lerpAmount >= 0) {
float linearTickrate = Interpolation.linear(((TickrateKeyframe)p1).tickrate, ((TickrateKeyframe)p2).tickrate, lerpAmount);
if (lerpFromRight) {
tickrate = Interpolation.linear(tickrate, linearTickrate, amount);
} else {
tickrate = Interpolation.linear(linearTickrate, tickrate, amount);
}
}
replayServer.desiredTickRate = tickrate;
}
public static class TypeAdapter implements JsonSerializer<TickrateKeyframe>, JsonDeserializer<TickrateKeyframe> {
@Override
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);
}
@Override
public JsonElement serialize(TickrateKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("tickrate", src.tickrate);
return jsonObject;
}
}
}
@@ -0,0 +1,89 @@
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.spline.CatmullRom;
import net.minecraft.client.Minecraft;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.GameRules;
import java.lang.reflect.Type;
public class TimeOfDayKeyframe extends Keyframe<Minecraft> {
private final int time;
public TimeOfDayKeyframe(int time) {
super(Minecraft.class);
this.time = time;
}
private void setTime(Minecraft minecraft, int time) {
time = time % 24000;
if (time < 0) {
time += 24000;
}
ReplayVisuals.overrideTimeOfDay = time;
}
@Override
public void apply(Minecraft minecraft) {
this.setTime(minecraft, this.time);
}
@Override
public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) {
if (!(otherGeneric instanceof TimeOfDayKeyframe other)) {
this.apply(minecraft);
return;
}
int time = Math.round(Interpolation.linear(this.time, other.time, amount));
this.setTime(minecraft, 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) {
float time1 = t1 - t0;
float time2 = t2 - t0;
float time3 = t3 - t0;
float timeOfDay = CatmullRom.value(this.time,
((TimeOfDayKeyframe)p1).time, ((TimeOfDayKeyframe)p2).time,
((TimeOfDayKeyframe)p3).time, time1, time2, time3, amount);
if (lerpAmount >= 0) {
float linearTimeOfDay = Interpolation.linear(((TimeOfDayKeyframe)p1).time, ((TimeOfDayKeyframe)p2).time, lerpAmount);
if (lerpFromRight) {
timeOfDay = Interpolation.linear(timeOfDay, linearTimeOfDay, amount);
} else {
timeOfDay = Interpolation.linear(linearTimeOfDay, timeOfDay, amount);
}
}
this.setTime(minecraft, Math.round(timeOfDay));
}
public static class TypeAdapter implements JsonSerializer<TimeOfDayKeyframe>, JsonDeserializer<TimeOfDayKeyframe> {
@Override
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);
}
@Override
public JsonElement serialize(TimeOfDayKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("time", src.time);
return jsonObject;
}
}
}
@@ -0,0 +1,33 @@
package com.moulberry.flashback.keyframe.interpolation;
import com.moulberry.flashback.keyframe.KeyframeType;
public enum InterpolationType {
SMOOTH(SidedInterpolationType.SMOOTH, SidedInterpolationType.SMOOTH),
LINEAR(SidedInterpolationType.LINEAR, SidedInterpolationType.LINEAR),
EASE_IN(SidedInterpolationType.EASE, SidedInterpolationType.LINEAR),
EASE_OUT(SidedInterpolationType.LINEAR, SidedInterpolationType.EASE),
EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE),
HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD);
public static final InterpolationType[] INTERPOLATION_TYPES = values();
public static String[] NAMES = new String[] {
"Smooth",
"Linear",
"Ease In (Linear Out)",
"Ease Out (Linear In)",
"Ease In/Out",
"Hold"
};
public SidedInterpolationType leftSide;
public SidedInterpolationType rightSide;
InterpolationType(SidedInterpolationType leftSide, SidedInterpolationType rightSide) {
this.leftSide = leftSide;
this.rightSide = rightSide;
}
}
@@ -0,0 +1,47 @@
package com.moulberry.flashback.keyframe.interpolation;
public enum SidedInterpolationType {
SMOOTH,
LINEAR,
EASE,
HOLD;
public static float interpolate(SidedInterpolationType left, SidedInterpolationType right, float amount) {
if (left == SidedInterpolationType.SMOOTH || right == SidedInterpolationType.SMOOTH) {
throw new IllegalArgumentException("SMOOTH not allowed");
}
if (left == SidedInterpolationType.HOLD) {
return 0.0f;
}
if (right == SidedInterpolationType.HOLD) {
right = left;
}
if (left == SidedInterpolationType.LINEAR) {
if (right == SidedInterpolationType.LINEAR) {
return amount;
} else if (right == SidedInterpolationType.EASE) {
// https://easings.net/#easeOutCubic
return 1 - (float) Math.pow(1 - amount, 3);
}
} else if (left == SidedInterpolationType.EASE) {
if (right == SidedInterpolationType.LINEAR) {
// https://easings.net/#easeInCubic
return amount * amount * amount;
} else if (right == SidedInterpolationType.EASE) {
// https://easings.net/#easeInOutCubic
if (amount < 0.5) {
return 4 * amount * amount * amount;
} else {
return 1 - (float) Math.pow(-2 * amount + 2, 3) / 2;
}
}
}
throw new IllegalArgumentException("Don't know how to interpolate " + left + " and " + right);
}
}
@@ -0,0 +1,31 @@
package com.moulberry.flashback.mixin;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.DebugScreenOverlay;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
@Mixin(value = DebugScreenOverlay.class, priority = 1100)
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()) {
ci.cancel();
}
}
@Inject(method = "getGameInformation", at = @At("RETURN"))
public void getGameInformation(CallbackInfoReturnable<List<String>> info) {
if (Flashback.RECORDER != null) {
info.getReturnValue().add(Flashback.RECORDER.getDebugString());
}
}
}
@@ -0,0 +1,125 @@
package com.moulberry.flashback.mixin;
import com.llamalad7.mixinextras.injector.v2.WrapWithCondition;
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.editor.ui.ReplayUI;
import com.moulberry.flashback.exporting.PerfectFrames;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.client.Camera;
import net.minecraft.client.CloudStatus;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.Options;
import net.minecraft.client.particle.ParticleEngine;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher;
import net.minecraft.client.renderer.chunk.RenderRegionCache;
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher;
import net.minecraft.client.renderer.culling.Frustum;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.entity.BlockEntity;
import org.jetbrains.annotations.Nullable;
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(value = LevelRenderer.class, priority = 1100)
public abstract class MixinLevelRenderer {
@Shadow @Final public ObjectArrayList<SectionRenderDispatcher.RenderSection> visibleSections;
@Shadow private @Nullable SectionRenderDispatcher sectionRenderDispatcher;
@Shadow @Final public SectionOcclusionGraph sectionOcclusionGraph;
@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;
ReplayUI.lastViewQuaternion = camera.rotation();
}
@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) {
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) {
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;
}
@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) {
if (entity instanceof Player) {
return ReplayVisuals.renderPlayers;
} else {
return 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 {
return CloudStatus.OFF;
}
}
@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;
}
@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;
}
@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"))
public void setupRender(LevelRenderer instance, Camera camera, Frustum frustum, boolean capturedFrustum, boolean isSpectator, Operation<Void> original) {
if (PerfectFrames.isEnabled()) {
boolean doCompile = true;
while (doCompile) {
doCompile = false;
int before = this.visibleSections.size();
original.call(instance, camera, frustum, capturedFrustum, isSpectator);
if (this.visibleSections.size() != before) {
doCompile = true;
}
RenderRegionCache renderRegionCache = new RenderRegionCache();
for (SectionRenderDispatcher.RenderSection renderSection : this.visibleSections) {
if (renderSection.isDirty()) {
this.sectionRenderDispatcher.rebuildSectionSync(renderSection, renderRegionCache);
renderSection.setNotDirty();
doCompile = true;
}
}
this.sectionRenderDispatcher.uploadAllPendingUploads();
}
} else {
original.call(instance, camera, frustum, capturedFrustum, isSpectator);
}
}
}
@@ -0,0 +1,353 @@
package com.moulberry.flashback.mixin;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
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.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
import com.moulberry.flashback.exporting.PerfectFrames;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.editor.ui.ReplayUI;
import it.unimi.dsi.fastutil.floats.FloatUnaryOperator;
import net.minecraft.CrashReport;
import net.minecraft.ReportedException;
import net.minecraft.Util;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.Minecraft;
import net.minecraft.client.User;
import net.minecraft.client.gui.screens.LevelLoadingScreen;
import net.minecraft.client.gui.screens.Overlay;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.main.GameConfig;
import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.chat.report.ReportEnvironment;
import net.minecraft.client.particle.ParticleEngine;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.Services;
import net.minecraft.server.WorldStem;
import net.minecraft.server.level.progress.ProcessorChunkProgressListener;
import net.minecraft.server.level.progress.StoringChunkProgressListener;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.players.GameProfileCache;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.TickRateManager;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.block.entity.SkullBlockEntity;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.phys.Vec3;
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.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.io.File;
import java.net.SocketAddress;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
@Mixin(Minecraft.class)
public abstract class MixinMinecraft implements MinecraftExt {
@Shadow
public abstract void disconnect();
@Shadow
@Final
private AtomicReference<StoringChunkProgressListener> progressListener;
@Shadow
@Final
private YggdrasilAuthenticationService authenticationService;
@Shadow
@Final
public File gameDirectory;
@Shadow
private @Nullable IntegratedServer singleplayerServer;
@Shadow
private boolean isLocalServer;
@Shadow
public abstract void updateReportEnvironment(ReportEnvironment reportEnvironment);
@Shadow
public abstract void setScreen(@Nullable Screen screen);
@Shadow
private ProfilerFiller profiler;
@Shadow
private @Nullable Overlay overlay;
@Shadow
protected abstract void runTick(boolean bl);
@Shadow
protected abstract void handleDelayedCrash();
@Shadow
public abstract User getUser();
@Shadow
private @Nullable Connection pendingConnection;
@Shadow
@Final
private Queue<Runnable> progressTasks;
@Shadow
@Nullable
public ClientLevel level;
@Shadow
@Nullable
public LocalPlayer player;
@Shadow
@Final
public ParticleEngine particleEngine;
@Shadow @Final public DeltaTracker.Timer timer;
@Inject(method="<init>", at=@At("RETURN"))
public void init(GameConfig gameConfig, CallbackInfo ci) {
ReplayUI.init();
}
@Inject(method = "pauseGame", at = @At("HEAD"), cancellable = true)
public void pauseGame(boolean bl, CallbackInfo ci) {
if (Flashback.EXPORT_JOB != null) {
ci.cancel();
}
}
@Inject(method = "renderNames", at = @At("HEAD"), cancellable = true)
private static void renderNames(CallbackInfoReturnable<Boolean> cir) {
if (!ReplayVisuals.renderNametags) {
cir.setReturnValue(false);
}
}
@Inject(method = "runTick", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V", shift = At.Shift.AFTER))
public void afterMainBlit(boolean bl, CallbackInfo ci) {
if (!RenderSystem.isOnRenderThread()) return;
ReplayUI.drawOverlay();
}
@Unique
private boolean inReplayLast = false;
@Inject(method = "tick", at = @At("RETURN"))
public void tick(CallbackInfo ci) {
if (Flashback.RECORDER != null) {
Flashback.RECORDER.endTick(false);
}
EditorStateCache.saveIfNeeded();
ReplayServer replayServer = Flashback.getReplayServer();
boolean inReplay = replayServer != null;
if (inReplay != inReplayLast) {
inReplayLast = inReplay;
if (inReplay) {
ReplayVisuals.setupReplay();
Minecraft.getInstance().options.hideGui = false;
} else {
ReplayVisuals.disable();
EditorStateCache.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)
public void getTickTargetMillis(float f, CallbackInfoReturnable<Float> cir) {
if (Flashback.isInReplay()) {
if (this.level == null) {
return;
}
TickRateManager tickRateManager = this.level.tickRateManager();
if (tickRateManager.runsNormally()) {
cir.setReturnValue(tickRateManager.millisecondsPerTick());
}
}
}
@Unique
private final DeltaTracker.Timer localPlayerTimer = new DeltaTracker.Timer(20.0f, 0, FloatUnaryOperator.identity());
@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 (Flashback.EXPORT_JOB != null && !ReplayUI.isActive()) {
try {
PerfectFrames.enable();
Flashback.EXPORT_JOB.run();
} finally {
PerfectFrames.disable();
Flashback.EXPORT_JOB = null;
}
}
if (Flashback.isInReplay()) {
int localPlayerTicks = localPlayerTimer.advanceTime(Util.getMillis(), runTick);
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);
}
}
}
}
@Override
public float flashback$getLocalPlayerPartialTick() {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) {
return this.timer.getGameTimeDeltaPartialTick(true);
}
return localPlayerTimer.getGameTimeDeltaPartialTick(true);
}
@Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", ordinal = 1), cancellable = true)
public void runTick_setErrorSection(boolean bl, CallbackInfo ci) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
return;
}
if (!replayServer.replayPaused) {
EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier);
editorState.applyKeyframes((Minecraft) (Object) this, replayServer.getPartialReplayTick());
}
if (!replayServer.doClientRendering()) {
ci.cancel();
}
}
@Override
public void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem,
UUID playbackUUID, Path path) {
this.disconnect();
this.progressListener.set(null);
Instant instant = Instant.now();
try {
// levelStorageAccess.saveDataTag((RegistryAccess)worldStem.registries().compositeAccess(), worldStem.worldData());
Services services = Services.create(this.authenticationService, this.gameDirectory);
services.profileCache().setExecutor((Executor)this);
SkullBlockEntity.setup(services, (Executor)this);
GameProfileCache.setUsesAuthentication(false);
this.singleplayerServer = MinecraftServer.spin(thread -> new ReplayServer(thread, (Minecraft) (Object) this,
levelStorageAccess, packRepository, stem, services, i -> {
StoringChunkProgressListener storingChunkProgressListener = StoringChunkProgressListener.createFromGameruleRadius(i);
this.progressListener.set(storingChunkProgressListener);
return ProcessorChunkProgressListener.createStarted(storingChunkProgressListener, this.progressTasks::add);
}, playbackUUID, path));
this.isLocalServer = true;
this.updateReportEnvironment(ReportEnvironment.local());
// this.quickPlayLog.setWorldData(QuickPlayLog.Type.SINGLEPLAYER, levelStorageAccess.getLevelId(), worldStem.worldData().getLevelName());
} catch (Throwable throwable) {
CrashReport crashReport = CrashReport.forThrowable(throwable, "Starting replay server");
// CrashReportCategory crashReportCategory = crashReport.addCategory("Starting integrated server");
// crashReportCategory.setDetail("Level ID", (Object)levelStorageAccess.getLevelId());
// crashReportCategory.setDetail("Level Name", () -> worldStem.worldData().getLevelName());
throw new ReportedException(crashReport);
}
while (this.progressListener.get() == null) {
Thread.yield();
}
LevelLoadingScreen levelLoadingScreen = new LevelLoadingScreen(this.progressListener.get());
this.setScreen(levelLoadingScreen);
this.profiler.push("waitForServer");
while (!this.singleplayerServer.isReady() || this.overlay != null) {
levelLoadingScreen.tick();
this.runTick(false);
try {
Thread.sleep(16L);
} catch (InterruptedException crashReport) {
// empty catch block
}
this.handleDelayedCrash();
}
this.profiler.pop();
Duration duration = Duration.between(instant, Instant.now());
SocketAddress socketAddress = this.singleplayerServer.getConnection().startMemoryChannel();
Connection connection = Connection.connectToLocalServer(socketAddress);
connection.initiateServerboundPlayConnection(socketAddress.toString(), 0, new ClientHandshakePacketListenerImpl(connection,
(Minecraft) (Object) this, null, null, false, duration, component -> {}, null));
connection.send(new ServerboundHelloPacket(this.getUser().getName(), this.getUser().getProfileId()));
this.pendingConnection = connection;
}
}
@@ -0,0 +1,32 @@
package com.moulberry.flashback.mixin;
import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw;
import com.moulberry.flashback.editor.ui.ReplayUI;
import net.minecraft.client.MouseHandler;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(MouseHandler.class)
public class MixinMouseHandler {
@Inject(method = "isMouseGrabbed", at=@At("HEAD"), cancellable = true)
public void isMouseGrabbed(CallbackInfoReturnable<Boolean> cir) {
if (ReplayUI.isActive()) {
cir.setReturnValue(ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME);
}
}
@Inject(method = "grabMouse", at=@At("HEAD"), cancellable = true)
public void grabMouse(CallbackInfo ci) {
if (ReplayUI.isActive()) ci.cancel();
}
@Inject(method = "releaseMouse", at=@At("HEAD"), cancellable = true)
public void releaseMouse(CallbackInfo ci) {
if (ReplayUI.isActive()) ci.cancel();
}
}
@@ -0,0 +1,28 @@
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.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) {
ReplayUI.setupMainViewport();
} else {
original.call(left, bottom, width, height);
}
}
}
@@ -0,0 +1,24 @@
package com.moulberry.flashback.mixin;
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;
@Mixin(ThreadedLevelLightEngine.class)
public abstract class MixinThreadedLevelLightEngine extends LevelLightEngine implements ThreadedLevelLightEngineExt {
@Shadow
protected abstract void addTask(int i, int j, ThreadedLevelLightEngine.TaskType taskType, Runnable runnable);
public MixinThreadedLevelLightEngine(LightChunkGetter lightChunkGetter, boolean bl, boolean bl2) {
super(lightChunkGetter, bl, bl2);
}
@Override
public void flashback$submitPost(int x, int z, Runnable runnable) {
this.addTask(x, z, ThreadedLevelLightEngine.TaskType.POST_UPDATE, runnable);
}
}
@@ -0,0 +1,154 @@
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.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.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(Window.class)
public abstract class MixinWindow {
@Shadow private int framebufferWidth;
@Shadow private int framebufferHeight;
@Shadow private int width;
@Shadow private int height;
@Shadow private double guiScale;
@Shadow private int guiScaledWidth;
@Shadow private int guiScaledHeight;
@Shadow
private int windowedWidth;
@Shadow
@Final
private long window;
@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));
}
}
@Inject(method = "getHeight", at=@At("HEAD"), cancellable = true)
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));
}
}
@Inject(method = "getScreenWidth", at=@At("HEAD"), cancellable = true)
public void getScreenWidth(CallbackInfoReturnable<Integer> cir) {
if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) {
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) {
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];
}
}
@Inject(method = "calculateScale", at=@At("HEAD"), cancellable = true)
public void calculateScale(int scale, boolean forceEven, CallbackInfoReturnable<Integer> cir) {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) {
int fbw = Flashback.EXPORT_JOB.getWidth();
int fbh = Flashback.EXPORT_JOB.getHeight();
int j = 1;
while (j != scale && j < fbw && j < fbh && fbw / (j + 1) >= 320 && fbh / (j + 1) >= 240) {
j++;
}
if (forceEven && j % 2 != 0) {
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);
int j = 1;
while (j != scale && j < fbw && j < fbh && fbw / (j + 1) >= 320 && fbh / (j + 1) >= 240) {
j++;
}
if (forceEven && j % 2 != 0) {
j++;
}
cir.setReturnValue(j);
}
}
@Inject(method = "setGuiScale", at=@At("HEAD"), cancellable = true)
public void setGuiScale(double d, CallbackInfo ci) {
if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) {
int fbw = Flashback.EXPORT_JOB.getWidth();
int fbh = Flashback.EXPORT_JOB.getHeight();
this.guiScale = d;
int i = (int)((double)fbw / d);
this.guiScaledWidth = (double)fbw / d > (double)i ? i + 1 : i;
int j = (int)((double)fbh / d);
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);
this.guiScale = d;
int i = (int)((double)fbw / d);
this.guiScaledWidth = (double)fbw / d > (double)i ? i + 1 : i;
int j = (int)((double)fbh / d);
this.guiScaledHeight = (double)fbh / d > (double)j ? j + 1 : j;
ci.cancel();
}
}
}
@@ -0,0 +1,29 @@
package com.moulberry.flashback.mixin.compat;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.editor.ui.ReplayUI;
import com.moulberry.mixinconstraints.annotations.IfModLoaded;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
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.CallbackInfoReturnable;
@IfModLoaded("axiom")
@Pseudo
@Mixin(targets = "com.moulberry.axiom.editor.EditorUI", remap = false)
public class MixinAxiomEditorUI {
@Shadow
private static boolean enabled;
@Inject(method = "isActiveInternal", at = @At("HEAD"), cancellable = true)
private static void isActiveInternal(CallbackInfoReturnable<Boolean> cir) {
if (ReplayUI.isActive() || Flashback.isInReplay()) {
enabled = false;
cir.setReturnValue(false);
}
}
}
@@ -0,0 +1,31 @@
package com.moulberry.flashback.mixin.compat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.mixinconstraints.annotations.IfModLoaded;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import net.minecraft.client.Camera;
import net.minecraft.client.renderer.RenderBuffers;
import net.minecraft.server.level.BlockDestructionProgress;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.SortedSet;
@IfModLoaded(value = "sodium", aliases = "embeddium")
@Pseudo
@Mixin(targets = {"net.caffeinemc.mods.sodium.client.render.SodiumWorldRenderer", "me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer"})
public class MixinSodiumWorldRenderer {
@Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;Lnet/minecraft/client/Camera;F)V",
at = @At("HEAD"), cancellable = true)
public void renderBlockEntities(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap<SortedSet<BlockDestructionProgress>> blockBreakingProgressions, Camera camera, float tickDelta, CallbackInfo ci) {
if (!ReplayVisuals.renderBlocks) {
ci.cancel();
}
}
}
@@ -0,0 +1,64 @@
package com.moulberry.flashback.mixin.packet_fix;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.gui.components.BossHealthOverlay;
import net.minecraft.client.gui.components.LerpingBossEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundBossEventPacket;
import net.minecraft.world.BossEvent;
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.Map;
import java.util.UUID;
@Mixin(BossHealthOverlay.class)
public class MixinBossHealthOverlay {
@Shadow
@Final
Map<UUID, LerpingBossEvent> events;
/**
* Prevent disconnection if boss state is incorrect
*/
@Inject(method = "update", at = @At("HEAD"), cancellable = true)
public void update(ClientboundBossEventPacket clientboundBossEventPacket, CallbackInfo ci) {
if (Flashback.isInReplay()) {
clientboundBossEventPacket.dispatch(new ClientboundBossEventPacket.Handler() {
@Override
public void updateProgress(UUID uuid, float f) {
if (!events.containsKey(uuid)) {
ci.cancel();
}
}
@Override
public void updateName(UUID uuid, Component component) {
if (!events.containsKey(uuid)) {
ci.cancel();
}
}
@Override
public void updateStyle(UUID uuid, BossEvent.BossBarColor bossBarColor, BossEvent.BossBarOverlay bossBarOverlay) {
if (!events.containsKey(uuid)) {
ci.cancel();
}
}
@Override
public void updateProperties(UUID uuid, boolean bl, boolean bl2, boolean bl3) {
if (!events.containsKey(uuid)) {
ci.cancel();
}
}
});
}
}
}
@@ -0,0 +1,29 @@
package com.moulberry.flashback.mixin.playback;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.renderer.entity.ArmorStandRenderer;
import net.minecraft.world.entity.decoration.ArmorStand;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ArmorStandRenderer.class)
public class MixinArmorStandRenderer {
/*
* Disable armor stand hit animation
* If the game time isn't updated, it'll just keep on playing it (even if it wasn't hit)
*/
@Inject(method = "setupRotations(Lnet/minecraft/world/entity/decoration/ArmorStand;Lcom/mojang/blaze3d/vertex/PoseStack;FFFF)V", at = @At("HEAD"), cancellable = true)
public void setupRotations(ArmorStand armorStand, PoseStack poseStack, float f, float g, float h, float i, CallbackInfo ci) {
if (Flashback.isInReplay()) {
poseStack.mulPose(Axis.YP.rotationDegrees(180.0F - g));
ci.cancel();
}
}
}
@@ -0,0 +1,64 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.packet.FinishedServerTick;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl;
import net.minecraft.network.protocol.PacketUtils;
import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket;
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;
import java.net.URL;
import java.util.UUID;
@Mixin(ClientCommonPacketListenerImpl.class)
public abstract class MixinClientCommonPacketListenerImpl {
@Shadow
@Final
protected Minecraft minecraft;
@Shadow
@Nullable
private static URL parseResourcePackUrl(String string) {
return null;
}
/**
* Removes the resource pack prompt screen in replays
*/
@Inject(method = "handleResourcePackPush", at = @At("HEAD"), cancellable = true)
public void handleResourcePackPush(ClientboundResourcePackPushPacket clientboundResourcePackPushPacket, CallbackInfo ci) {
if (Flashback.isInReplay()) {
PacketUtils.ensureRunningOnSameThread(clientboundResourcePackPushPacket, (ClientCommonPacketListenerImpl)(Object)this, this.minecraft);
UUID uuid = clientboundResourcePackPushPacket.id();
URL uRL = parseResourcePackUrl(clientboundResourcePackPushPacket.url());
if (uRL != null) {
String string = clientboundResourcePackPushPacket.hash();
this.minecraft.getDownloadedPackSource().allowServerPacks();
this.minecraft.getDownloadedPackSource().pushPack(uuid, uRL, string);
}
ci.cancel();
}
}
@Inject(method = "handleCustomPayload(Lnet/minecraft/network/protocol/common/ClientboundCustomPayloadPacket;)V", at = @At("HEAD"), cancellable = true)
public void handleCustomPayload(ClientboundCustomPayloadPacket clientboundCustomPayloadPacket, CallbackInfo ci) {
if (clientboundCustomPayloadPacket.payload() == FinishedServerTick.INSTANCE) {
if (Flashback.EXPORT_JOB != null) {
Flashback.EXPORT_JOB.onFinishedServerTick();
}
ci.cancel();
}
}
}
@@ -0,0 +1,44 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.client.Minecraft;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
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.CallbackInfoReturnable;
@Mixin(Entity.class)
public abstract class MixinEntity {
@Shadow
public abstract boolean isInvisible();
@Shadow
private Level level;
@Shadow
public abstract boolean isInvisibleTo(Player player);
@Inject(method = "isInvisibleTo", at = @At("HEAD"), cancellable = true)
public void isInvisibleTo(Player player, CallbackInfoReturnable<Boolean> cir) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null && player == Minecraft.getInstance().player) {
int localId = replayServer.getLocalPlayerId();
if (this.level.getEntity(localId) instanceof Player localPlayer) {
if ((Object)this == localPlayer) {
cir.setReturnValue(false);
} else {
cir.setReturnValue(this.isInvisibleTo(localPlayer));
}
} else {
cir.setReturnValue(this.isInvisible());
}
}
}
}
@@ -0,0 +1,102 @@
package com.moulberry.flashback.mixin.playback;
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.editor.ui.ReplayUI;
import com.moulberry.flashback.ext.ItemInHandRendererExt;
import com.moulberry.flashback.ext.MinecraftExt;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Options;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.ItemInHandRenderer;
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.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 org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(GameRenderer.class)
public class MixinGameRenderer {
@WrapOperation(method = "render", at=@At(value = "FIELD", target = "Lnet/minecraft/client/Options;pauseOnLostFocus:Z"))
public boolean getPauseOnLostFocus(Options instance, Operation<Boolean> original) {
if (ReplayUI.isActive() || Flashback.EXPORT_JOB != null) {
return false;
}
return original.call(instance);
}
/*
* Render item in hand for spectators in a replay
*/
@Shadow
@Final
private Minecraft minecraft;
@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) {
return GameType.SURVIVAL;
}
return original.call(instance);
}
@WrapOperation(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderHandsWithItems(FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/player/LocalPlayer;I)V"))
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);
} else {
original.call(instance, f, poseStack, bufferSource, localPlayer, i);
}
}
@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();
}
original.call(instance, blockGetter, entity, bl, bl2, f);
}
@Inject(method = "tryTakeScreenshotIfNeeded", at = @At("HEAD"), cancellable = true)
public void tryTakeScreenshotIfNeeded(CallbackInfo ci) {
if (Flashback.isInReplay()) {
ci.cancel();
}
}
@Inject(method = "getFov", at = @At("HEAD"), cancellable = true)
public void getFov(Camera camera, float f, boolean bl, CallbackInfoReturnable<Double> cir) {
if (Flashback.isInReplay()) {
if (!bl) {
cir.setReturnValue(70.0);
return;
}
int fov = this.minecraft.options.fov().get().intValue();
if (ReplayVisuals.overrideFov) {
cir.setReturnValue((double) ReplayVisuals.overrideFovAmount);
return;
}
cir.setReturnValue((double) fov);
}
}
}
@@ -0,0 +1,126 @@
package com.moulberry.flashback.mixin.playback;
import com.google.common.base.MoreObjects;
import com.mojang.blaze3d.vertex.PoseStack;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ext.ItemInHandRendererExt;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.ItemInHandRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.ItemStack;
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.util.UUID;
@Mixin(ItemInHandRenderer.class)
public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt {
@Shadow
private float oMainHandHeight;
@Shadow
private float mainHandHeight;
@Shadow
private float oOffHandHeight;
@Shadow
private float offHandHeight;
@Shadow
protected abstract void renderArmWithItem(AbstractClientPlayer abstractClientPlayer, float f, float g, InteractionHand interactionHand, float h, ItemStack itemStack, float i, PoseStack poseStack, MultiBufferSource multiBufferSource, int j);
@Shadow
private ItemStack mainHandItem;
@Shadow
private ItemStack offHandItem;
@Override
public void flashback$renderHandsWithItems(float partialTick, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, AbstractClientPlayer clientPlayer, int i) {
float m;
float l;
float g = clientPlayer.getAttackAnim(partialTick);
InteractionHand interactionHand = MoreObjects.firstNonNull(clientPlayer.swingingArm, InteractionHand.MAIN_HAND);
float h = Mth.lerp(partialTick, clientPlayer.xRotO, clientPlayer.getXRot());
// todo: hand selection
// ItemInHandRenderer.HandRenderSelection handRenderSelection = evaluateWhichHandsToRender(clientPlayer);
// todo: bob
// float j = Mth.lerp((float)f, (float)clientPlayer.xBobO, (float)clientPlayer.xBob);
// float k = Mth.lerp((float)f, (float)clientPlayer.yBobO, (float)clientPlayer.yBob);
// poseStack.mulPose(Axis.XP.rotationDegrees((clientPlayer.getViewXRot(f) - j) * 0.1f));
// poseStack.mulPose(Axis.YP.rotationDegrees((clientPlayer.getViewYRot(f) - k) * 0.1f));
if (true) {
l = interactionHand == InteractionHand.MAIN_HAND ? g : 0.0f;
m = 1.0f - Mth.lerp(partialTick, this.oMainHandHeight, this.mainHandHeight);
renderArmWithItem(clientPlayer, partialTick, h, InteractionHand.MAIN_HAND, l, this.mainHandItem, m, poseStack, bufferSource, i);
}
if (true) {
l = interactionHand == InteractionHand.OFF_HAND ? g : 0.0f;
m = 1.0f - Mth.lerp(partialTick, this.oOffHandHeight, this.offHandHeight);
renderArmWithItem(clientPlayer, partialTick, h, InteractionHand.OFF_HAND, l, this.offHandItem, m, poseStack, bufferSource, i);
}
bufferSource.endBatch();
}
// todo: change first person FOV when pulling bows, etc.
// todo: show arm (need to replace usage of LocalPlayer in renderPlayerArm
@Unique
private UUID lastSpectatingPlayer = null;
@Inject(method = "tick", at = @At("HEAD"), cancellable = true)
public void tick(CallbackInfo ci) {
AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer();
if (spectatingPlayer == null) {
this.lastSpectatingPlayer = null;
} else {
ItemStack newMainHandItem = spectatingPlayer.getMainHandItem();
ItemStack newOffHandItem = spectatingPlayer.getOffhandItem();
if (!spectatingPlayer.getUUID().equals(lastSpectatingPlayer)) {
this.lastSpectatingPlayer = spectatingPlayer.getUUID();
this.mainHandItem = newMainHandItem;
this.offHandItem = newOffHandItem;
this.oMainHandHeight = this.mainHandHeight = 1.0f;
this.oOffHandHeight = this.offHandHeight = 1.0f;
ci.cancel();
return;
}
this.oMainHandHeight = this.mainHandHeight;
this.oOffHandHeight = this.offHandHeight;
if (ItemStack.matches(this.mainHandItem, newMainHandItem)) {
this.mainHandItem = newMainHandItem;
}
if (ItemStack.matches(this.offHandItem, newOffHandItem)) {
this.offHandItem = newOffHandItem;
}
if (false /*clientPlayer.isHandsBusy()*/) {
this.mainHandHeight = Mth.clamp((float)(this.mainHandHeight - 0.4f), (float)0.0f, (float)1.0f);
this.offHandHeight = Mth.clamp((float)(this.offHandHeight - 0.4f), (float)0.0f, (float)1.0f);
} else {
// todo: attack strength
float f = 1.0f;//spectatingPlayer.getAttackStrengthScale(1.0f);
this.mainHandHeight += Mth.clamp((this.mainHandItem == newMainHandItem ? f * f * f : 0.0f) - this.mainHandHeight, -0.4f, 0.4f);
this.offHandHeight += Mth.clamp((float)(this.offHandItem == newOffHandItem ? 1 : 0) - this.offHandHeight, -0.4f, 0.4f);
}
if (this.mainHandHeight < 0.1f) {
this.mainHandItem = newMainHandItem;
}
if (this.offHandHeight < 0.1f) {
this.offHandItem = newOffHandItem;
}
ci.cancel();
}
}
}
@@ -0,0 +1,56 @@
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;
}
}
@@ -0,0 +1,40 @@
package com.moulberry.flashback.mixin.playback;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(LivingEntity.class)
public abstract class MixinLivingEntity extends Entity {
@Shadow
public abstract void lerpTo(double d, double e, double f, float g, float h, int i);
@Shadow
public abstract void lerpHeadTo(float f, int i);
public MixinLivingEntity(EntityType<?> entityType, Level level) {
super(entityType, level);
}
// todo: maybe reintroduce this lerpTo code?
// @Inject(method = "lerpTo", at = @At("HEAD"), cancellable = true)
// public void lerpTo(double d, double e, double f, float g, float h, int i, CallbackInfo ci) {
// if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) {
// this.lerpTo(d, e, f, g, h, 1);
// ci.cancel();
// }
// }
//
// @Inject(method = "lerpHeadTo", at = @At("HEAD"), cancellable = true)
// public void lerpHeadTo(float f, int i, CallbackInfo ci) {
// if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) {
// this.lerpHeadTo(f, 1);
// ci.cancel();
// }
// }
}
@@ -0,0 +1,35 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.PlayerChunkSender;
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(PlayerChunkSender.class)
public class MixinPlayerChunkSender {
// Make chunks send faster on replay servers
@Shadow
private float desiredChunksPerTick;
@Shadow
private int unacknowledgedBatches;
@Shadow
private float batchQuota;
@Inject(method = "sendNextChunks", at = @At("HEAD"))
public void sendNextChunks(ServerPlayer serverPlayer, CallbackInfo ci) {
if (Flashback.isInReplay()) {
this.unacknowledgedBatches = 0;
this.batchQuota = 0.0f;
this.desiredChunksPerTick = Math.max(this.desiredChunksPerTick, 256.0f);
}
}
}
@@ -0,0 +1,31 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.numbers.NumberFormat;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
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.CallbackInfoReturnable;
@Mixin(Scoreboard.class)
public abstract class MixinScoreboard {
@Shadow @Final private Object2ObjectMap<String, Objective> objectivesByName;
@Shadow public abstract void removeObjective(Objective objective);
@Inject(method = "addObjective", at = @At("HEAD"))
public void addObjective(String string, ObjectiveCriteria objectiveCriteria, Component component, ObjectiveCriteria.RenderType renderType, boolean bl, NumberFormat numberFormat, CallbackInfoReturnable<Objective> cir) {
if (Flashback.isInReplay() && this.objectivesByName.containsKey(string)) {
this.removeObjective(this.objectivesByName.get(string));
}
}
}
@@ -0,0 +1,35 @@
package com.moulberry.flashback.mixin.playback;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.Minecraft;
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.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(TickRateManager.class)
public abstract class MixinTickRateManager {
@Shadow
public abstract boolean runsNormally();
@Unique
private final boolean isClientTickRateManager = !((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);
} else {
cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player);
}
}
}
}
@@ -0,0 +1,30 @@
package com.moulberry.flashback.mixin.record;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl;
import net.minecraft.client.multiplayer.ClientConfigurationPacketListenerImpl;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.CommonListenerCookie;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientConfigurationPacketListenerImpl.class)
public abstract class MixinClientConfigurationPacketListenerImpl extends ClientCommonPacketListenerImpl {
protected MixinClientConfigurationPacketListenerImpl(Minecraft minecraft, Connection connection, CommonListenerCookie commonListenerCookie) {
super(minecraft, connection, commonListenerCookie);
}
@Inject(method = "handleConfigurationFinished", at = @At("RETURN"))
public void handleConfigurationFinished(ClientboundFinishConfigurationPacket clientboundFinishConfigurationPacket, CallbackInfo ci) {
if (Flashback.RECORDER != null) {
Flashback.RECORDER.setRegistryAccess(((ClientPacketListener)this.connection.getPacketListener()).registryAccess());
}
}
}
@@ -0,0 +1,31 @@
package com.moulberry.flashback.mixin.record;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.record.Recorder;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.PacketListener;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Connection.class)
public class MixinConnection {
@Inject(method = "genericsFtw", at = @At("HEAD"))
private static void genericsFtw(Packet<?> packet, PacketListener packetListener, CallbackInfo ci) {
Recorder recorder = Flashback.RECORDER;
if (recorder != null) {
if (packetListener instanceof ClientGamePacketListener) {
recorder.writePacketAsync(packet, ConnectionProtocol.PLAY);
} else if (packetListener instanceof ClientConfigurationPacketListener) {
recorder.writePacketAsync(packet, ConnectionProtocol.CONFIGURATION);
}
}
}
}
@@ -0,0 +1,20 @@
package com.moulberry.flashback.mixin.record;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import org.bytedeco.ffmpeg.avutil.AVFrame;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(value = FFmpegFrameRecorder.class, remap = false)
public class MixinFFmpegFrameRecorder {
// Don't change linesize, let it be calculated automatically
@WrapOperation(method = "recordImage", remap = false, at = @At(value = "INVOKE", remap = false, target = "Lorg/bytedeco/ffmpeg/avutil/AVFrame;linesize(II)Lorg/bytedeco/ffmpeg/avutil/AVFrame;"))
private AVFrame changeLinesize(AVFrame instance, int i, int setter, Operation<AVFrame> original) {
return instance;
}
}
@@ -0,0 +1,21 @@
package com.moulberry.flashback.mixin.replay_server;
import com.mojang.serialization.MapCodec;
import com.moulberry.flashback.playback.EmptyLevelSource;
import net.minecraft.core.Registry;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.ChunkGenerators;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ChunkGenerators.class)
public class MixinChunkGenerators {
@Inject(method = "bootstrap", at = @At("HEAD"))
private static void bootstrap(Registry<MapCodec<? extends ChunkGenerator>> registry, CallbackInfoReturnable<MapCodec<? extends ChunkGenerator>> cir) {
Registry.register(registry, "flashback/empty", EmptyLevelSource.CODEC);
}
}
@@ -0,0 +1,34 @@
package com.moulberry.flashback.mixin.replay_server;
import com.moulberry.flashback.Flashback;
import net.minecraft.server.level.GenerationChunkHolder;
import net.minecraft.util.StaticCache2D;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.status.ChunkStatusTasks;
import net.minecraft.world.level.chunk.status.ChunkStep;
import net.minecraft.world.level.chunk.status.WorldGenContext;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.concurrent.CompletableFuture;
@Mixin(ChunkStatusTasks.class)
public class MixinChunkStatusTasks {
@Inject(method = "initializeLight", at = @At("HEAD"), cancellable = true)
private static void initializeLight(WorldGenContext worldGenContext, ChunkStep chunkStep, StaticCache2D<GenerationChunkHolder> staticCache2D, ChunkAccess chunkAccess, CallbackInfoReturnable<CompletableFuture<ChunkAccess>> cir) {
if (Flashback.isInReplay()) {
cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess));
}
}
@Inject(method = "light", at = @At("HEAD"), cancellable = true)
private static void light(WorldGenContext worldGenContext, ChunkStep chunkStep, StaticCache2D<GenerationChunkHolder> staticCache2D, ChunkAccess chunkAccess, CallbackInfoReturnable<CompletableFuture<ChunkAccess>> cir) {
if (Flashback.isInReplay()) {
cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess));
}
}
}
@@ -0,0 +1,20 @@
package com.moulberry.flashback.mixin.replay_server;
import com.moulberry.flashback.Flashback;
import net.minecraft.world.level.entity.PersistentEntitySectionManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PersistentEntitySectionManager.class)
public class MixinPersistentEntitySectionManager {
@Inject(method = "saveAll", at = @At("HEAD"), cancellable = true)
public void saveAll(CallbackInfo ci) {
if (Flashback.isInReplay()) {
ci.cancel();
}
}
}
@@ -0,0 +1,33 @@
package com.moulberry.flashback.mixin.replay_server;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.players.PlayerList;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import java.util.Optional;
import java.util.function.Function;
@Mixin(PlayerList.class)
public class MixinPlayerList {
/*
* Don't change the dimension of replay viewers when spawning them
*/
@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) {
if (serverPlayer.server instanceof ReplayServer) {
return Optional.of(serverPlayer.level().dimension());
}
return original.call(instance, function);
}
}
@@ -0,0 +1,27 @@
package com.moulberry.flashback.mixin.replay_server;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
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(ServerChunkCache.class)
public class MixinServerChunkCache {
@Shadow
@Final
ServerLevel level;
@Inject(method = "save", at = @At("HEAD"), cancellable = true)
public void save(boolean bl, CallbackInfo ci) {
if (this.level.getServer() instanceof ReplayServer) {
ci.cancel();
}
}
}
@@ -0,0 +1,57 @@
package com.moulberry.flashback.mixin.replay_server;
import com.moulberry.flashback.ext.ServerConfigurationPacketListenerImplExt;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.CommonListenerCookie;
import net.minecraft.server.network.ConfigurationTask;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
import net.minecraft.server.network.config.SynchronizeRegistriesTask;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import java.util.List;
import java.util.Queue;
@Mixin(ServerConfigurationPacketListenerImpl.class)
public abstract class MixinServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements ServerConfigurationPacketListenerImplExt {
@Shadow
@Final
private Queue<ConfigurationTask> configurationTasks;
@Shadow
protected abstract void startNextTask();
@Shadow
private @Nullable SynchronizeRegistriesTask synchronizeRegistriesTask;
public MixinServerConfigurationPacketListenerImpl(MinecraftServer minecraftServer, Connection connection, CommonListenerCookie commonListenerCookie) {
super(minecraftServer, connection, commonListenerCookie);
}
@Override
public void flashback$startConfiguration(List<Packet<? super ClientConfigurationPacketListener>> initialPackets, List<ConfigurationTask> tasks) {
for (Packet<? super ClientConfigurationPacketListener> initialPacket : initialPackets) {
this.send(initialPacket);
}
for (ConfigurationTask task : tasks) {
if (task instanceof SynchronizeRegistriesTask synchronizeRegistriesTask) {
if (this.synchronizeRegistriesTask != null) {
throw new IllegalStateException("Duplicate SynchronizeRegistriesTask");
}
this.synchronizeRegistriesTask = synchronizeRegistriesTask;
}
}
this.configurationTasks.addAll(tasks);
this.startNextTask();
}
}
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more