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,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;
}
}