From 2fbe1f5480960401195a4b89817f97593924e621 Mon Sep 17 00:00:00 2001 From: Moulberry Date: Sun, 1 Sep 2024 18:08:55 +0800 Subject: [PATCH] 0.4.0 --- build.gradle | 1 + gradle.properties | 2 +- .../com/moulberry/flashback/Flashback.java | 164 +++++++++++++--- .../action/ActionAccuratePlayerPosition.java | 25 +++ .../flashback/action/PositionAndAngle.java | 16 ++ .../ActionSimpleVoiceChatSound.java | 46 +++++ .../SimpleVoiceChatPlayback.java | 78 ++++++++ .../SimpleVoiceChatPlugin.java | 34 ++++ .../SimpleVoiceChatRecorder.java | 68 +++++++ .../configuration/FlashbackConfig.java | 77 +++++++- .../configuration/IntOptionRange.java | 16 ++ .../flashback/exporting/ExportJob.java | 20 +- .../flashback/ext/RemotePlayerExt.java | 8 + .../moulberry/flashback/io/ReplayReader.java | 21 ++- .../flashback/mixin/MixinMinecraft.java | 31 +-- .../mixin/compat/bobby/MixinBobby.java | 5 +- .../bobby/MixinBobbyFakeChunkManager.java | 4 +- .../MixinVoiceChatALSpeakerBase.java | 30 +++ .../MixinVoiceChatClientVoicechat.java | 23 +++ .../MixinVoiceChatRenderEvents.java | 32 ++++ .../MixinVoiceChatSoundManager.java | 25 +++ .../playback/MixinItemInHandRenderer.java | 99 ++++++++-- .../mixin/playback/MixinLivingEntity.java | 2 + .../mixin/playback/MixinRemotePlayer.java | 59 ++++++ .../flashback/mixin/visuals/MixinGui.java | 131 +++++++++++-- .../FlashbackAccurateEntityPosition.java | 58 ++++++ .../packet/FlashbackRemoteExperience.java | 37 ++++ .../packet/FlashbackRemoteFoodData.java | 35 ++++ .../FlashbackRemoteSelectHotbarSlot.java | 33 ++++ .../packet/FlashbackRemoteSetSlot.java | 38 ++++ .../packet/FlashbackVoiceChatSound.java | 100 ++++++++++ .../playback/ReplayGamePacketHandler.java | 88 +++++++-- .../flashback/playback/ReplayPlayer.java | 11 ++ .../flashback/playback/ReplayServer.java | 144 ++++++++++++-- .../flashback/record/IgnoredPacketSet.java | 2 + .../moulberry/flashback/record/Recorder.java | 176 +++++++++++++++++- .../screen/UnsupportedLoaderScreen.java | 80 ++++++++ .../flashback/state/EditorState.java | 26 +++ .../AccurateEntityPositionHandler.java | 85 +++++++++ .../flashback/visuals/CameraRotation.java | 2 +- .../assets/flashback/lang/en_us.json | 8 +- .../assets/flashback/world_marker_circle.png | Bin 0 -> 696 bytes src/main/resources/fabric.mod.json | 8 +- src/main/resources/flashback.accesswidener | 4 + src/main/resources/flashback.mixins.json | 5 + .../licenses/ReplayVoiceChat-LICENSE | 21 +++ 46 files changed, 1846 insertions(+), 132 deletions(-) create mode 100644 src/main/java/com/moulberry/flashback/action/ActionAccuratePlayerPosition.java create mode 100644 src/main/java/com/moulberry/flashback/action/PositionAndAngle.java create mode 100644 src/main/java/com/moulberry/flashback/compat/simple_voice_chat/ActionSimpleVoiceChatSound.java create mode 100644 src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlayback.java create mode 100644 src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlugin.java create mode 100644 src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java create mode 100644 src/main/java/com/moulberry/flashback/configuration/IntOptionRange.java create mode 100644 src/main/java/com/moulberry/flashback/ext/RemotePlayerExt.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java create mode 100644 src/main/java/com/moulberry/flashback/mixin/playback/MixinRemotePlayer.java create mode 100644 src/main/java/com/moulberry/flashback/packet/FlashbackAccurateEntityPosition.java create mode 100644 src/main/java/com/moulberry/flashback/packet/FlashbackRemoteExperience.java create mode 100644 src/main/java/com/moulberry/flashback/packet/FlashbackRemoteFoodData.java create mode 100644 src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSelectHotbarSlot.java create mode 100644 src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSetSlot.java create mode 100644 src/main/java/com/moulberry/flashback/packet/FlashbackVoiceChatSound.java create mode 100644 src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java create mode 100644 src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java create mode 100644 src/main/resources/assets/flashback/world_marker_circle.png create mode 100644 src/main/resources/licenses/ReplayVoiceChat-LICENSE diff --git a/build.gradle b/build.gradle index 30587b5..ec5e58e 100644 --- a/build.gradle +++ b/build.gradle @@ -67,6 +67,7 @@ dependencies { modCompileOnly("maven.modrinth:sodium:RncWhTxD") modCompileOnly("maven.modrinth:iris:kuOV4Ece") modCompileOnly("maven.modrinth:bobby:2cuVyTav") + modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I") modImplementation("maven.modrinth:modmenu:xhN1IvHi") // modCompileOnly("maven.modrinth:axiom:D3uDJmiB") diff --git a/gradle.properties b/gradle.properties index e0a4247..0aa438d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ yarn_mappings=1.21+build.9 loader_version=0.15.11 # Mod Properties -mod_version=0.3.1 +mod_version=0.4.0 maven_group=com.moulberry.flashback archives_base_name=flashback diff --git a/src/main/java/com/moulberry/flashback/Flashback.java b/src/main/java/com/moulberry/flashback/Flashback.java index e5f00e1..5f1adae 100644 --- a/src/main/java/com/moulberry/flashback/Flashback.java +++ b/src/main/java/com/moulberry/flashback/Flashback.java @@ -9,6 +9,7 @@ import com.mojang.realmsclient.RealmsMainScreen; import com.mojang.serialization.Lifecycle; import com.moulberry.flashback.action.*; import com.moulberry.flashback.command.BetterColorArgument; +import com.moulberry.flashback.compat.simple_voice_chat.SimpleVoiceChatPlayback; import com.moulberry.flashback.configuration.FlashbackConfig; import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.ext.MinecraftExt; @@ -20,10 +21,16 @@ import com.moulberry.flashback.keyframe.types.FOVKeyframeType; import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; import com.moulberry.flashback.keyframe.types.TimeOfDayKeyframeType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; +import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; import com.moulberry.flashback.packet.FlashbackClearParticles; import com.moulberry.flashback.packet.FinishedServerTick; import com.moulberry.flashback.packet.FlashbackForceClientTick; import com.moulberry.flashback.packet.FlashbackInstantlyLerp; +import com.moulberry.flashback.packet.FlashbackRemoteExperience; +import com.moulberry.flashback.packet.FlashbackRemoteFoodData; +import com.moulberry.flashback.packet.FlashbackRemoteSelectHotbarSlot; +import com.moulberry.flashback.packet.FlashbackRemoteSetSlot; +import com.moulberry.flashback.packet.FlashbackVoiceChatSound; import com.moulberry.flashback.playback.EmptyLevelSource; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.record.FlashbackMeta; @@ -32,6 +39,8 @@ import com.moulberry.flashback.record.ReplayExporter; import com.moulberry.flashback.record.ReplayMarker; import com.moulberry.flashback.screen.ConfigScreen; import com.moulberry.flashback.screen.SaveReplayScreen; +import com.moulberry.flashback.screen.UnsupportedLoaderScreen; +import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.ShaderManager; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ModInitializer; @@ -44,7 +53,6 @@ import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.ChatFormatting; import net.minecraft.FileUtil; import net.minecraft.Util; import net.minecraft.client.Minecraft; @@ -57,7 +65,6 @@ import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.server.IntegratedServer; import net.minecraft.commands.Commands; -import net.minecraft.commands.arguments.ColorArgument; import net.minecraft.core.*; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; @@ -70,6 +77,7 @@ import net.minecraft.server.packs.repository.ServerPacksSource; import net.minecraft.world.Difficulty; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.level.*; import net.minecraft.world.level.biome.Biome; @@ -83,7 +91,6 @@ 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.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -147,31 +154,14 @@ public class Flashback implements ModInitializer, ClientModInitializer { StreamCodec.unit(FinishedServerTick.INSTANCE)); PayloadTypeRegistry.playS2C().register(FlashbackForceClientTick.TYPE, StreamCodec.unit(FlashbackForceClientTick.INSTANCE)); - ClientPlayNetworking.registerGlobalReceiver(FlashbackForceClientTick.TYPE, (payload, context) -> { - if (Flashback.isInReplay()) { - Minecraft.getInstance().tick(); - } - }); - PayloadTypeRegistry.playS2C().register(FlashbackClearParticles.TYPE, StreamCodec.unit(FlashbackClearParticles.INSTANCE)); - ClientPlayNetworking.registerGlobalReceiver(FlashbackClearParticles.TYPE, (payload, context) -> { - if (Flashback.isInReplay()) { - Minecraft.getInstance().particleEngine.clearParticles(); - } - }); - PayloadTypeRegistry.playS2C().register(FlashbackInstantlyLerp.TYPE, StreamCodec.unit(FlashbackInstantlyLerp.INSTANCE)); - ClientPlayNetworking.registerGlobalReceiver(FlashbackInstantlyLerp.TYPE, (payload, context) -> { - if (Flashback.isInReplay()) { - for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) { - if (entity instanceof LivingEntity && !entity.isRemoved() && !(entity instanceof LocalPlayer)) { - entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), - entity.lerpTargetYRot(), entity.lerpTargetXRot()); - } - entity.setOldPosAndRot(); - } - } - }); + PayloadTypeRegistry.playS2C().register(FlashbackRemoteSelectHotbarSlot.TYPE, FlashbackRemoteSelectHotbarSlot.STREAM_CODEC); + PayloadTypeRegistry.playS2C().register(FlashbackRemoteExperience.TYPE, FlashbackRemoteExperience.STREAM_CODEC); + PayloadTypeRegistry.playS2C().register(FlashbackRemoteFoodData.TYPE, FlashbackRemoteFoodData.STREAM_CODEC); + PayloadTypeRegistry.playS2C().register(FlashbackRemoteSetSlot.TYPE, FlashbackRemoteSetSlot.STREAM_CODEC); + PayloadTypeRegistry.playS2C().register(FlashbackVoiceChatSound.TYPE, FlashbackVoiceChatSound.STREAM_CODEC); + PayloadTypeRegistry.playS2C().register(FlashbackAccurateEntityPosition.TYPE, FlashbackAccurateEntityPosition.STREAM_CODEC); } @Override @@ -200,6 +190,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { ActionRegistry.register(ActionCreateLocalPlayer.INSTANCE); ActionRegistry.register(ActionMoveEntities.INSTANCE); ActionRegistry.register(ActionLevelChunkCached.INSTANCE); + ActionRegistry.register(ActionAccuratePlayerPosition.INSTANCE); KeyframeRegistry.register(CameraKeyframeType.INSTANCE); KeyframeRegistry.register(CameraOrbitKeyframeType.INSTANCE); @@ -209,6 +200,83 @@ public class Flashback implements ModInitializer, ClientModInitializer { KeyframeRegistry.register(TimelapseKeyframeType.INSTANCE); KeyframeRegistry.register(TimeOfDayKeyframeType.INSTANCE); + ClientPlayNetworking.registerGlobalReceiver(FlashbackForceClientTick.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Minecraft.getInstance().tick(); + } + }); + + ClientPlayNetworking.registerGlobalReceiver(FlashbackClearParticles.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Minecraft.getInstance().particleEngine.clearParticles(); + } + }); + + ClientPlayNetworking.registerGlobalReceiver(FlashbackInstantlyLerp.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) { + if (entity instanceof LivingEntity && !entity.isRemoved() && !(entity instanceof LocalPlayer)) { + entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), + entity.lerpTargetYRot(), entity.lerpTargetXRot()); + } + entity.setOldPosAndRot(); + } + } + }); + + ClientPlayNetworking.registerGlobalReceiver(FlashbackRemoteSelectHotbarSlot.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Entity entity = Minecraft.getInstance().level.getEntity(payload.entityId()); + if (entity instanceof Player player) { + player.getInventory().selected = payload.slot(); + } + } + }); + + ClientPlayNetworking.registerGlobalReceiver(FlashbackRemoteExperience.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Entity entity = Minecraft.getInstance().level.getEntity(payload.entityId()); + if (entity instanceof Player player) { + player.experienceProgress = payload.experienceProgress(); + player.totalExperience = payload.totalExperience(); + player.experienceLevel = payload.experienceLevel(); + } + } + }); + + ClientPlayNetworking.registerGlobalReceiver(FlashbackRemoteFoodData.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Entity entity = Minecraft.getInstance().level.getEntity(payload.entityId()); + if (entity instanceof Player player) { + player.getFoodData().setFoodLevel(payload.foodLevel()); + player.getFoodData().setSaturation(payload.saturationLevel()); + } + } + }); + + ClientPlayNetworking.registerGlobalReceiver(FlashbackRemoteSetSlot.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Entity entity = Minecraft.getInstance().level.getEntity(payload.entityId()); + if (entity instanceof Player player) { + player.getInventory().setItem(payload.slot(), payload.itemStack()); + } + } + }); + + if (FabricLoader.getInstance().isModLoaded("voicechat")) { + ClientPlayNetworking.registerGlobalReceiver(FlashbackVoiceChatSound.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + SimpleVoiceChatPlayback.play(payload); + } + }); + } + + ClientPlayNetworking.registerGlobalReceiver(FlashbackAccurateEntityPosition.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + AccurateEntityPositionHandler.update(payload); + } + }); + ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(ShaderManager.INSTANCE); ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { @@ -244,13 +312,38 @@ public class Flashback implements ModInitializer, ClientModInitializer { if (!Flashback.isInReplay() && Flashback.getConfig().automaticallyStart && RECORDER == null) { delayedStartRecording = 20; } + if (FabricLoader.getInstance().isModLoaded("voicechat")) { + SimpleVoiceChatPlayback.cleanUp(); + } }); - ClientTickEvents.START_CLIENT_TICK.register(tick -> { + String unsupportedLoader = findUnsupportedLoaders(); + + ClientTickEvents.END_CLIENT_TICK.register(minecraft -> { + AccurateEntityPositionHandler.tick(); + }); + + ClientTickEvents.START_CLIENT_TICK.register(minecraft -> { + if (unsupportedLoader != null && + System.currentTimeMillis() > Flashback.getConfig().nextUnsupportedModLoaderWarning && + canReplaceScreen(Minecraft.getInstance().screen)) { + String warning = String.format(""" + You are using an unsupported modloader: %s + + Do not report crashes, bugs or other issues to Flashback + + You will not receive support from Flashback + + If you need assistance, please contact %s + """, unsupportedLoader, unsupportedLoader); + + Minecraft.getInstance().setScreen(new UnsupportedLoaderScreen(Minecraft.getInstance().screen, + Component.literal("Flashback: Unsupported"), Component.literal(warning))); + } + if (!pendingReplaySave.isEmpty()) { Screen currentScreen = Minecraft.getInstance().screen; - if (currentScreen == null || currentScreen instanceof PauseScreen || currentScreen instanceof TitleScreen - || currentScreen instanceof RealmsMainScreen || currentScreen instanceof JoinMultiplayerScreen) { + if (canReplaceScreen(currentScreen)) { Path recordFolder = pendingReplaySave.getFirst(); LocalDateTime dateTime = LocalDateTime.now(); @@ -283,6 +376,19 @@ public class Flashback implements ModInitializer, ClientModInitializer { }); } + private static @Nullable String findUnsupportedLoaders() { + if (FabricLoader.getInstance().isModLoaded("feather")) { + return "Feather Client"; + } else { + return null; + } + } + + private static boolean canReplaceScreen(Screen screen) { + return screen == null || screen instanceof PauseScreen || screen instanceof TitleScreen + || screen instanceof RealmsMainScreen || screen instanceof JoinMultiplayerScreen; + } + private void addMarker(CommandContext command, @Nullable Integer colour, @Nullable Boolean savePosition, @Nullable String description) { if (RECORDER == null) { command.getSource().sendError(Component.literal("Not recording")); diff --git a/src/main/java/com/moulberry/flashback/action/ActionAccuratePlayerPosition.java b/src/main/java/com/moulberry/flashback/action/ActionAccuratePlayerPosition.java new file mode 100644 index 0000000..9d94e00 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/action/ActionAccuratePlayerPosition.java @@ -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 ActionAccuratePlayerPosition implements Action { + + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/accurate_player_position_optional"); + public static final ActionAccuratePlayerPosition INSTANCE = new ActionAccuratePlayerPosition(); + private ActionAccuratePlayerPosition() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleAccuratePlayerPosition(friendlyByteBuf); + } + +} diff --git a/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java b/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java new file mode 100644 index 0000000..e0196f4 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java @@ -0,0 +1,16 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.record.Recorder; +import net.minecraft.util.Mth; + +public record PositionAndAngle(double x, double y, double z, float yaw, float pitch) { + public PositionAndAngle lerp(PositionAndAngle other, double amount) { + return new PositionAndAngle( + this.x + (other.x - this.x) * amount, + this.y + (other.y - this.y) * amount, + this.z + (other.z - this.z) * amount, + (float) (this.yaw + Mth.wrapDegrees(other.yaw - this.yaw) * amount), + (float) (this.pitch + Mth.wrapDegrees(other.pitch - this.pitch) * amount) + ); + } +} diff --git a/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/ActionSimpleVoiceChatSound.java b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/ActionSimpleVoiceChatSound.java new file mode 100644 index 0000000..a015c53 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/ActionSimpleVoiceChatSound.java @@ -0,0 +1,46 @@ +package com.moulberry.flashback.compat.simple_voice_chat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.action.Action; +import com.moulberry.flashback.packet.FlashbackVoiceChatSound; +import com.moulberry.flashback.playback.ReplayPlayer; +import com.moulberry.flashback.playback.ReplayServer; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionSimpleVoiceChatSound implements Action { + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/simple_voice_chat_sound_optional"); + public static final ActionSimpleVoiceChatSound INSTANCE = new ActionSimpleVoiceChatSound(); + private ActionSimpleVoiceChatSound() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + var soundPacket = FlashbackVoiceChatSound.STREAM_CODEC.decode(friendlyByteBuf); + + if (replayServer.isProcessingSnapshot) { + return; + } + + boolean sendVoiceChat; + if (Flashback.isExporting()) { + sendVoiceChat = Flashback.EXPORT_JOB.getSettings().recordAudio() && Flashback.EXPORT_JOB.getCurrentTickDouble() > 0.0; + } else { + sendVoiceChat = !replayServer.fastForwarding && !replayServer.replayPaused; + } + + if (sendVoiceChat) { + for (ReplayPlayer replayViewer : replayServer.getReplayViewers()) { + ServerPlayNetworking.send(replayViewer, soundPacket); + } + } + + } + +} diff --git a/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlayback.java b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlayback.java new file mode 100644 index 0000000..efa420b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlayback.java @@ -0,0 +1,78 @@ +package com.moulberry.flashback.compat.simple_voice_chat; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.packet.FlashbackVoiceChatSound; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import de.maxhenkel.voicechat.api.Position; +import de.maxhenkel.voicechat.api.audiochannel.ClientEntityAudioChannel; +import de.maxhenkel.voicechat.api.audiochannel.ClientLocationalAudioChannel; +import de.maxhenkel.voicechat.api.audiochannel.ClientStaticAudioChannel; +import de.maxhenkel.voicechat.voice.client.ClientManager; +import de.maxhenkel.voicechat.voice.client.ClientVoicechat; +import net.minecraft.world.phys.Vec3; + +import java.time.Duration; +import java.util.UUID; + +public class SimpleVoiceChatPlayback { + + private static final Cache staticAudioChannelCache = CacheBuilder.newBuilder().expireAfterAccess(Duration.ofMinutes(1)).build(); + private static final Cache locationAudioChannelCache = CacheBuilder.newBuilder().expireAfterAccess(Duration.ofMinutes(1)).build(); + private static final Cache entityAudioChannelCache = CacheBuilder.newBuilder().expireAfterAccess(Duration.ofMinutes(1)).build(); + + public static void play(FlashbackVoiceChatSound sound) { + try { + UUID source = sound.source(); + + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState == null || editorState.hideDuringExport.contains(source)) { + return; + } + + boolean whispering = false; + switch (sound) { + case FlashbackVoiceChatSound.SoundStatic soundStatic -> { + ClientStaticAudioChannel channel = staticAudioChannelCache.get(source, + () -> SimpleVoiceChatPlugin.CLIENT_API.createStaticAudioChannel(source)); + channel.play(sound.samples()); + } + case FlashbackVoiceChatSound.SoundLocational soundLocational -> { + Vec3 pos = soundLocational.position(); + Position position = SimpleVoiceChatPlugin.CLIENT_API.createPosition(pos.x, pos.y, pos.z); + ClientLocationalAudioChannel channel = locationAudioChannelCache.get(source, + () -> SimpleVoiceChatPlugin.CLIENT_API.createLocationalAudioChannel(source, position)); + channel.setLocation(position); + channel.setDistance(soundLocational.distance()); + channel.play(sound.samples()); + } + case FlashbackVoiceChatSound.SoundEntity soundEntity -> { + ClientEntityAudioChannel channel = entityAudioChannelCache.get(source, + () -> SimpleVoiceChatPlugin.CLIENT_API.createEntityAudioChannel(source)); + channel.setWhispering(soundEntity.whispering()); + channel.setDistance(soundEntity.distance()); + channel.play(sound.samples()); + whispering = soundEntity.whispering(); + } + default -> { + } + } + + ClientVoicechat client = ClientManager.getClient(); + if (client != null) { + client.getTalkCache().updateTalking(sound.source(), whispering); + } + } catch (Exception e) { + Flashback.LOGGER.error("Error while trying to play voice chat sound", e); + } + } + + public static void cleanUp() { + staticAudioChannelCache.cleanUp(); + locationAudioChannelCache.cleanUp(); + entityAudioChannelCache.cleanUp(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlugin.java b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlugin.java new file mode 100644 index 0000000..2ee256e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatPlugin.java @@ -0,0 +1,34 @@ +package com.moulberry.flashback.compat.simple_voice_chat; + +import com.moulberry.flashback.action.ActionLevelChunkCached; +import com.moulberry.flashback.action.ActionRegistry; +import de.maxhenkel.voicechat.api.VoicechatApi; +import de.maxhenkel.voicechat.api.VoicechatClientApi; +import de.maxhenkel.voicechat.api.VoicechatPlugin; +import de.maxhenkel.voicechat.api.events.ClientReceiveSoundEvent; +import de.maxhenkel.voicechat.api.events.ClientSoundEvent; +import de.maxhenkel.voicechat.api.events.EventRegistration; +import de.maxhenkel.voicechat.plugins.impl.VoicechatClientApiImpl; + +public class SimpleVoiceChatPlugin implements VoicechatPlugin { + + public static VoicechatClientApi CLIENT_API = VoicechatClientApiImpl.instance(); + + @Override + public String getPluginId() { + return "flashback"; + } + + @Override + public void initialize(VoicechatApi api) { + ActionRegistry.register(ActionSimpleVoiceChatSound.INSTANCE); + } + + @Override + public void registerEvents(EventRegistration registration) { + registration.registerEvent(ClientReceiveSoundEvent.EntitySound.class, SimpleVoiceChatRecorder::onReceiveEntitySound); + registration.registerEvent(ClientReceiveSoundEvent.LocationalSound.class, SimpleVoiceChatRecorder::onReceiveLocationalSound); + registration.registerEvent(ClientReceiveSoundEvent.StaticSound.class, SimpleVoiceChatRecorder::onReceiveStaticSound); + registration.registerEvent(ClientSoundEvent.class, SimpleVoiceChatRecorder::onSendSound); + } +} diff --git a/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java new file mode 100644 index 0000000..5857ff7 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/compat/simple_voice_chat/SimpleVoiceChatRecorder.java @@ -0,0 +1,68 @@ +package com.moulberry.flashback.compat.simple_voice_chat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.packet.FlashbackVoiceChatSound; +import de.maxhenkel.voicechat.api.events.ClientReceiveSoundEvent; +import de.maxhenkel.voicechat.api.events.ClientSoundEvent; +import de.maxhenkel.voicechat.voice.client.ClientManager; +import net.minecraft.world.phys.Vec3; + +import java.util.UUID; + +public class SimpleVoiceChatRecorder { + + public static void onReceiveEntitySound(ClientReceiveSoundEvent.EntitySound event) { + if (Flashback.RECORDER == null) { + return; + } + + FlashbackVoiceChatSound soundPacket = new FlashbackVoiceChatSound.SoundEntity(event.getId(), event.getRawAudio(), event.isWhispering(), event.getDistance()); + submitSoundPacket(soundPacket); + } + + public static void onReceiveLocationalSound(ClientReceiveSoundEvent.LocationalSound event) { + if (Flashback.RECORDER == null) { + return; + } + + Vec3 position = new Vec3(event.getPosition().getX(), event.getPosition().getY(), event.getPosition().getZ()); + FlashbackVoiceChatSound soundPacket = new FlashbackVoiceChatSound.SoundLocational(event.getId(), event.getRawAudio(), position, event.getDistance()); + submitSoundPacket(soundPacket); + } + + public static void onReceiveStaticSound(ClientReceiveSoundEvent.StaticSound event) { + if (Flashback.RECORDER == null) { + return; + } + + FlashbackVoiceChatSound soundPacket = new FlashbackVoiceChatSound.SoundStatic(event.getId(), event.getRawAudio()); + submitSoundPacket(soundPacket); + } + + public static void onSendSound(ClientSoundEvent event) { + if (Flashback.RECORDER == null) { + return; + } + + UUID id = ClientManager.getPlayerStateManager().getOwnID(); + + FlashbackVoiceChatSound soundPacket; + if (SimpleVoiceChatPlugin.CLIENT_API.getGroup() != null) { + soundPacket = new FlashbackVoiceChatSound.SoundStatic(id, event.getRawAudio()); + } else { + soundPacket = new FlashbackVoiceChatSound.SoundEntity(id, event.getRawAudio(), event.isWhispering(), + (float) SimpleVoiceChatPlugin.CLIENT_API.getVoiceChatDistance()); + } + + submitSoundPacket(soundPacket); + } + + private static void submitSoundPacket(FlashbackVoiceChatSound soundPacket) { + Flashback.RECORDER.submitCustomTask(writer -> { + writer.startAction(ActionSimpleVoiceChatSound.INSTANCE); + FlashbackVoiceChatSound.STREAM_CODEC.encode(writer.friendlyByteBuf(), soundPacket); + writer.finishAction(ActionSimpleVoiceChatSound.INSTANCE); + }); + } + +} diff --git a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java index d6e7909..efbcef8 100644 --- a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java +++ b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java @@ -1,6 +1,6 @@ package com.moulberry.flashback.configuration; -import com.google.common.reflect.Reflection; +import com.mojang.serialization.Codec; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.SneakyThrow; @@ -9,8 +9,6 @@ import net.minecraft.ChatFormatting; import net.minecraft.client.OptionInstance; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; -import org.apache.logging.log4j.core.util.ReflectionUtil; -import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.lang.reflect.Field; @@ -22,6 +20,7 @@ import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; public class FlashbackConfig { @@ -50,7 +49,17 @@ public class FlashbackConfig { @OptionDescription("flashback.option.mark_dimension_changes.description") public boolean markDimensionChanges = true; + @OptionCaption("flashback.option.record_hotbar") + @OptionDescription("flashback.option.record_hotbar.description") + public boolean recordHotbar = false; + + @OptionCaption("flashback.option.local_player_updates_per_second") + @OptionDescription("flashback.option.local_player_updates_per_second.description") + @IntOptionRange(min = 20, max = 120, step = 20) + public int localPlayerUpdatesPerSecond = 20; + public Set openedWindows = new HashSet<>(); + public long nextUnsupportedModLoaderWarning = 0; @SuppressWarnings("unchecked") public OptionInstance[] createOptionInstances() { @@ -87,6 +96,21 @@ public class FlashbackConfig { throw SneakyThrow.sneakyThrow(e); } })); + } else if (field.getType() == int.class) { + IntOptionRange range = field.getDeclaredAnnotation(IntOptionRange.class); + if (range == null) { + continue; + } + + options.add(new OptionInstance(caption.value(), tooltipSupplier, (component, integer) -> { + return Component.translatable("options.generic_value", component, Component.translatable("flashback.option.per_second", integer)); + }, new IntRangeWithStep(range.min(), range.max(), range.step()), field.getInt(this), (integer) -> { + try { + field.set(this, integer); + } catch (Exception e) { + throw SneakyThrow.sneakyThrow(e); + } + })); } } catch (Exception e) { Flashback.LOGGER.error("Error while trying to convert config field to OptionInstance", e); @@ -96,6 +120,53 @@ public class FlashbackConfig { return options.toArray(new OptionInstance[0]); } + public record IntRangeWithStep(int minInclusive, int maxInclusive, int step) implements OptionInstance.IntRangeBase { + public Optional validateValue(Integer integer) { + int intValue = integer; + + if (intValue < minInclusive || intValue > maxInclusive) { + return Optional.empty(); + } else if (step > 0 && intValue != maxInclusive) { + int distance = intValue - minInclusive; + distance = distance/step*step; + intValue = minInclusive + distance; + } + return Optional.of(intValue); + } + + @Override + public Integer fromSliderValue(double d) { + if (d >= 1.0) { + return maxInclusive; + } + + int distance = (int)((maxInclusive - minInclusive) * d); + if (step > 0) { + distance = distance/step*step; + } + return minInclusive + distance; + } + + public Codec codec() { + return Codec.intRange(this.minInclusive, this.maxInclusive + 1); + } + + @Override + public int minInclusive() { + return this.minInclusive; + } + + @Override + public int maxInclusive() { + return this.maxInclusive; + } + + @Override + public boolean applyValueImmediately() { + return true; + } + } + public static FlashbackConfig tryLoadFromFolder(Path configFolder) { Path primary = configFolder.resolve("flashback.json"); Path backup = configFolder.resolve(".flashback.json.backup"); diff --git a/src/main/java/com/moulberry/flashback/configuration/IntOptionRange.java b/src/main/java/com/moulberry/flashback/configuration/IntOptionRange.java new file mode 100644 index 0000000..55026cc --- /dev/null +++ b/src/main/java/com/moulberry/flashback/configuration/IntOptionRange.java @@ -0,0 +1,16 @@ +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 IntOptionRange { + + int min(); + int max(); + int step() default 0; + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java index 6ce3cde..d06bcac 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -3,27 +3,24 @@ 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.Utils; -import com.moulberry.flashback.compat.IrisApiWrapper; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; import com.moulberry.flashback.keyframe.types.SpeedKeyframeType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; -import net.minecraft.client.Screenshot; import net.minecraft.client.gui.Font; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; @@ -43,7 +40,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; -import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Random; @@ -253,6 +249,7 @@ public class ExportJob { KeyframeHandler keyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance()); this.settings.editorState().applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble)); + AccurateEntityPositionHandler.apply(Minecraft.getInstance().level, (float) partialTick); SaveableFramebuffer saveable = downloader.take(); RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget; @@ -406,14 +403,11 @@ public class ExportJob { } private void updateSoundSound(Minecraft minecraft) { - EditorState editorState = EditorStateManager.getCurrent(); - if (editorState != null && editorState.audioSourceEntity != null && minecraft.level != null) { - Entity sourceEntity = minecraft.level.getEntities().get(editorState.audioSourceEntity); - if (sourceEntity != null) { - Camera dummyCamera = new Camera(); - dummyCamera.eyeHeight = sourceEntity.getEyeHeight(); - dummyCamera.setup(minecraft.level, sourceEntity, false, false, 1.0f); - minecraft.getSoundManager().updateSource(dummyCamera); + EditorState editorState = this.settings.editorState(); + if (editorState != null) { + Camera audioCamera = editorState.getAudioCamera(); + if (audioCamera != null) { + minecraft.getSoundManager().updateSource(audioCamera); return; } } diff --git a/src/main/java/com/moulberry/flashback/ext/RemotePlayerExt.java b/src/main/java/com/moulberry/flashback/ext/RemotePlayerExt.java new file mode 100644 index 0000000..6214084 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/ext/RemotePlayerExt.java @@ -0,0 +1,8 @@ +package com.moulberry.flashback.ext; + +public interface RemotePlayerExt { + + float flashback$getXBob(float partialTick); + float flashback$getYBob(float partialTick); + +} diff --git a/src/main/java/com/moulberry/flashback/io/ReplayReader.java b/src/main/java/com/moulberry/flashback/io/ReplayReader.java index 287af36..5222b68 100644 --- a/src/main/java/com/moulberry/flashback/io/ReplayReader.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayReader.java @@ -7,6 +7,8 @@ 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 it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; import net.minecraft.core.RegistryAccess; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; @@ -20,6 +22,7 @@ public class ReplayReader { private RegistryAccess registryAccess; private Action lastAction = null; private final Int2ObjectMap actions = new Int2ObjectOpenHashMap<>(); + private final IntSet ignoredActions = new IntOpenHashSet(); public ReplayReader(ByteBuf byteBuf, RegistryAccess registryAccess) { this.friendlyByteBuf = new FriendlyByteBuf(byteBuf); @@ -36,9 +39,13 @@ public class ReplayReader { Action action = ActionRegistry.getAction(actionName); if (action == null) { - throw new RuntimeException("Missing action: " + actionName); + if (actionName.getPath().endsWith("optional")) { + this.ignoredActions.add(i); + } else { + throw new RuntimeException("Missing action: " + actionName); + } } else { - this.actions.put(this.actions.size(), action); + this.actions.put(i, action); } } @@ -65,6 +72,11 @@ public class ReplayReader { int id = this.friendlyByteBuf.readVarInt(); Action action = this.actions.get(id); if (action == null) { + if (this.ignoredActions.contains(id)) { + int size = this.friendlyByteBuf.readInt(); + this.friendlyByteBuf.skipBytes(size); + continue; + } throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name()); } this.lastAction = action; @@ -93,6 +105,11 @@ public class ReplayReader { int id = this.friendlyByteBuf.readVarInt(); Action action = this.actions.get(id); if (action == null) { + if (this.ignoredActions.contains(id)) { + int size = this.friendlyByteBuf.readInt(); + this.friendlyByteBuf.skipBytes(size); + return true; + } throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name()); } this.lastAction = action; diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java index 2f6cde6..4c8fe3c 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java @@ -5,7 +5,6 @@ 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.configuration.FlashbackConfig; import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.exporting.ExportJobQueue; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; @@ -15,6 +14,7 @@ import com.moulberry.flashback.exporting.PerfectFrames; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.editor.ui.ReplayUI; +import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import it.unimi.dsi.fastutil.floats.FloatUnaryOperator; import net.minecraft.CrashReport; import net.minecraft.ReportedException; @@ -43,13 +43,12 @@ import net.minecraft.server.level.progress.ProcessorChunkProgressListener; import net.minecraft.server.level.progress.StoringChunkProgressListener; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.players.GameProfileCache; +import net.minecraft.util.Mth; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.TickRateManager; import net.minecraft.world.entity.Entity; -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; @@ -69,7 +68,6 @@ import java.util.Queue; import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @Mixin(Minecraft.class) @@ -140,6 +138,10 @@ public abstract class MixinMinecraft implements MinecraftExt { @Nullable public Entity cameraEntity; + @Shadow + @Final + public DeltaTracker.Timer timer; + @Inject(method="", at=@At("RETURN")) public void init(GameConfig gameConfig, CallbackInfo ci) { ReplayUI.init(); @@ -163,13 +165,10 @@ public abstract class MixinMinecraft implements MinecraftExt { @WrapOperation(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/sounds/SoundManager;updateSource(Lnet/minecraft/client/Camera;)V")) public void runTick_updateSource(SoundManager instance, Camera camera, Operation original) { EditorState editorState = EditorStateManager.getCurrent(); - if (editorState != null && editorState.audioSourceEntity != null && this.level != null) { - Entity sourceEntity = this.level.getEntities().get(editorState.audioSourceEntity); - if (sourceEntity != null) { - Camera dummyCamera = new Camera(); - dummyCamera.eyeHeight = sourceEntity.getEyeHeight(); - dummyCamera.setup(this.level, sourceEntity, false, false, 1.0f); - instance.updateSource(dummyCamera); + if (editorState != null) { + Camera audioCamera = editorState.getAudioCamera(); + if (audioCamera != null) { + original.call(instance, audioCamera); return; } } @@ -235,6 +234,16 @@ public abstract class MixinMinecraft implements MinecraftExt { } } + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MouseHandler;handleAccumulatedMovement()V", shift = At.Shift.AFTER)) + public void runTick_handleAccumulatedMovement(boolean runTick, CallbackInfo ci) { + if (Flashback.RECORDER != null && this.player != null) { + float partialTick = this.timer.deltaTickResidual; + Flashback.RECORDER.trackPartialPosition(this.player, partialTick); + } + + AccurateEntityPositionHandler.apply(this.level, this.timer.deltaTickResidual); + } + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runAllTasks()V", shift = At.Shift.AFTER)) public void runTick_runAllTasks(boolean runTick, CallbackInfo ci) { if (ExportJobQueue.drainingQueue) { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java index 3726cff..9a7cc0b 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobby.java @@ -11,10 +11,11 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @IfModLoaded("bobby") -@Mixin(value = Bobby.class, remap = false) +@Mixin(value = Bobby.class) public class MixinBobby { - @WrapOperation(method = "isEnabled", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;getSingleplayerServer()Lnet/minecraft/client/server/IntegratedServer;")) + @WrapOperation(method = "isEnabled", require = 0, remap = false, at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/Minecraft;getSingleplayerServer()Lnet/minecraft/client/server/IntegratedServer;")) public IntegratedServer isEnabled_getSingleplayerServer(Minecraft instance, Operation original) { IntegratedServer server = original.call(instance); if (server instanceof ReplayServer) { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java index 9899bc0..94da722 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/bobby/MixinBobbyFakeChunkManager.java @@ -20,7 +20,7 @@ import java.util.function.Supplier; @Mixin(value = FakeChunkManager.class, remap = false) public class MixinBobbyFakeChunkManager { - @Inject(method = "getCurrentWorldOrServerName", at = @At("HEAD"), cancellable = true) + @Inject(method = "getCurrentWorldOrServerName", require = 0, at = @At("HEAD"), cancellable = true) private static void getCurrentWorldOrServerName(ClientPacketListener networkHandler, CallbackInfoReturnable cir) { ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer != null) { @@ -34,7 +34,7 @@ public class MixinBobbyFakeChunkManager { } } - @Inject(method = "save", at = @At("HEAD"), cancellable = true) + @Inject(method = "save", at = @At("HEAD"), require = 0, cancellable = true) public void save(LevelChunk chunk, CallbackInfoReturnable> cir) { if (Flashback.isInReplay()) { Pair> copy = ChunkSerializer.shallowCopy(chunk); diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java new file mode 100644 index 0000000..72acceb --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatALSpeakerBase.java @@ -0,0 +1,30 @@ +package com.moulberry.flashback.mixin.compat.voice_chat; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import de.maxhenkel.voicechat.voice.client.speaker.ALSpeakerBase; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.GameRenderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@IfModLoaded("voicechat") +@Mixin(ALSpeakerBase.class) +public class MixinVoiceChatALSpeakerBase { + + @WrapOperation(method = "setPositionSync", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GameRenderer;getMainCamera()Lnet/minecraft/client/Camera;")) + public Camera setPositionSync_getMainCamera(GameRenderer instance, Operation original) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + Camera audioCamera = editorState.getAudioCamera(); + if (audioCamera != null) { + return audioCamera; + } + } + return original.call(instance); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java new file mode 100644 index 0000000..f784154 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatClientVoicechat.java @@ -0,0 +1,23 @@ +package com.moulberry.flashback.mixin.compat.voice_chat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import de.maxhenkel.voicechat.voice.client.ClientVoicechat; +import de.maxhenkel.voicechat.voice.client.ClientVoicechatConnection; +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; + +@IfModLoaded("voicechat") +@Mixin(value = ClientVoicechat.class, remap = false) +public class MixinVoiceChatClientVoicechat { + + @Inject(method = "startMicThread", at = @At("HEAD"), cancellable = true) + public void startMicThread(ClientVoicechatConnection connection, CallbackInfo ci) { + if (Flashback.isInReplay()) { + ci.cancel(); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java new file mode 100644 index 0000000..6ee2080 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatRenderEvents.java @@ -0,0 +1,32 @@ +package com.moulberry.flashback.mixin.compat.voice_chat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import de.maxhenkel.voicechat.voice.client.RenderEvents; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.resources.ResourceLocation; +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; + +@IfModLoaded("voicechat") +@Mixin(value = RenderEvents.class, remap = false) +public class MixinVoiceChatRenderEvents { + + @Inject(method = "shouldShowIcons", at = @At("HEAD"), cancellable = true) + public void shouldShowIcons(CallbackInfoReturnable cir) { + if (Flashback.isInReplay()) { + cir.setReturnValue(true); + } + } + + @Inject(method = "renderIcon", at = @At("HEAD"), cancellable = true) + public void renderIcon(GuiGraphics guiGraphics, ResourceLocation texture, CallbackInfo ci) { + if (Flashback.isInReplay()) { + ci.cancel(); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java new file mode 100644 index 0000000..7900466 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/voice_chat/MixinVoiceChatSoundManager.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.mixin.compat.voice_chat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import de.maxhenkel.voicechat.voice.client.SoundManager; +import net.minecraft.client.Minecraft; +import org.lwjgl.openal.EXTThreadLocalContext; +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; + +@IfModLoaded("voicechat") +@Mixin(value = SoundManager.class, remap = false) +public class MixinVoiceChatSoundManager { + + @Inject(method = "openContext", at = @At("HEAD"), cancellable = true) + public void openContext(CallbackInfoReturnable cir) { + if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().recordAudio()) { + long context = Minecraft.getInstance().getSoundManager().soundEngine.library.context; + cir.setReturnValue(EXTThreadLocalContext.alcSetThreadContext(context)); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java index e08d596..81a85c1 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java @@ -2,19 +2,25 @@ package com.moulberry.flashback.mixin.playback; import com.google.common.base.MoreObjects; import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ext.ItemInHandRendererExt; +import com.moulberry.flashback.ext.RemotePlayerExt; import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; 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.entity.Entity; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; 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.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.UUID; @@ -43,6 +49,42 @@ public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt { @Shadow private ItemStack offHandItem; + @Shadow + private static boolean isChargedCrossbow(ItemStack itemStack) { + return false; + } + + @Unique + private static final int RENDER_MAIN_HAND = 1; + @Unique + private static final int RENDER_OFF_HAND = 2; + @Unique + private static final int RENDER_BOTH_HANDS = RENDER_MAIN_HAND | RENDER_OFF_HAND; + + @Unique + private static int evaluateWhichHandsToRender(AbstractClientPlayer player) { + ItemStack mainStack = player.getMainHandItem(); + ItemStack offStack = player.getOffhandItem(); + boolean isHoldingBow = mainStack.is(Items.BOW) || offStack.is(Items.BOW); + boolean isHoldingCrossbow = mainStack.is(Items.CROSSBOW) || offStack.is(Items.CROSSBOW); + if (!isHoldingBow && !isHoldingCrossbow) { + return RENDER_BOTH_HANDS; + } + if (player.isUsingItem()) { + ItemStack useStack = player.getUseItem(); + InteractionHand interactionHand = player.getUsedItemHand(); + if (!useStack.is(Items.BOW) && !useStack.is(Items.CROSSBOW)) { + return interactionHand == InteractionHand.MAIN_HAND && isChargedCrossbow(player.getOffhandItem()) ? RENDER_MAIN_HAND : RENDER_BOTH_HANDS; + } else { + return interactionHand == InteractionHand.MAIN_HAND ? RENDER_MAIN_HAND : RENDER_OFF_HAND; + } + } + if (isChargedCrossbow(mainStack)) { + return RENDER_MAIN_HAND; + } + return RENDER_BOTH_HANDS; + } + @Override public void flashback$renderHandsWithItems(float partialTick, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, AbstractClientPlayer clientPlayer, int i) { float m; @@ -50,19 +92,19 @@ public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt { 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) { + int handRenderSelection = evaluateWhichHandsToRender(clientPlayer); + if (clientPlayer instanceof RemotePlayerExt remotePlayerExt) { +// float xBob = remotePlayerExt.flashback$getXBob(partialTick); +// float yBob = remotePlayerExt.flashback$getYBob(partialTick); +// poseStack.mulPose(Axis.XP.rotationDegrees((clientPlayer.getViewXRot(partialTick) - xBob) * 0.1f)); +// poseStack.mulPose(Axis.YP.rotationDegrees((clientPlayer.getViewYRot(partialTick) - yBob) * 0.1f)); + } + if ((handRenderSelection & RENDER_MAIN_HAND) != 0) { 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) { + if ((handRenderSelection & RENDER_OFF_HAND) != 0) { 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); @@ -70,9 +112,32 @@ public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt { bufferSource.endBatch(); } - // todo: change first person FOV when pulling bows, etc. + @ModifyArg(method = "renderPlayerArm", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;getRenderer(Lnet/minecraft/world/entity/Entity;)Lnet/minecraft/client/renderer/entity/EntityRenderer;")) + public Entity renderPlayerArm_getRenderer(Entity entity) { + AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer(); + if (spectatingPlayer != null) { + return spectatingPlayer; + } + return entity; + } - // todo: show arm (need to replace usage of LocalPlayer in renderPlayerArm + @ModifyArg(method = "renderPlayerArm", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/player/PlayerRenderer;renderLeftHand(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;)V")) + public AbstractClientPlayer renderPlayerArm_renderLeftHand(AbstractClientPlayer entity) { + AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer(); + if (spectatingPlayer != null) { + return spectatingPlayer; + } + return entity; + } + + @ModifyArg(method = "renderPlayerArm", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/player/PlayerRenderer;renderRightHand(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;)V")) + public AbstractClientPlayer renderPlayerArm_renderRightHand(AbstractClientPlayer entity) { + AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer(); + if (spectatingPlayer != null) { + return spectatingPlayer; + } + return entity; + } @Unique private UUID lastSpectatingPlayer = null; @@ -104,15 +169,9 @@ public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt { 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); - } + float str = spectatingPlayer.getAttackStrengthScale(1.0f); + this.mainHandHeight += Mth.clamp((this.mainHandItem == newMainHandItem ? str * str * str : 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; } diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLivingEntity.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLivingEntity.java index 779c118..89a332e 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLivingEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLivingEntity.java @@ -6,6 +6,8 @@ import net.minecraft.world.entity.LivingEntity; 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; @Mixin(LivingEntity.class) public abstract class MixinLivingEntity extends Entity { diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinRemotePlayer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinRemotePlayer.java new file mode 100644 index 0000000..204e4a4 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinRemotePlayer.java @@ -0,0 +1,59 @@ +package com.moulberry.flashback.mixin.playback; + +import com.mojang.authlib.GameProfile; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.ext.RemotePlayerExt; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.RemotePlayer; +import net.minecraft.util.Mth; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(RemotePlayer.class) +public class MixinRemotePlayer extends AbstractClientPlayer implements RemotePlayerExt { + + @Unique + private boolean wasSwinging = false; + + @Unique + private float xBobO = 0.0f; + @Unique + private float xBob = 0.0f; + @Unique + private float yBobO = 0.0f; + @Unique + private float yBob = 0.0f; + + private MixinRemotePlayer(ClientLevel clientLevel, GameProfile gameProfile) { + super(clientLevel, gameProfile); + } + + @Inject(method = "aiStep", at = @At("RETURN")) + public void aiStep(CallbackInfo ci) { + if (Flashback.isInReplay()) { + if (!this.wasSwinging && this.swinging) { + this.resetAttackStrengthTicker(); + } + this.wasSwinging = this.swinging; + + this.xBobO = xBob; + this.xBob += Mth.wrapDegrees(this.getXRot() - this.xBob) * 0.5f; + this.yBobO = yBob; + this.yBob += Mth.wrapDegrees(this.getYRot() - this.yBob) * 0.5f; + } + } + + @Override + public float flashback$getXBob(float partialTick) { + return Mth.lerp(partialTick, this.xBobO, this.xBob); + } + + @Override + public float flashback$getYBob(float partialTick) { + return Mth.lerp(partialTick, this.yBobO, this.yBob); + } +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java index 61745b1..5b77d67 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java @@ -1,23 +1,58 @@ package com.moulberry.flashback.mixin.visuals; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.DeltaTracker; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.GameType; import net.minecraft.world.phys.HitResult; +import org.jetbrains.annotations.Nullable; 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(Gui.class) -public class MixinGui { +public abstract class MixinGui { + + @Shadow + @Nullable + protected abstract Player getCameraPlayer(); + + @Unique + private GameType cameraGameType = GameType.DEFAULT_MODE; + + @Inject(method = "render", at = @At("HEAD")) + public void render_updateCameraGameType(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { + if (Flashback.isInReplay()) { + Player player = this.getCameraPlayer(); + if (player != null) { + var connection = Minecraft.getInstance().getConnection(); + if (connection != null) { + var playerInfo = connection.getPlayerInfo(player.getUUID()); + if (playerInfo != null) { + this.cameraGameType = playerInfo.getGameMode(); + return; + } + } + } + this.cameraGameType = Minecraft.getInstance().gameMode.getPlayerMode(); + } + } @Inject(method = "renderChat", at = @At("HEAD"), cancellable = true) public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { @@ -51,6 +86,84 @@ public class MixinGui { } } + @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;")) + public GameType renderHotbarAndDecorations_getPlayerMode(MultiPlayerGameMode instance, Operation original) { + if (Flashback.isInReplay()) { + return this.cameraGameType; + } + return original.call(instance); + } + + @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;canHurtPlayer()Z")) + public boolean renderHotbarAndDecorations_canHurtPlayer(MultiPlayerGameMode instance, Operation original) { + if (Flashback.isInReplay()) { + return this.cameraGameType.isSurvival(); + } + return original.call(instance); + } + + @Inject(method = "isExperienceBarVisible", at = @At("HEAD"), cancellable = true) + public void isExperienceBarVisible(CallbackInfoReturnable cir) { + if (Flashback.isInReplay()) { + cir.setReturnValue(this.cameraGameType.isSurvival()); + } + } + + @WrapOperation(method = "renderExperienceBar", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getXpNeededForNextLevel()I")) + public int renderExperienceBar_getXpNeededForNextLevel(LocalPlayer instance, Operation original) { + if (Flashback.isInReplay()) { + Player player = this.getCameraPlayer(); + if (player != null) { + return player.getXpNeededForNextLevel(); + } + } + return original.call(instance); + } + + @WrapOperation(method = "renderExperienceBar", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceProgress:F")) + public float renderExperienceBar_experienceProgress(LocalPlayer instance, Operation original) { + if (Flashback.isInReplay()) { + Player player = this.getCameraPlayer(); + if (player != null) { + return player.experienceProgress; + } + } + return original.call(instance); + } + + @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getAttackStrengthScale(F)F")) + public float renderCrosshair_getAttackStrengthScale(LocalPlayer instance, float partialTick, Operation original) { + if (Flashback.isInReplay()) { + Player player = this.getCameraPlayer(); + if (player != null) { + return player.getAttackStrengthScale(partialTick); + } + } + return original.call(instance, partialTick); + } + + @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getCurrentItemAttackStrengthDelay()F")) + public float renderCrosshair_getCurrentItemAttackStrengthDelay(LocalPlayer instance, Operation original) { + if (Flashback.isInReplay()) { + Player player = this.getCameraPlayer(); + if (player != null) { + return player.getCurrentItemAttackStrengthDelay(); + } + } + return original.call(instance); + } + + @WrapOperation(method = "renderExperienceLevel", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceLevel:I")) + public int renderExperienceLevel_experienceLevel(LocalPlayer instance, Operation original) { + if (Flashback.isInReplay()) { + Player player = this.getCameraPlayer(); + if (player != null) { + return player.experienceLevel; + } + } + return original.call(instance); + } + @Inject(method = "renderVignette", at = @At("HEAD"), cancellable = true) public void renderVignette(GuiGraphics guiGraphics, Entity entity, CallbackInfo ci) { // The vignette ruins the transparency when trying to export with alpha @@ -62,16 +175,12 @@ public class MixinGui { @Inject(method = "canRenderCrosshairForSpectator", at = @At("HEAD"), cancellable = true) public void canRenderCrosshairForSpectator(HitResult hitResult, CallbackInfoReturnable cir) { - if (Flashback.isExporting()) { - cir.setReturnValue(false); - return; - } - if (ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) { - cir.setReturnValue(true); - return; - } - if (Flashback.getSpectatingPlayer() != null) { - cir.setReturnValue(true); + if (Flashback.isInReplay()) { + if (!Flashback.isExporting() && ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) { + cir.setReturnValue(true); + return; + } + cir.setReturnValue(Flashback.getSpectatingPlayer() != null); } } diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackAccurateEntityPosition.java b/src/main/java/com/moulberry/flashback/packet/FlashbackAccurateEntityPosition.java new file mode 100644 index 0000000..1a14360 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackAccurateEntityPosition.java @@ -0,0 +1,58 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.action.PositionAndAngle; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.world.item.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public record FlashbackAccurateEntityPosition(int entityId, List positionAndAngles) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("accurate_entity_position")); + + public static final StreamCodec STREAM_CODEC = new AccurateEntityPositionStreamCodec(); + + @Override + public Type type() { + return TYPE; + } + + public static class AccurateEntityPositionStreamCodec implements StreamCodec { + @Override + public FlashbackAccurateEntityPosition decode(FriendlyByteBuf friendlyByteBuf) { + int entityId = friendlyByteBuf.readVarInt(); + int interpolatedCount = friendlyByteBuf.readVarInt(); + + List interpolatedPositions = new ArrayList<>(interpolatedCount); + for (int i = 0; i < interpolatedCount; i++) { + double x = friendlyByteBuf.readDouble(); + double y = friendlyByteBuf.readDouble(); + double z = friendlyByteBuf.readDouble(); + float yaw = friendlyByteBuf.readFloat(); + float pitch = friendlyByteBuf.readFloat(); + + interpolatedPositions.add(new PositionAndAngle(x, y, z, yaw, pitch)); + } + + return new FlashbackAccurateEntityPosition(entityId, interpolatedPositions); + } + + @Override + public void encode(FriendlyByteBuf friendlyByteBuf, FlashbackAccurateEntityPosition accurateEntityPosition) { + friendlyByteBuf.writeVarInt(accurateEntityPosition.entityId); + friendlyByteBuf.writeVarInt(accurateEntityPosition.positionAndAngles.size()); + for (PositionAndAngle interpolatedPosition : accurateEntityPosition.positionAndAngles) { + friendlyByteBuf.writeDouble(interpolatedPosition.x()); + friendlyByteBuf.writeDouble(interpolatedPosition.y()); + friendlyByteBuf.writeDouble(interpolatedPosition.z()); + friendlyByteBuf.writeFloat(interpolatedPosition.yaw()); + friendlyByteBuf.writeFloat(interpolatedPosition.pitch()); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteExperience.java b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteExperience.java new file mode 100644 index 0000000..19076aa --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteExperience.java @@ -0,0 +1,37 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public record FlashbackRemoteExperience(int entityId, float experienceProgress, int totalExperience, int experienceLevel) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("remote_experience")); + + public static final StreamCodec STREAM_CODEC = new FlashbackRemoteExperienceStreamCodec(); + + @Override + public Type type() { + return TYPE; + } + + public static class FlashbackRemoteExperienceStreamCodec implements StreamCodec { + @Override + public FlashbackRemoteExperience decode(FriendlyByteBuf friendlyByteBuf) { + int entityId = friendlyByteBuf.readVarInt(); + float experienceProgress = friendlyByteBuf.readFloat(); + int totalExperience = friendlyByteBuf.readVarInt(); + int experienceLevel = friendlyByteBuf.readVarInt(); + return new FlashbackRemoteExperience(entityId, experienceProgress, totalExperience, experienceLevel); + } + + @Override + public void encode(FriendlyByteBuf friendlyByteBuf, FlashbackRemoteExperience remoteHotbarSlot) { + friendlyByteBuf.writeVarInt(remoteHotbarSlot.entityId); + friendlyByteBuf.writeFloat(remoteHotbarSlot.experienceProgress); + friendlyByteBuf.writeVarInt(remoteHotbarSlot.totalExperience); + friendlyByteBuf.writeVarInt(remoteHotbarSlot.experienceLevel); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteFoodData.java b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteFoodData.java new file mode 100644 index 0000000..678c443 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteFoodData.java @@ -0,0 +1,35 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public record FlashbackRemoteFoodData(int entityId, int foodLevel, float saturationLevel) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("remote_food_data")); + + public static final StreamCodec STREAM_CODEC = new FlashbackRemoteFoodDataStreamCodec(); + + @Override + public Type type() { + return TYPE; + } + + public static class FlashbackRemoteFoodDataStreamCodec implements StreamCodec { + @Override + public FlashbackRemoteFoodData decode(FriendlyByteBuf friendlyByteBuf) { + int entityId = friendlyByteBuf.readVarInt(); + int foodLevel = friendlyByteBuf.readVarInt(); + float saturationLevel = friendlyByteBuf.readFloat(); + return new FlashbackRemoteFoodData(entityId, foodLevel, saturationLevel); + } + + @Override + public void encode(FriendlyByteBuf friendlyByteBuf, FlashbackRemoteFoodData remoteHotbarSlot) { + friendlyByteBuf.writeVarInt(remoteHotbarSlot.entityId); + friendlyByteBuf.writeVarInt(remoteHotbarSlot.foodLevel); + friendlyByteBuf.writeFloat(remoteHotbarSlot.saturationLevel); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSelectHotbarSlot.java b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSelectHotbarSlot.java new file mode 100644 index 0000000..b2d6b3a --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSelectHotbarSlot.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public record FlashbackRemoteSelectHotbarSlot(int entityId, int slot) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("remote_select_hotbar_slot")); + + public static final StreamCodec STREAM_CODEC = new RemoteSelectHotbarSlotStreamCodec(); + + @Override + public Type type() { + return TYPE; + } + + public static class RemoteSelectHotbarSlotStreamCodec implements StreamCodec { + @Override + public FlashbackRemoteSelectHotbarSlot decode(FriendlyByteBuf friendlyByteBuf) { + int entityId = friendlyByteBuf.readVarInt(); + int slot = friendlyByteBuf.readByte(); + return new FlashbackRemoteSelectHotbarSlot(entityId, slot); + } + + @Override + public void encode(FriendlyByteBuf friendlyByteBuf, FlashbackRemoteSelectHotbarSlot remoteHotbarSlot) { + friendlyByteBuf.writeVarInt(remoteHotbarSlot.entityId); + friendlyByteBuf.writeByte(remoteHotbarSlot.slot); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSetSlot.java b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSetSlot.java new file mode 100644 index 0000000..2fb4203 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackRemoteSetSlot.java @@ -0,0 +1,38 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.util.ExtraCodecs; +import net.minecraft.world.item.ItemStack; + +public record FlashbackRemoteSetSlot(int entityId, int slot, ItemStack itemStack) implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("remote_set_slot")); + + public static final StreamCodec STREAM_CODEC = new RemoteSetSlotStreamCodec(); + + @Override + public Type type() { + return TYPE; + } + + public static class RemoteSetSlotStreamCodec implements StreamCodec { + @Override + public FlashbackRemoteSetSlot decode(RegistryFriendlyByteBuf friendlyByteBuf) { + int entityId = friendlyByteBuf.readVarInt(); + int slot = friendlyByteBuf.readByte(); + ItemStack itemStack = ItemStack.OPTIONAL_STREAM_CODEC.decode(friendlyByteBuf); + return new FlashbackRemoteSetSlot(entityId, slot, itemStack); + } + + @Override + public void encode(RegistryFriendlyByteBuf friendlyByteBuf, FlashbackRemoteSetSlot remoteHotbarSlot) { + friendlyByteBuf.writeVarInt(remoteHotbarSlot.entityId); + friendlyByteBuf.writeByte(remoteHotbarSlot.slot); + ItemStack.OPTIONAL_STREAM_CODEC.encode(friendlyByteBuf, remoteHotbarSlot.itemStack); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackVoiceChatSound.java b/src/main/java/com/moulberry/flashback/packet/FlashbackVoiceChatSound.java new file mode 100644 index 0000000..5745fad --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackVoiceChatSound.java @@ -0,0 +1,100 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import io.netty.handler.codec.DecoderException; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.util.ExtraCodecs; +import net.minecraft.world.phys.Vec3; + +import java.util.UUID; + +public interface FlashbackVoiceChatSound extends CustomPacketPayload { + Type TYPE = new Type<>(Flashback.createResourceLocation("voice_chat_sound")); + StreamCodec STREAM_CODEC = new FlashbackVoiceChatSoundStreamCodec(); + + @Override + default Type type() { + return TYPE; + } + + UUID source(); + short[] samples(); + void writeExtraData(FriendlyByteBuf friendlyByteBuf); + + byte TYPE_STATIC_SOUND = 0; + byte TYPE_LOCATIONAL_SOUND = 1; + byte TYPE_ENTITY_SOUND = 2; + + record SoundStatic(UUID source, short[] samples) implements FlashbackVoiceChatSound { + @Override + public void writeExtraData(FriendlyByteBuf friendlyByteBuf) { + friendlyByteBuf.writeByte(TYPE_STATIC_SOUND); + } + } + + record SoundLocational(UUID source, short[] samples, Vec3 position, float distance) implements FlashbackVoiceChatSound { + @Override + public void writeExtraData(FriendlyByteBuf friendlyByteBuf) { + friendlyByteBuf.writeByte(TYPE_LOCATIONAL_SOUND); + friendlyByteBuf.writeVec3(this.position); + friendlyByteBuf.writeFloat(this.distance); + } + } + + record SoundEntity(UUID source, short[] samples, boolean whispering, float distance) implements FlashbackVoiceChatSound { + @Override + public void writeExtraData(FriendlyByteBuf friendlyByteBuf) { + friendlyByteBuf.writeByte(TYPE_ENTITY_SOUND); + friendlyByteBuf.writeBoolean(this.whispering); + friendlyByteBuf.writeFloat(this.distance); + } + } + + class FlashbackVoiceChatSoundStreamCodec implements StreamCodec { + @Override + public FlashbackVoiceChatSound decode(FriendlyByteBuf friendlyByteBuf) { + UUID uuid = friendlyByteBuf.readUUID(); + + int sampleCount = friendlyByteBuf.readVarInt(); + short[] samples = new short[sampleCount]; + for (int i = 0; i < sampleCount; i++) { + samples[i] = friendlyByteBuf.readShort(); + } + + byte type = friendlyByteBuf.readByte(); + + switch (type) { + case TYPE_STATIC_SOUND -> { + return new SoundStatic(uuid, samples); + } + case TYPE_LOCATIONAL_SOUND -> { + Vec3 position = friendlyByteBuf.readVec3(); + float distance = friendlyByteBuf.readFloat(); + return new SoundLocational(uuid, samples, position, distance); + } + case TYPE_ENTITY_SOUND -> { + boolean whispering = friendlyByteBuf.readBoolean(); + float distance = friendlyByteBuf.readFloat(); + return new SoundEntity(uuid, samples, whispering, distance); + } + default -> throw new DecoderException("Unknown voice chat type: " + type); + } + } + + @Override + public void encode(FriendlyByteBuf friendlyByteBuf, FlashbackVoiceChatSound packet) { + friendlyByteBuf.writeUUID(packet.source()); + + short[] samples = packet.samples(); + friendlyByteBuf.writeVarInt(samples.length); + for (short sample : samples) { + friendlyByteBuf.writeShort(sample); + } + + packet.writeExtraData(friendlyByteBuf); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index 0109c05..b620751 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -7,12 +7,15 @@ import com.moulberry.flashback.exception.UnsupportedPacketException; import com.moulberry.flashback.ext.LevelChunkExt; import com.moulberry.flashback.ext.ServerLevelExt; import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; +import com.moulberry.flashback.packet.FlashbackRemoteExperience; +import com.moulberry.flashback.packet.FlashbackRemoteFoodData; +import com.moulberry.flashback.packet.FlashbackRemoteSelectHotbarSlot; +import com.moulberry.flashback.packet.FlashbackRemoteSetSlot; import io.netty.channel.embedded.EmbeddedChannel; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.client.multiplayer.PlayerInfo; -import net.minecraft.client.player.KeyboardInput; -import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Holder; @@ -48,12 +51,10 @@ import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.ai.attributes.AttributeMap; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraft.world.entity.decoration.HangingEntity; -import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.decoration.Painting; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.npc.Villager; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.GameType; @@ -221,6 +222,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } } + for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { + if (Objects.equals(replayViewer.lastFirstPersonDataUUID, addEntityPacket.getUUID())) { + replayViewer.lastFirstPersonDataUUID = null; + } + } + Connection connection = new Connection(PacketFlow.SERVERBOUND); EmbeddedChannel embeddedChannel = new EmbeddedChannel(connection); serverPlayer.recreateFromPacket(addEntityPacket); @@ -408,7 +415,23 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleContainerSetSlot(ClientboundContainerSetSlotPacket clientboundContainerSetSlotPacket) { - throw new UnsupportedPacketException(clientboundContainerSetSlotPacket); + Entity entity = this.level().getEntity(this.localPlayerId); + if (!(entity instanceof Player player)) { + return; + } + + if (clientboundContainerSetSlotPacket.getContainerId() == -2) { + int slot = clientboundContainerSetSlotPacket.getSlot(); + ItemStack itemStack = clientboundContainerSetSlotPacket.getItem(); + player.getInventory().setItem(slot, itemStack); + + for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { + if (Objects.equals(replayViewer.lastFirstPersonDataUUID, player.getUUID())) { + replayViewer.lastFirstPersonHotbarItems[slot] = itemStack.copy(); + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteSetSlot(player.getId(), slot, itemStack.copy())); + } + } + } } @Override @@ -896,7 +919,29 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleSetCarriedItem(ClientboundSetCarriedItemPacket clientboundSetCarriedItemPacket) { - throw new UnsupportedPacketException(clientboundSetCarriedItemPacket); + if (!Inventory.isHotbarSlot(clientboundSetCarriedItemPacket.getSlot())) { + return; + } + + Entity entity = this.level().getEntity(this.localPlayerId); + if (!(entity instanceof Player player)) { + return; + } + + Inventory inventory = player.getInventory(); + + if (inventory.selected == clientboundSetCarriedItemPacket.getSlot()) { + return; + } + + inventory.selected = clientboundSetCarriedItemPacket.getSlot(); + + for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { + if (Objects.equals(replayViewer.lastFirstPersonDataUUID, player.getUUID())) { + replayViewer.lastFirstPersonSelectedSlot = inventory.selected; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteSelectHotbarSlot(player.getId(), inventory.selected)); + } + } } @Override @@ -952,6 +997,16 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { player.experienceProgress = clientboundSetExperiencePacket.getExperienceProgress(); player.totalExperience = clientboundSetExperiencePacket.getTotalExperience(); player.experienceLevel = clientboundSetExperiencePacket.getExperienceLevel(); + + for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { + if (Objects.equals(replayViewer.lastFirstPersonDataUUID, player.getUUID())) { + replayViewer.lastFirstPersonExperienceProgress = player.experienceProgress; + replayViewer.lastFirstPersonTotalExperience = player.totalExperience; + replayViewer.lastFirstPersonExperienceLevel = player.experienceLevel; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteExperience(player.getId(), player.experienceProgress, + player.totalExperience, player.experienceLevel)); + } + } } } @@ -960,8 +1015,20 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { Entity entity = this.level().getEntity(this.localPlayerId); if (entity instanceof Player player) { player.setHealth(clientboundSetHealthPacket.getHealth()); - player.getFoodData().setFoodLevel(clientboundSetHealthPacket.getFood()); - player.getFoodData().setSaturation(clientboundSetHealthPacket.getSaturation()); + + int food = clientboundSetHealthPacket.getFood(); + float saturation = clientboundSetHealthPacket.getSaturation(); + + player.getFoodData().setFoodLevel(food); + player.getFoodData().setSaturation(saturation); + + for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { + if (Objects.equals(replayViewer.lastFirstPersonDataUUID, player.getUUID())) { + replayViewer.lastFirstPersonFoodLevel = food; + replayViewer.lastFirstPersonSaturationLevel = saturation; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteFoodData(player.getId(), food, saturation)); + } + } } } @@ -1414,7 +1481,6 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleCustomPayload(ClientboundCustomPayloadPacket clientboundCustomPayloadPacket) { - // todo: handle some custom packets here? forward(clientboundCustomPayloadPacket); } diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java b/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java index c6879c2..e7f3987 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java @@ -9,6 +9,7 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.stats.Stat; import net.minecraft.world.damagesource.DamageSource; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.biome.BiomeManager; @@ -18,6 +19,16 @@ import java.util.UUID; public class ReplayPlayer extends ServerPlayer { public boolean followLocalPlayerNextTick = false; public UUID spectatingUuid = null; + public int spectatingUuidTickCount = 0; + + public UUID lastFirstPersonDataUUID = null; + public int lastFirstPersonSelectedSlot = -1; + public ItemStack[] lastFirstPersonHotbarItems = new ItemStack[9]; + public float lastFirstPersonExperienceProgress = 0.0f; + public int lastFirstPersonTotalExperience = 0; + public int lastFirstPersonExperienceLevel = 0; + public int lastFirstPersonFoodLevel = 0; + public float lastFirstPersonSaturationLevel = 0; public ReplayPlayer(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation clientInformation) { super(minecraftServer, serverLevel, gameProfile, clientInformation); diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java index 183145a..868b077 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java @@ -4,12 +4,18 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.action.PositionAndAngle; import com.moulberry.flashback.ext.LevelChunkExt; import com.moulberry.flashback.TempFolderProvider; import com.moulberry.flashback.keyframe.handler.ReplayServerKeyframeHandler; +import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; import com.moulberry.flashback.packet.FlashbackClearParticles; import com.moulberry.flashback.packet.FlashbackForceClientTick; import com.moulberry.flashback.packet.FlashbackInstantlyLerp; +import com.moulberry.flashback.packet.FlashbackRemoteExperience; +import com.moulberry.flashback.packet.FlashbackRemoteFoodData; +import com.moulberry.flashback.packet.FlashbackRemoteSelectHotbarSlot; +import com.moulberry.flashback.packet.FlashbackRemoteSetSlot; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.ext.MinecraftExt; @@ -30,6 +36,7 @@ import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; import net.minecraft.core.registries.Registries; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.codec.StreamCodec; @@ -53,8 +60,11 @@ import net.minecraft.server.players.PlayerList; import net.minecraft.world.BossEvent; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.food.FoodData; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.WorldDataConfiguration; @@ -75,9 +85,11 @@ import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.TreeMap; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; @@ -108,7 +120,7 @@ public class ReplayServer extends IntegratedServer { public boolean followLocalPlayerNextTickIfWrongDimension = false; public boolean isProcessingSnapshot = false; private boolean processedSnapshot = false; - private volatile boolean fastForwarding = false; + public volatile boolean fastForwarding = false; private int printFailedDecodePacketCount = 8; @@ -409,6 +421,18 @@ public class ReplayServer extends IntegratedServer { } } + public float getPartialServerTick() { + if (this.replayPaused || this.isPaused()) { + return 1.0f; + } else { + long currentNanos = Util.getNanos(); + long nanosPerTick = this.tickRateManager().nanosecondsPerTick(); + + double partial = (currentNanos - this.lastTickTimeNanos) / (double) nanosPerTick; + return Math.max(0, Math.min(1, (float) partial)); + } + } + public int getTotalReplayTicks() { return this.totalTicks; } @@ -546,6 +570,13 @@ public class ReplayServer extends IntegratedServer { this.gamePacketHandler.handleCreateLocalPlayer(friendlyByteBuf); } + public void handleAccuratePlayerPosition(RegistryFriendlyByteBuf friendlyByteBuf) { + var packet = FlashbackAccurateEntityPosition.STREAM_CODEC.decode(friendlyByteBuf); + for (ReplayPlayer replayViewer : this.replayViewers) { + ServerPlayNetworking.send(replayViewer, packet); + } + } + public void handleMoveEntities(RegistryFriendlyByteBuf friendlyByteBuf) { this.gamePacketHandler.flushPendingEntities(); this.configurationPacketHandler.flushPendingConfiguration(); @@ -622,7 +653,8 @@ public class ReplayServer extends IntegratedServer { public void clearLevel(ServerLevel serverLevel) { for (ServerPlayer player : new ArrayList<>(serverLevel.players())) { - if (player instanceof ReplayPlayer) { + if (player instanceof ReplayPlayer replayPlayer) { + replayPlayer.lastFirstPersonDataUUID = null; continue; } player.connection.disconnect(Component.empty()); @@ -664,15 +696,30 @@ public class ReplayServer extends IntegratedServer { replayReader.handleSnapshot(this); } +// this.accurateEntityPositions = this.pendingAccurateEntityPositions; +// this.pendingAccurateEntityPositions = new ConcurrentHashMap<>(); this.lastReplayTick = this.currentTick; this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick(); // Update list of replay viewers this.replayViewers.clear(); + for (ServerPlayer player : this.getPlayerList().getPlayers()) { if (player instanceof ReplayPlayer replayPlayer) { - Entity cameraEntity = replayPlayer.getCamera(); - replayPlayer.spectatingUuid = cameraEntity == null || cameraEntity == replayPlayer ? null : cameraEntity.getUUID(); + if (replayPlayer.isShiftKeyDown()) { + replayPlayer.spectatingUuid = null; + replayPlayer.spectatingUuidTickCount = 0; + } else { + Entity cameraEntity = replayPlayer.getCamera(); + if (cameraEntity != null && cameraEntity != replayPlayer) { + replayPlayer.spectatingUuid = cameraEntity.getUUID(); + replayPlayer.spectatingUuidTickCount = 20; + } else if (replayPlayer.spectatingUuidTickCount > 0) { + replayPlayer.spectatingUuidTickCount -= 1; + } else { + replayPlayer.spectatingUuid = null; + } + } this.replayViewers.add(replayPlayer); } } @@ -724,6 +771,80 @@ public class ReplayServer extends IntegratedServer { this.tryFollowLocalPlayer(); + // Update first person data + for (ReplayPlayer replayViewer : this.replayViewers) { + // Ensure replay viewers are still spectating + if (replayViewer.spectatingUuid != null) { + Entity camera = replayViewer.getCamera(); + if (camera == null || camera == replayViewer || camera.isRemoved()) { + Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid); + if (targetEntity != null && !targetEntity.isRemoved()) { + replayViewer.setCamera(targetEntity); + } + } + } + + Entity camera = replayViewer.getCamera(); + if (camera != replayViewer && camera instanceof Player playerCamera) { + Inventory inventory = playerCamera.getInventory(); + if (!Objects.equals(replayViewer.lastFirstPersonDataUUID, playerCamera.getUUID())) { + replayViewer.lastFirstPersonDataUUID = playerCamera.getUUID(); + + replayViewer.lastFirstPersonExperienceProgress = playerCamera.experienceProgress; + replayViewer.lastFirstPersonTotalExperience = playerCamera.totalExperience; + replayViewer.lastFirstPersonExperienceLevel = playerCamera.experienceLevel; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteExperience(playerCamera.getId(), playerCamera.experienceProgress, + playerCamera.totalExperience, playerCamera.experienceLevel)); + + FoodData foodData = playerCamera.getFoodData(); + replayViewer.lastFirstPersonFoodLevel = foodData.getFoodLevel(); + replayViewer.lastFirstPersonSaturationLevel = foodData.getSaturationLevel(); + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteFoodData(playerCamera.getId(), foodData.getFoodLevel(), foodData.getSaturationLevel())); + + replayViewer.lastFirstPersonSelectedSlot = inventory.selected; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteSelectHotbarSlot(playerCamera.getId(), inventory.selected)); + + for (int i = 0; i < 9; i++) { + ItemStack hotbarItem = inventory.getItem(i); + replayViewer.lastFirstPersonHotbarItems[i] = hotbarItem.copy(); + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteSetSlot(playerCamera.getId(), i, hotbarItem.copy())); + } + } else { + if (replayViewer.lastFirstPersonExperienceProgress != playerCamera.experienceProgress || + replayViewer.lastFirstPersonTotalExperience != playerCamera.totalExperience || + replayViewer.lastFirstPersonExperienceLevel != playerCamera.experienceLevel) { + replayViewer.lastFirstPersonExperienceProgress = playerCamera.experienceProgress; + replayViewer.lastFirstPersonTotalExperience = playerCamera.totalExperience; + replayViewer.lastFirstPersonExperienceLevel = playerCamera.experienceLevel; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteExperience(playerCamera.getId(), playerCamera.experienceProgress, + playerCamera.totalExperience, playerCamera.experienceLevel)); + } + + FoodData foodData = playerCamera.getFoodData(); + if (replayViewer.lastFirstPersonFoodLevel != foodData.getFoodLevel() || replayViewer.lastFirstPersonSaturationLevel != foodData.getSaturationLevel()) { + replayViewer.lastFirstPersonFoodLevel = foodData.getFoodLevel(); + replayViewer.lastFirstPersonSaturationLevel = foodData.getSaturationLevel(); + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteFoodData(playerCamera.getId(), foodData.getFoodLevel(), foodData.getSaturationLevel())); + } + + if (replayViewer.lastFirstPersonSelectedSlot != inventory.selected) { + replayViewer.lastFirstPersonSelectedSlot = inventory.selected; + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteSelectHotbarSlot(playerCamera.getId(), inventory.selected)); + } + + for (int i = 0; i < 9; i++) { + ItemStack hotbarItem = inventory.getItem(i); + if (!ItemStack.matches(replayViewer.lastFirstPersonHotbarItems[i], hotbarItem)) { + replayViewer.lastFirstPersonHotbarItems[i] = hotbarItem.copy(); + ServerPlayNetworking.send(replayViewer, new FlashbackRemoteSetSlot(playerCamera.getId(), i, hotbarItem.copy())); + } + } + } + } else { + replayViewer.lastFirstPersonDataUUID = null; + } + } + // Update resourcepacks if (this.remotePacks.isEmpty()) { if (!this.oldRemotePacks.isEmpty()) { @@ -808,21 +929,6 @@ public class ReplayServer extends IntegratedServer { replayViewer.connection.chunkSender.sendNextChunks(replayViewer); ServerPlayNetworking.send(replayViewer, FlashbackInstantlyLerp.INSTANCE); ServerPlayNetworking.send(replayViewer, FlashbackClearParticles.INSTANCE); - - // Ensure replay viewers are still spectating - if (replayViewer.spectatingUuid != null) { - Entity camera = replayViewer.getCamera(); - if (camera == null || camera == replayViewer || camera.isRemoved()) { - Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid); - if (targetEntity != null && !targetEntity.isRemoved()) { - replayViewer.setCamera(targetEntity); - } else { - replayViewer.spectatingUuid = null; - } - } else { - replayViewer.spectatingUuid = null; - } - } } for (ServerLevel level : this.getAllLevels()) { for (ServerPlayer player : level.players()) { diff --git a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java index c449321..656eb09 100644 --- a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java +++ b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java @@ -48,6 +48,8 @@ public class IgnoredPacketSet { ClientboundForgetLevelChunkPacket.class, ClientboundPlayerAbilitiesPacket.class, ClientboundSetCarriedItemPacket.class, + ClientboundSetExperiencePacket.class, + ClientboundSetHealthPacket.class, ClientboundTickingStatePacket.class, ClientboundTickingStepPacket.class, ClientboundPlayerCombatEndPacket.class, diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java index 48a83eb..e098b95 100644 --- a/src/main/java/com/moulberry/flashback/record/Recorder.java +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -10,7 +10,7 @@ import com.moulberry.flashback.action.*; import com.moulberry.flashback.io.AsyncReplaySaver; import com.moulberry.flashback.io.ReplayWriter; import com.moulberry.flashback.mixin.compat.bobby.FakeChunkManagerAccessor; -import de.johni0702.minecraft.bobby.FakeChunkManager; +import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; import io.netty.buffer.ByteBuf; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.SharedConstants; @@ -34,8 +34,6 @@ import net.minecraft.nbt.Tag; import net.minecraft.network.ConnectionProtocol; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.PlayerChatMessage; -import net.minecraft.network.chat.SignedMessageBody; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; @@ -59,6 +57,7 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.food.FoodData; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.GameRules; @@ -69,6 +68,7 @@ import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.saveddata.maps.MapDecoration; import net.minecraft.world.level.saveddata.maps.MapId; import net.minecraft.world.level.saveddata.maps.MapItemSavedData; +import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.*; import java.nio.file.Path; @@ -77,6 +77,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.function.Consumer; public class Recorder { @@ -107,8 +108,15 @@ public class Recorder { // Local player data private final List lastPlayerEntityMeta = new ArrayList<>(); private final Map lastPlayerEquipment = new EnumMap<>(EquipmentSlot.class); + private final ItemStack[] lastHotbarItems = new ItemStack[9]; private BlockPos lastDestroyPos = null; private int lastDestroyProgress = -1; + private int lastSelectedSlot = -1; + private float lastExperienceProgress = -1; + private int lastTotalExperience = -1; + private int lastExperienceLevel = -1; + private int lastFoodLevel = -1; + private float lastSaturationLevel = -1; private boolean wasSwinging = false; private int lastSwingTime = -1; @@ -143,6 +151,10 @@ public class Recorder { this.metadata.replayMarkers.put(this.writtenTicks, marker); } + public void submitCustomTask(Consumer consumer) { + this.asyncReplaySaver.submit(consumer); + } + public void setRegistryAccess(RegistryAccess registryAccess) { this.asyncReplaySaver.submit(writer -> writer.setRegistryAccess(registryAccess)); this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); @@ -162,6 +174,29 @@ public class Recorder { return builder.toString(); } + private long lastPositionNanos; + private PositionAndAngle lastPlayerPositionAndAngle = null; + private Vec3 nextPlayerPosition = null; + private final TreeMap partialPositions = new TreeMap<>(); + + public void trackPartialPosition(Entity entity, float partialTick) { + int localPlayerUpdatesPerSecond = Flashback.getConfig().localPlayerUpdatesPerSecond; + if (localPlayerUpdatesPerSecond <= 20) { + return; + } + + long currentNanos = System.nanoTime(); + + double x = Mth.lerp(partialTick, entity.xo, entity.getX()); + double y = Mth.lerp(partialTick, entity.yo, entity.getY()); + double z = Mth.lerp(partialTick, entity.zo, entity.getZ()); + float yaw = entity.getViewYRot(partialTick); + float pitch = entity.getViewXRot(partialTick); + + this.nextPlayerPosition = new Vec3(entity.getX(), entity.getY(), entity.getZ()); + this.partialPositions.put(currentNanos, new PositionAndAngle(x, y, z, yaw, pitch)); + } + public void endTick(boolean close) { if (this.closeForWriting) { return; @@ -185,11 +220,77 @@ public class Recorder { boolean isLevelLoaded = !(Minecraft.getInstance().screen instanceof ReceivingLevelScreen); boolean changedDimensions = false; + int localPlayerUpdatesPerSecond = Flashback.getConfig().localPlayerUpdatesPerSecond; + boolean trackAccurateFirstPersonPosition = localPlayerUpdatesPerSecond > 20; + if (minecraft.level != null && (minecraft.getOverlay() == null || !minecraft.getOverlay().isPauseScreen()) && !minecraft.isPaused() && !this.isPaused && isLevelLoaded) { this.writeEntityPositions(); this.writeLocalData(); + if (trackAccurateFirstPersonPosition) { + long nanos = System.nanoTime(); + + LocalPlayer player = Minecraft.getInstance().player; + if (player == null || this.nextPlayerPosition == null) { + this.lastPlayerPositionAndAngle = null; + } else if (this.lastPlayerPositionAndAngle == null) { + this.lastPlayerPositionAndAngle = new PositionAndAngle(this.nextPlayerPosition.x, this.nextPlayerPosition.y, this.nextPlayerPosition.z, + player.getYRot(), player.getXRot()); + } else { + int divisions = localPlayerUpdatesPerSecond / 20; + PositionAndAngle newPosition = new PositionAndAngle(this.nextPlayerPosition.x, this.nextPlayerPosition.y, this.nextPlayerPosition.z, + player.getYRot(), player.getXRot()); + + if (!this.lastPlayerPositionAndAngle.equals(newPosition)) { + List interpolatedPositions = new ArrayList<>(); + + for (int i = 0; i <= divisions; i++) { + double amount = (double) i / divisions; + double partialNanos = this.lastPositionNanos + (nanos - this.lastPositionNanos) * amount; + long partialNanosRounded = (long) partialNanos; + + Long floorNanos = this.lastPositionNanos; + PositionAndAngle floorPosition = this.lastPlayerPositionAndAngle; + Long ceilNanos = nanos; + PositionAndAngle ceilPosition = newPosition; + + Map.Entry floorEntry = this.partialPositions.floorEntry(partialNanosRounded); + Map.Entry ceilEntry = this.partialPositions.ceilingEntry(partialNanosRounded + 1); + + if (floorEntry != null) { + floorNanos = floorEntry.getKey(); + floorPosition = floorEntry.getValue(); + } + if (ceilEntry != null) { + ceilNanos = ceilEntry.getKey(); + ceilPosition = ceilEntry.getValue(); + } + + double lerpAmount = 0.5; + if (!Objects.equals(ceilNanos, floorNanos)) { + lerpAmount = (partialNanos - floorNanos) / (ceilNanos - floorNanos); + } + + PositionAndAngle interpolatedPosition = floorPosition.lerp(ceilPosition, lerpAmount); + interpolatedPositions.add(interpolatedPosition); + } + + FlashbackAccurateEntityPosition accurateEntityPosition = new FlashbackAccurateEntityPosition(player.getId(), interpolatedPositions); + this.asyncReplaySaver.submit(writer -> { + writer.startAction(ActionAccuratePlayerPosition.INSTANCE); + FlashbackAccurateEntityPosition.STREAM_CODEC.encode(writer.friendlyByteBuf(), accurateEntityPosition); + writer.finishAction(ActionAccuratePlayerPosition.INSTANCE); + }); + + this.lastPlayerPositionAndAngle = newPosition; + } + } + + this.partialPositions.clear(); + this.lastPositionNanos = nanos; + } + this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); this.writtenTicksInChunk += 1; this.writtenTicks += 1; @@ -208,6 +309,16 @@ public class Recorder { this.lastDimensionType = dimension; changedDimensions = true; } + } else if (trackAccurateFirstPersonPosition) { + this.partialPositions.clear(); + this.lastPositionNanos = System.nanoTime(); + + LocalPlayer player = Minecraft.getInstance().player; + if (player != null) { + this.lastPlayerPositionAndAngle = new PositionAndAngle(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); + } else { + this.lastPlayerPositionAndAngle = null; + } } this.finishedPausing |= this.wasPaused && !this.isPaused; @@ -285,11 +396,41 @@ public class Recorder { this.lastPlayerEquipment.clear(); this.lastDestroyPos = null; this.lastDestroyProgress = -1; + this.lastSelectedSlot = -1; + this.lastExperienceProgress = -1; + this.lastTotalExperience = -1; + this.lastExperienceLevel = -1; + this.lastFoodLevel = -1; + this.lastSaturationLevel = -1; + Arrays.fill(this.lastHotbarItems, null); return; } List> gamePackets = new ArrayList<>(); + if (Flashback.getConfig().recordHotbar) { + if (player.experienceProgress != this.lastExperienceProgress || player.totalExperience != this.lastTotalExperience || + player.experienceLevel != this.lastExperienceLevel) { + this.lastExperienceProgress = player.experienceProgress; + this.lastTotalExperience = player.totalExperience; + this.lastExperienceLevel = player.experienceLevel; + gamePackets.add(new ClientboundSetExperiencePacket(player.experienceProgress, player.totalExperience, player.experienceLevel)); + } + + FoodData foodData = player.getFoodData(); + if (foodData.getFoodLevel() != this.lastFoodLevel || foodData.getSaturationLevel() != this.lastSaturationLevel) { + this.lastFoodLevel = foodData.getFoodLevel(); + this.lastSaturationLevel = foodData.getSaturationLevel(); + gamePackets.add(new ClientboundSetHealthPacket(player.getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel())); + } + + int selectedSlot = player.getInventory().selected; + if (selectedSlot != this.lastSelectedSlot) { + gamePackets.add(new ClientboundSetCarriedItemPacket(selectedSlot)); + this.lastSelectedSlot = selectedSlot; + } + } + // Update entity data SynchedEntityData.DataItem[] items = Minecraft.getInstance().player.getEntityData().itemsById; List> changedData = new ArrayList<>(); @@ -329,6 +470,21 @@ public class Recorder { gamePackets.add(new ClientboundSetEquipmentPacket(player.getId(), changedSlots)); } + if (Flashback.getConfig().recordHotbar) { + for (int i = 0; i < this.lastHotbarItems.length; i++) { + ItemStack hotbarItem = player.getInventory().getItem(i); + + if (this.lastHotbarItems[i] == null) { + this.lastHotbarItems[i] = hotbarItem.copy(); + } else if (!ItemStack.matches(this.lastHotbarItems[i], hotbarItem)) { + ItemStack copied = hotbarItem.copy(); + this.lastHotbarItems[i] = copied; + gamePackets.add(new ClientboundContainerSetSlotPacket(-2, 0, i, copied)); + + } + } + } + // Update breaking MultiPlayerGameMode multiPlayerGameMode = Minecraft.getInstance().gameMode; if (multiPlayerGameMode == null) { @@ -734,6 +890,20 @@ public class Recorder { } } + if (Flashback.getConfig().recordHotbar) { + gamePackets.add(new ClientboundSetExperiencePacket(localPlayer.experienceProgress, localPlayer.totalExperience, localPlayer.experienceLevel)); + + FoodData foodData = localPlayer.getFoodData(); + gamePackets.add(new ClientboundSetHealthPacket(localPlayer.getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel())); + + gamePackets.add(new ClientboundSetCarriedItemPacket(localPlayer.getInventory().selected)); + + for (int i = 0; i < 9; i++) { + ItemStack hotbarItem = localPlayer.getInventory().getItem(i); + gamePackets.add(new ClientboundContainerSetSlotPacket(-2, 0, i, hotbarItem.copy())); + } + } + // Entity data for (Entity entity : level.entitiesForRendering()) { if (PacketHelper.shouldIgnoreEntity(entity)) { diff --git a/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java b/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java new file mode 100644 index 0000000..96d85f2 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/UnsupportedLoaderScreen.java @@ -0,0 +1,80 @@ +package com.moulberry.flashback.screen; + +import com.moulberry.flashback.Flashback; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; + +import java.time.Duration; +import java.util.Objects; + +public class UnsupportedLoaderScreen extends Screen { + + private Screen lastScreen; + private final Component title; + private final Component messageText; + private MultiLineLabel message = MultiLineLabel.EMPTY; + private long lastInitTime; + private int countdown = 15; + + public UnsupportedLoaderScreen(Screen lastScreen, Component title, Component message) { + super(title); + this.lastScreen = lastScreen; + this.title = title; + this.messageText = message; + } + + @Override + public Component getNarrationMessage() { + return CommonComponents.joinForNarration(super.getNarrationMessage(), this.messageText); + } + + @Override + protected void init() { + super.init(); + + this.lastInitTime = System.currentTimeMillis(); + this.message = MultiLineLabel.create(this.font, this.messageText, this.width - 50); + int lines = this.message.getLineCount(); + int height = lines * this.font.lineHeight; + int buttonY = Mth.clamp(90 + height + 12, this.height / 6 + 96, this.height - 24); + + this.clearWidgets(); + if (this.countdown == 0) { + var button = Button.builder(Component.literal("I Understand"), b -> { + Flashback.getConfig().nextUnsupportedModLoaderWarning = System.currentTimeMillis() + Duration.ofDays(7).toMillis(); + Flashback.getConfig().saveToDefaultFolder(); + Minecraft.getInstance().setScreen(this.lastScreen); + }).bounds((this.width - 150) / 2, buttonY, 150, 20).build(); + this.addRenderableWidget(button); + } else if (this.countdown <= 10) { + var button = Button.builder(Component.literal("I Understand (" + this.countdown + ")"), b -> {}) + .bounds((this.width - 150) / 2, buttonY, 150, 20).build(); + button.active = false; + this.addRenderableWidget(button); + } + } + + @Override + public void render(GuiGraphics guiGraphics, int i, int j, float f) { + super.render(guiGraphics, i, j, f); + guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, 70, 0xFFFFFF); + this.message.renderCentered(guiGraphics, this.width / 2, 90); + + if (this.countdown > 0 && System.currentTimeMillis() - this.lastInitTime > 1000) { + this.countdown -= 1; + this.init(); + } + } + + @Override + public boolean shouldCloseOnEsc() { + return false; + } + +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java index 4ed6843..09a4ff3 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorState.java +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -8,6 +8,10 @@ import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType; import com.moulberry.flashback.visuals.ReplayVisuals; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.world.entity.Entity; import org.jetbrains.annotations.Nullable; import java.io.IOException; @@ -59,6 +63,28 @@ public class EditorState { this.push(new EditorStateHistoryEntry(undo, redo, description)); } + @Nullable + public Camera getAudioCamera() { + if (this.audioSourceEntity == null) { + return null; + } + + ClientLevel level = Minecraft.getInstance().level; + if (level == null) { + return null; + } + + Entity sourceEntity = level.getEntities().get(this.audioSourceEntity); + if (sourceEntity == null) { + return null; + } + + Camera dummyCamera = new Camera(); + dummyCamera.eyeHeight = sourceEntity.getEyeHeight(); + dummyCamera.setup(level, sourceEntity, false, false, 1.0f); + return dummyCamera; + } + public void push(EditorStateHistoryEntry entry) { if (entry.undo().isEmpty() && entry.redo().isEmpty()) { return; diff --git a/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java b/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java new file mode 100644 index 0000000..830c685 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java @@ -0,0 +1,85 @@ +package com.moulberry.flashback.visuals; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.action.PositionAndAngle; +import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; +import com.moulberry.flashback.playback.ReplayServer; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; + +import java.util.List; + +public class AccurateEntityPositionHandler { + + private static Int2ObjectMap> currentData = null; + private static Int2ObjectMap> pendingData = null; + + public static void tick() { + currentData = pendingData; + pendingData = null; + } + + public static void update(FlashbackAccurateEntityPosition data) { + if (pendingData == null) { + pendingData = new Int2ObjectOpenHashMap<>(); + } + pendingData.put(data.entityId(), data.positionAndAngles()); + } + + public static void apply(ClientLevel level, float partialTick) { + if (currentData == null) { + return; + } + + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null && level != null) { + for (Int2ObjectMap.Entry> entry : currentData.int2ObjectEntrySet()) { + Entity entity = level.getEntity(entry.getIntKey()); + if (entity == null) { + continue; + } + + List positionAndAngles = entry.getValue(); + float amount = partialTick * (positionAndAngles.size() - 1); + + int floorAmount = (int) amount; + PositionAndAngle floorPosition = positionAndAngles.get(floorAmount); + + int ceilAmount = floorAmount + 1; + + if (ceilAmount >= positionAndAngles.size()) { + entity.setYHeadRot(floorPosition.yaw()); + entity.moveTo(floorPosition.x(), floorPosition.y(), floorPosition.z(), floorPosition.yaw(), floorPosition.pitch()); + if (entity instanceof LivingEntity livingEntity) { + livingEntity.lerpSteps = 0; + livingEntity.lerpHeadSteps = 0; + livingEntity.yHeadRotO = livingEntity.yHeadRot; + } + } else { + PositionAndAngle ceilPosition = positionAndAngles.get(ceilAmount); + float partialAmount = amount - floorAmount; + + double x = floorPosition.x() + (ceilPosition.x() - floorPosition.x()) * partialAmount; + double y = floorPosition.y() + (ceilPosition.y() - floorPosition.y()) * partialAmount; + double z = floorPosition.z() + (ceilPosition.z() - floorPosition.z()) * partialAmount; + float yaw = floorPosition.yaw() + Mth.wrapDegrees(ceilPosition.yaw() - floorPosition.yaw()) * partialAmount; + float pitch = floorPosition.pitch() + Mth.wrapDegrees(ceilPosition.pitch() - floorPosition.pitch()) * partialAmount; + + entity.setYHeadRot(Mth.wrapDegrees(yaw)); + entity.moveTo(x, y, z, Mth.wrapDegrees(yaw), Mth.wrapDegrees(pitch)); + if (entity instanceof LivingEntity livingEntity) { + livingEntity.lerpSteps = 0; + livingEntity.lerpHeadSteps = 0; + livingEntity.yHeadRotO = livingEntity.yHeadRot; + } + } + + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java b/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java index b352fd8..4f4276d 100644 --- a/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java +++ b/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java @@ -34,7 +34,7 @@ public class CameraRotation { ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer != null && visuals.overrideCameraShake && (Flashback.isExporting() || !replayServer.replayPaused)) { - float tick = replayServer.getPartialReplayTick(); + float tick = Flashback.isExporting() ? (float) Flashback.EXPORT_JOB.getCurrentTickDouble() : replayServer.getPartialReplayTick(); if (tick < lastShakeReplayTick) { lastShakeReplayTick = tick; shakeTimeY = 0.0f; diff --git a/src/main/resources/assets/flashback/lang/en_us.json b/src/main/resources/assets/flashback/lang/en_us.json index 96d2819..043a00f 100644 --- a/src/main/resources/assets/flashback/lang/en_us.json +++ b/src/main/resources/assets/flashback/lang/en_us.json @@ -7,6 +7,8 @@ "flashback.select_replay.delete_question": "Are you sure you want to delete this replay?", "flashback.select_replay.duration": "Duration: %s", + "flashback.option.per_second": "%s/s", + "flashback.option.automatically_start": "Automatically Start", "flashback.option.automatically_start.description": "Automatically starts a replay recording when joining a world/server", "flashback.option.automatically_finish": "Automatically Finish", @@ -18,5 +20,9 @@ "flashback.option.hide_pause_menu_controls": "Hide Pause Controls", "flashback.option.hide_pause_menu_controls.description": "Hide Pause (ESC) menu controls for starting/finishing a replay. The commands will still work", "flashback.option.mark_dimension_changes": "Mark Dimension Changes", - "flashback.option.mark_dimension_changes.description": "Automatically add a marker to the replay when switching dimensions" + "flashback.option.mark_dimension_changes.description": "Automatically add a marker to the replay when switching dimensions", + "flashback.option.record_hotbar": "Record Hotbar", + "flashback.option.record_hotbar.description": "Adds first-person hotbar information to recorded replays", + "flashback.option.local_player_updates_per_second": "First-person Updates", + "flashback.option.local_player_updates_per_second.description": "The update rate per second for the position/angle of the first-person player" } diff --git a/src/main/resources/assets/flashback/world_marker_circle.png b/src/main/resources/assets/flashback/world_marker_circle.png new file mode 100644 index 0000000000000000000000000000000000000000..d8ec35937dd8cac2e473efaa71f7d894fb54cd06 GIT binary patch literal 696 zcmV;p0!RIcP)xTczOCn``?G@QZRi3Tpz z;BfsaW+2CMgf_?C?at#TckgcZ`}WP=%)IxEijlMeYyfM(DzE~yfJNX<`q(XS1B`$n zZ~>eHKg?`c<^5SjqCWv`U<>##<iVrHl1 z6XA(39AqS(q~&1Ji7;t;n^tnU(VjGIw(`OTI8AHz92o+eX7=l;2-wY7JW1Q`#0W@h z>~r8PdGi}sGqX`S0(KmTCu!W7Gz7Ns!}bFM(jMNrBLmix=KBa}WI$(9h1j#WE|g3L z_%4-ACipFuE}7u7T)s3Md^Sv!jPThqQ!>GC(^Sa_pKWvH1(e&y$&wL`Y@K!AJZ&?G ej1_9!KK~aWW${J1OQ#_K0000