commit 9c4a30d224439ce789b012e24e979c03184965a0 Author: Moulberry Date: Fri Jun 28 18:28:24 2024 +0800 Initial diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c476faf --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ + +# java + +hs_err_*.log +replay_*.log +*.hprof +*.jfr diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..8979dea --- /dev/null +++ b/build.gradle @@ -0,0 +1,127 @@ +buildscript { + repositories { + mavenCentral() + maven { url 'https://jitpack.io' } + maven { url "https://plugins.gradle.org/m2/" } + } + dependencies { + classpath "gradle.plugin.com.github.johnrengelman:shadow:7.1.0" + } +} + +plugins { + id 'fabric-loom' version '1.6-SNAPSHOT' + id 'com.github.johnrengelman.shadow' version "7.1.2" + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. + maven { url = "https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1" } +} + +loom { + accessWidenerPath.set(new File(rootDir, "src/main/resources/flashback.accesswidener")) + splitEnvironmentSourceSets() + + mods { + "flashback" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } + +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings loom.officialMojangMappings() + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + modRuntimeOnly("me.djtheredstoner:DevAuth-fabric:1.1.2") + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + +// shadow(implementation("org.jcodec:jcodec:0.2.5")) +// shadow(implementation("org.jcodec:jcodec-javase:0.2.5")) + shadow(implementation("io.humble:humble-video-all:0.3.0")) + + // ImGui + shadow(implementation(rootProject.files('deps/imgui-java-binding-1.86.11-10-g0dbf36c.jar'))) + shadow(implementation("io.github.spair:imgui-java-lwjgl3:1.86.10") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api(rootProject.files('deps/imgui-java-natives-linux-1.86.11-10-g0dbf36c.jar'))) + shadow(api(rootProject.files('deps/imgui-java-natives-macos-1.86.11-10-g0dbf36c.jar'))) + shadow(api(rootProject.files('deps/imgui-java-natives-windows-1.86.11-10-g0dbf36c.jar'))) +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 21 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +jar { + from("LICENSE") { + rename { "${it}_${project.base.archivesName.get()}"} + } +} + + +shadowJar { + configurations = [project.configurations.shadow] + archiveBaseName = "Flashback-all.jar" + destinationDirectory = file("${buildDir}/tmp/allJar") + + exclude("LICENSE") + exclude("LICENSE.txt") +} + +// configure the maven publication +publishing { + publications { + create("mavenJava", MavenPublication) { + artifactId = project.archives_base_name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} diff --git a/deps/imgui-java-binding-1.86.11-10-g0dbf36c.jar b/deps/imgui-java-binding-1.86.11-10-g0dbf36c.jar new file mode 100644 index 0000000..b78a11e Binary files /dev/null and b/deps/imgui-java-binding-1.86.11-10-g0dbf36c.jar differ diff --git a/deps/imgui-java-lwjgl3-1.86.11-10-g0dbf36c.jar b/deps/imgui-java-lwjgl3-1.86.11-10-g0dbf36c.jar new file mode 100644 index 0000000..ac6f5f0 Binary files /dev/null and b/deps/imgui-java-lwjgl3-1.86.11-10-g0dbf36c.jar differ diff --git a/deps/imgui-java-natives-linux-1.86.11-10-g0dbf36c.jar b/deps/imgui-java-natives-linux-1.86.11-10-g0dbf36c.jar new file mode 100644 index 0000000..3400bb5 Binary files /dev/null and b/deps/imgui-java-natives-linux-1.86.11-10-g0dbf36c.jar differ diff --git a/deps/imgui-java-natives-macos-1.86.11-10-g0dbf36c.jar b/deps/imgui-java-natives-macos-1.86.11-10-g0dbf36c.jar new file mode 100644 index 0000000..3e2bf56 Binary files /dev/null and b/deps/imgui-java-natives-macos-1.86.11-10-g0dbf36c.jar differ diff --git a/deps/imgui-java-natives-windows-1.86.11-10-g0dbf36c.jar b/deps/imgui-java-natives-windows-1.86.11-10-g0dbf36c.jar new file mode 100644 index 0000000..0a30ccf Binary files /dev/null and b/deps/imgui-java-natives-windows-1.86.11-10-g0dbf36c.jar differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..acdf74b --- /dev/null +++ b/gradle.properties @@ -0,0 +1,17 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true + +# Fabric Properties +# check these on https://fabricmc.net/develop +minecraft_version=1.20.6 +yarn_mappings=1.20.6+build.1 +loader_version=0.15.10 + +# Mod Properties +mod_version=1.0.0 +maven_group=com.example +archives_base_name=modid + +# Dependencies +fabric_version=0.97.8+1.20.6 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..7101f8e --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..75c4d72 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} \ No newline at end of file diff --git a/src/client/java/com/moulberry/flashback/ChunkSectionHash.java b/src/client/java/com/moulberry/flashback/ChunkSectionHash.java new file mode 100644 index 0000000..6c2d5df --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ChunkSectionHash.java @@ -0,0 +1,4 @@ +package com.moulberry.flashback; + +public record ChunkSectionHash(short nonEmptyBlockCount, long blockHash, long biomeHash) { +} diff --git a/src/client/java/com/moulberry/flashback/FlashbackClient.java b/src/client/java/com/moulberry/flashback/FlashbackClient.java new file mode 100644 index 0000000..469d3ef --- /dev/null +++ b/src/client/java/com/moulberry/flashback/FlashbackClient.java @@ -0,0 +1,177 @@ +package com.moulberry.flashback; + +import com.mojang.brigadier.context.CommandContext; +import com.mojang.serialization.Lifecycle; +import com.moulberry.flashback.action.ActionConfigurationPacket; +import com.moulberry.flashback.action.ActionCreateLocalPlayer; +import com.moulberry.flashback.action.ActionGamePacket; +import com.moulberry.flashback.action.ActionMoveEntities; +import com.moulberry.flashback.action.ActionNextTick; +import com.moulberry.flashback.action.ActionRegistry; +import com.moulberry.flashback.exporting.ExportJob; +import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.playback.EmptyLevelSource; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.record.Recorder; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.commands.Commands; +import net.minecraft.core.*; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.*; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.world.Difficulty; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.WorldDimensions; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.PrimaryLevelData; +import org.apache.commons.io.FileUtils; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class FlashbackClient implements ClientModInitializer { + public static final Logger LOGGER = LoggerFactory.getLogger("flashback"); + + public static final int MAGIC = 0xD780E884; + public static Recorder RECORDER = null; + public static ExportJob EXPORT_JOB = null; + + public static ResourceLocation createResourceLocation(String value) { + return new ResourceLocation("flashback", value); + } + + @Override + public void onInitializeClient() { + ActionRegistry.register(ActionNextTick.INSTANCE); + ActionRegistry.register(ActionGamePacket.INSTANCE); + ActionRegistry.register(ActionConfigurationPacket.INSTANCE); + ActionRegistry.register(ActionCreateLocalPlayer.INSTANCE); + ActionRegistry.register(ActionMoveEntities.INSTANCE); + + ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + var flashback = ClientCommandManager.literal("flashback"); + flashback.then(ClientCommandManager.literal("start").executes(this::startReplay)); + flashback.then(ClientCommandManager.literal("end").executes(this::endReplay)); + dispatcher.register(flashback); + }); + } + + @Nullable + public static ReplayServer getReplayServer() { + if (Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer replayServer) { + return replayServer; + } + return null; + } + + public static boolean isInReplay() { + return Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer; + } + + private int startReplay(CommandContext command) { + Recorder recorder = new Recorder(Minecraft.getInstance().player.registryAccess()); + recorder.writeInitial(); + RECORDER = recorder; + return 0; + } + + private int endReplay(CommandContext command) { + Recorder recorder = RECORDER; + RECORDER = null; + recorder.endTick(true); + recorder.export(FabricLoader.getInstance().getGameDir().resolve("debug_recording.zip")); + return 0; + } + + @Nullable + public static AbstractClientPlayer getSpectatingPlayer() { + if (!isInReplay()) { + return null; + } + if (Minecraft.getInstance().getCameraEntity() instanceof AbstractClientPlayer clientPlayer) { + if (clientPlayer != Minecraft.getInstance().player) { + return clientPlayer; + } + } + return null; + } + + // todo: delete on start + public static Path getReplayServerTemp() { + return FabricLoader.getInstance().getGameDir().resolve("replay_server_temp"); + } + + // todo: export any partial recordings + delete on start + public static Path getReplayRecordTemp(UUID uuid) { + return FabricLoader.getInstance().getGameDir().resolve("replay_record_temp") + .resolve(uuid.toString()); + } + + // todo: delete on start + public static Path getReplayPlaybackTemp(UUID uuid) { + return FabricLoader.getInstance().getGameDir().resolve("replay_playback_temp") + .resolve(uuid.toString()); + } + + public static void testReplayWorld() { + try { + Path replayTemp = getReplayServerTemp(); + FileUtils.deleteDirectory(replayTemp.toFile()); + + LevelStorageSource source = new LevelStorageSource(replayTemp.resolve("saves"), replayTemp.resolve("backups"), + Minecraft.getInstance().directoryValidator(), Minecraft.getInstance().getFixerUpper()); + LevelStorageSource.LevelStorageAccess access = source.createAccess("replay"); + PackRepository packRepository = ServerPacksSource.createVanillaTrustedRepository(); + + packRepository.reload(); + + GameRules gameRules = new GameRules(); + gameRules.getRule(GameRules.RULE_DOMOBSPAWNING).set(false, null); + gameRules.getRule(GameRules.RULE_WEATHER_CYCLE).set(false, null); + gameRules.getRule(GameRules.RULE_RANDOMTICKING).set(0, null); + + WorldDataConfiguration worldDataConfiguration = new WorldDataConfiguration(new DataPackConfig(List.of(), List.of()), FeatureFlags.DEFAULT_FLAGS); + LevelSettings levelSettings = new LevelSettings("Replay", GameType.SPECTATOR, false, Difficulty.NORMAL, true, gameRules, worldDataConfiguration); + WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, worldDataConfiguration, false, true); + WorldLoader.InitConfig initConfig = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, 4); + + WorldStem worldStem = Util.blockUntilDone(executor -> WorldLoader.load(initConfig, dataLoadContext -> { + Registry registry = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze(); + + Holder.Reference plains = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.BIOME).getHolder(Biomes.PLAINS).get(); + Holder.Reference overworld = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.DIMENSION_TYPE).getHolder(BuiltinDimensionTypes.OVERWORLD).get(); + + WorldDimensions worldDimensions = new WorldDimensions(Map.of(LevelStem.OVERWORLD, new LevelStem(overworld, new EmptyLevelSource(plains)))); + WorldDimensions.Complete complete = worldDimensions.bake(registry); + + return new WorldLoader.DataLoadOutput<>(new PrimaryLevelData(levelSettings, new WorldOptions(0L, false, false), + complete.specialWorldProperty(), complete.lifecycle()), complete.dimensionsRegistryAccess()); + }, WorldStem::new, Util.backgroundExecutor(), executor)).get(); + + ((MinecraftExt)Minecraft.getInstance()).flashback$startReplayServer(access, packRepository, worldStem); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/client/java/com/moulberry/flashback/Interpolation.java b/src/client/java/com/moulberry/flashback/Interpolation.java new file mode 100644 index 0000000..d656705 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/Interpolation.java @@ -0,0 +1,19 @@ +package com.moulberry.flashback; + +import org.joml.Quaternionf; + +public class Interpolation { + + public static double linear(double from, double to, float amount) { + return from + (to - from) * amount; + } + + public static float linear(float from, float to, float amount) { + return from + (to - from) * amount; + } + + public static Quaternionf linear(Quaternionf from, Quaternionf to, float amount) { + return from.slerp(to, amount, new Quaternionf()); + } + +} diff --git a/src/client/java/com/moulberry/flashback/ReplayVisuals.java b/src/client/java/com/moulberry/flashback/ReplayVisuals.java new file mode 100644 index 0000000..edcbf95 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ReplayVisuals.java @@ -0,0 +1,37 @@ +package com.moulberry.flashback; + +public class ReplayVisuals { + + public static boolean showBossBar = true; + public static boolean showTitleText = true; + public static boolean showScoreboard = true; + public static boolean showActionBar = true; + public static boolean showNametags = true; + public static float overrideFogDistance = 0.0f; + public static float overrideFov = 0.0f; + public static long overrideTimeOfDay = -1; + + public static volatile int forceEntityLerpTicks = 0; + + public static void disable() { + showBossBar = true; + showTitleText = true; + showScoreboard = true; + showActionBar = true; + showNametags = true; + overrideFogDistance = 0.0f; + overrideFov = 0.0f; + forceEntityLerpTicks = 0; + overrideTimeOfDay = -1; + } + + public static void setupReplay() { + disable(); + + showBossBar = false; + showTitleText = false; + showActionBar = false; + showScoreboard = false; + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/Action.java b/src/client/java/com/moulberry/flashback/action/Action.java new file mode 100644 index 0000000..618795e --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/Action.java @@ -0,0 +1,12 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public interface Action { + + ResourceLocation name(); + void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf); + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionConfigurationPacket.java b/src/client/java/com/moulberry/flashback/action/ActionConfigurationPacket.java new file mode 100644 index 0000000..cdf1ab0 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/ActionConfigurationPacket.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionConfigurationPacket implements Action { + + private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/configuration_packet"); + public static final ActionConfigurationPacket INSTANCE = new ActionConfigurationPacket(); + private ActionConfigurationPacket() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleConfigurationPacket(friendlyByteBuf); + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java b/src/client/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java new file mode 100644 index 0000000..01279c1 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionCreateLocalPlayer implements Action { + + private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/create_local_player"); + public static final ActionCreateLocalPlayer INSTANCE = new ActionCreateLocalPlayer(); + private ActionCreateLocalPlayer() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleCreateLocalPlayer(friendlyByteBuf); + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionGamePacket.java b/src/client/java/com/moulberry/flashback/action/ActionGamePacket.java new file mode 100644 index 0000000..3ec7cdf --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/ActionGamePacket.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionGamePacket implements Action { + + private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/game_packet"); + public static final ActionGamePacket INSTANCE = new ActionGamePacket(); + private ActionGamePacket() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleGamePacket(friendlyByteBuf); + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionMoveEntities.java b/src/client/java/com/moulberry/flashback/action/ActionMoveEntities.java new file mode 100644 index 0000000..65e7ef8 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/ActionMoveEntities.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionMoveEntities implements Action { + + private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/move_entities"); + public static final ActionMoveEntities INSTANCE = new ActionMoveEntities(); + private ActionMoveEntities() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleMoveEntities(friendlyByteBuf); + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionNextTick.java b/src/client/java/com/moulberry/flashback/action/ActionNextTick.java new file mode 100644 index 0000000..f269bba --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/ActionNextTick.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionNextTick implements Action { + + private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/next_tick"); + public static final ActionNextTick INSTANCE = new ActionNextTick(); + private ActionNextTick() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleNextTick(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionRegistry.java b/src/client/java/com/moulberry/flashback/action/ActionRegistry.java new file mode 100644 index 0000000..2300a39 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/action/ActionRegistry.java @@ -0,0 +1,40 @@ +package com.moulberry.flashback.action; + +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class ActionRegistry { + + private static final List actions = new ArrayList<>(); + private static final Map resourceToAction = new HashMap<>(); + private static final Set> registeredActions = new HashSet<>(); + + public static void register(Action action) { + if (!registeredActions.add(action.getClass())) { + throw new IllegalArgumentException("Action already registered: " + action.getClass()); + } + if (resourceToAction.containsKey(action.name())) { + throw new IllegalArgumentException("Action already registered by name: " + action.name()); + } + + actions.add(action); + resourceToAction.put(action.name(), action); + } + + public static List getActions() { + return Collections.unmodifiableList(actions); + } + + public static @Nullable Action getAction(ResourceLocation actionName) { + return resourceToAction.get(actionName); + } + +} diff --git a/src/client/java/com/moulberry/flashback/exception/UnsupportedPacketException.java b/src/client/java/com/moulberry/flashback/exception/UnsupportedPacketException.java new file mode 100644 index 0000000..4c804cf --- /dev/null +++ b/src/client/java/com/moulberry/flashback/exception/UnsupportedPacketException.java @@ -0,0 +1,11 @@ +package com.moulberry.flashback.exception; + +import net.minecraft.network.protocol.Packet; + +public class UnsupportedPacketException extends RuntimeException { + + public UnsupportedPacketException(Packet packet) { + super("Packet " + packet.type().id() + " is not supported"); + } + +} diff --git a/src/client/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java b/src/client/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java new file mode 100644 index 0000000..6ccdcfb --- /dev/null +++ b/src/client/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java @@ -0,0 +1,222 @@ +package com.moulberry.flashback.exporting; + +import com.mojang.blaze3d.platform.NativeImage; +import io.humble.ferry.Buffer; +import io.humble.ferry.JNIReference; +import io.humble.video.Codec; +import io.humble.video.Encoder; +import io.humble.video.MediaPacket; +import io.humble.video.MediaPicture; +import io.humble.video.MediaPictureResampler; +import io.humble.video.Muxer; +import io.humble.video.MuxerFormat; +import io.humble.video.PixelFormat; +import io.humble.video.Rational; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; + +public class AsyncVideoEncoder { + + private final Muxer muxer; + private final Encoder encoder; + private final MediaPictureResampler resampler; + private final MediaPacket packet; + private final ArrayBlockingQueue inputQueue; + private final AtomicBoolean shouldEnd = new AtomicBoolean(false); + private final AtomicBoolean finishedWriting = new AtomicBoolean(false); + + public AsyncVideoEncoder(int fps) { + this.inputQueue = new ArrayBlockingQueue<>(32); + final Rational framerate = Rational.make(1, fps); + this.muxer = Muxer.make("new_output.mp4", null, "mp4"); + final MuxerFormat format = this.muxer.getFormat(); + Codec codec = Codec.findEncodingCodec(format.getDefaultVideoCodecId()); + this.encoder = Encoder.make(codec); + + this.encoder.setWidth(1920); + this.encoder.setHeight(1060); + final PixelFormat.Type pixelformat = PixelFormat.Type.PIX_FMT_YUV420P; + this.encoder.setPixelFormat(pixelformat); + this.encoder.setTimeBase(framerate); + + if (format.getFlag(MuxerFormat.Flag.GLOBAL_HEADER)) { + this.encoder.setFlag(Encoder.Flag.FLAG_GLOBAL_HEADER, true); + } + + this.encoder.open(null, null); + this.muxer.addNewStream(this.encoder); + try { + this.muxer.open(null, null); + } catch (InterruptedException | IOException e) { + throw new RuntimeException(e); + } + + this.resampler = MediaPictureResampler.make( + this.encoder.getWidth(), this.encoder.getHeight(), pixelformat, + this.encoder.getWidth(), this.encoder.getHeight(), PixelFormat.Type.PIX_FMT_RGBA, 0); + this.resampler.open(); + + this.packet = MediaPacket.make(); + + record Pictures(MediaPicture picture, MediaPicture pictureRgba) {} + + ArrayBlockingQueue pictureInputQueue = new ArrayBlockingQueue<>(32); + ArrayBlockingQueue pictureOutputQueue = new ArrayBlockingQueue<>(32); + + for (int i = 0; i < 32; i++) { + MediaPicture picture = MediaPicture.make( + this.encoder.getWidth(), + this.encoder.getHeight(), + pixelformat + ); + picture.setTimeBase(framerate); + + MediaPicture pictureRgba = MediaPicture.make( + this.encoder.getWidth(), + this.encoder.getHeight(), + PixelFormat.Type.PIX_FMT_RGBA + ); + + pictureInputQueue.add(new Pictures(picture, pictureRgba)); + } + + AtomicBoolean shouldEndEncoderThread = new AtomicBoolean(false); + + new Thread(() -> { + int currentFrame = 0; + + while (true) { + try { + Pictures pictures = pictureInputQueue.poll(10, TimeUnit.MILLISECONDS); + if (pictures == null) { + if (this.shouldEnd.get()) { + shouldEndEncoderThread.set(true); + return; + } else { + continue; + } + } + + NativeImage src = this.inputQueue.poll(10, TimeUnit.MILLISECONDS); + if (src == null) { + if (this.shouldEnd.get()) { + shouldEndEncoderThread.set(true); + return; + } else { + pictureInputQueue.put(pictures); + continue; + } + } + + final AtomicReference ref = new AtomicReference( + null); + Buffer buffer = pictures.pictureRgba.getData(0); + int size = pictures.pictureRgba.getDataPlaneSize(0); + ByteBuffer pictureByteBuffer = buffer.getByteBuffer(0, + size, ref); + buffer.delete(); + + pictureByteBuffer.order(ByteOrder.nativeOrder()); + for (int pixel : src.getPixelsRGBA()) { + pictureByteBuffer.putInt(pixel); + } + src.close(); + + pictures.pictureRgba.setTimeStamp(currentFrame++); + pictures.pictureRgba.setComplete(true); + + this.resampler.resample(pictures.picture, pictures.pictureRgba); + + if (ref.get() != null) { + ref.get().delete(); + } + + pictureOutputQueue.put(pictures); + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + + new Thread(() -> { + while (true) { + try { + Pictures pictures = pictureOutputQueue.poll(10, TimeUnit.MILLISECONDS); + if (pictures == null) { + if (shouldEndEncoderThread.get()) { + do { + this.encoder.encode(this.packet, null); + if (this.packet.isComplete()) { + this.muxer.write(this.packet, false); + } + } while (this.packet.isComplete()); + + this.muxer.close(); + + this.muxer.delete(); + this.encoder.delete(); + this.resampler.delete(); + this.packet.delete(); + this.finishedWriting.set(true); + + pictures = pictureInputQueue.poll(); + while (pictures != null) { + pictures.picture.delete(); + pictures.pictureRgba.delete(); + pictures = pictureInputQueue.poll(); + } + return; + } else { + continue; + } + } + + do { + this.encoder.encode(this.packet, pictures.picture); + if (this.packet.isComplete()) { + this.muxer.write(this.packet, false); + } + } while (this.packet.isComplete()); + + if (shouldEndEncoderThread.get()) { + pictures.picture.delete(); + pictures.pictureRgba.delete(); + } else { + pictureInputQueue.put(pictures); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }).start(); + } + + public void encode(NativeImage src) { + while (true) { + try { + this.inputQueue.put(src); + return; + } catch (InterruptedException ignored) {} + } + } + + public void finish() { + while (!this.inputQueue.isEmpty()) { + LockSupport.parkNanos("waiting for image queue to empty", 100000L); + } + + this.shouldEnd.set(true); + + while (!this.finishedWriting.get()) { + LockSupport.parkNanos("waiting for encoder thread to finish", 100000L); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/exporting/ExportJob.java b/src/client/java/com/moulberry/flashback/exporting/ExportJob.java new file mode 100644 index 0000000..8bf70ad --- /dev/null +++ b/src/client/java/com/moulberry/flashback/exporting/ExportJob.java @@ -0,0 +1,173 @@ +package com.moulberry.flashback.exporting; + +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.keyframe.Keyframes; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.Screenshot; +import net.minecraft.client.gui.Font; +import net.minecraft.client.renderer.FogRenderer; +import org.joml.Matrix4f; + +import java.util.concurrent.locks.LockSupport; + +public class ExportJob { + + private final int startTick; + private final int endTick; + private final int framesPerTick = 60 / 20; + + private boolean running = false; + private long lastRenderMillis; + private long renderStartTime; + + public ExportJob(int startTick, int endTick) { + this.startTick = startTick; + this.endTick = endTick; + } + + public void run() { + ReplayServer replayServer = FlashbackClient.getReplayServer(); + if (this.running || replayServer == null) { + return; + } + this.running = true; + + AsyncVideoEncoder encoder = new AsyncVideoEncoder(this.framesPerTick * 20); + + int currentFrame = 0; + int totalFrames = (this.endTick - this.startTick + 1) * this.framesPerTick; + int clientTickCount = 0; + + boolean shouldDoTextureDownload = false; + + RenderTarget mainRenderTarget = Minecraft.getInstance().getMainRenderTarget(); + this.renderStartTime = System.currentTimeMillis(); + + while (currentFrame <= totalFrames) { + int targetServerTick = this.startTick + currentFrame / this.framesPerTick; + + // Wait until server is on correct replay tick + while (replayServer.getReplayTick() != targetServerTick) { + replayServer.finishedServerTick.set(false); + replayServer.jumpToTick = targetServerTick; + replayServer.replayPaused = true; + + // Do some work by downloading textures while we're waiting for the server + if (shouldDoTextureDownload) { + shouldDoTextureDownload = false; + finishFrame(encoder, currentFrame-1, totalFrames); + } + + while (!replayServer.finishedServerTick.compareAndExchange(true, false)) { + LockSupport.parkNanos("waiting for server thread", 100000L); + } + } + + if (shouldDoTextureDownload) { + shouldDoTextureDownload = false; + finishFrame(encoder, currentFrame-1, totalFrames); + } + + long targetClientTick = currentFrame / this.framesPerTick; + + // Ensure client isn't frozen so partialTick is correctly used + Minecraft.getInstance().level.tickRateManager().setFrozen(false); + + // Tick client + while (clientTickCount < targetClientTick) { + while (Minecraft.getInstance().pollTask()) {} + Minecraft.getInstance().tick(); + clientTickCount += 1; + } + + float partialTick = (currentFrame / (float) this.framesPerTick) % 1.0f; + Keyframes.applyKeyframes(Minecraft.getInstance(), targetServerTick + partialTick); + + mainRenderTarget.bindWrite(true); + FogRenderer.setupNoFog(); + RenderSystem.enableCull(); + Minecraft.getInstance().timer.partialTick = partialTick; + Minecraft.getInstance().gameRenderer.render(partialTick, Util.getNanos(), true); + mainRenderTarget.unbindWrite(); + + shouldDoTextureDownload = true; + + currentFrame += 1; + } + + if (shouldDoTextureDownload) { + shouldDoTextureDownload = false; + finishFrame(encoder, currentFrame-1, totalFrames); + } + + encoder.finish(); + } + + + private void finishFrame(AsyncVideoEncoder encoder, int currentFrame, int totalFrames) { + RenderTarget mainRenderTarget = Minecraft.getInstance().getMainRenderTarget(); + NativeImage nativeImage = Screenshot.takeScreenshot(mainRenderTarget); + encoder.encode(nativeImage); + Window window = Minecraft.getInstance().getWindow(); + + long currentTime = System.currentTimeMillis(); + if (currentTime - this.lastRenderMillis > 10) { + this.lastRenderMillis = currentTime; + + var bufferSource = Minecraft.getInstance().renderBuffers().bufferSource(); + bufferSource.endBatch(); + mainRenderTarget.bindWrite(true); + + RenderSystem.disableDepthTest(); + Matrix4f matrix = new Matrix4f(); + matrix.translate(0.0f, 0.0f, -11000f); + float x = window.getGuiScaledWidth()/2f; + float y = window.getGuiScaledHeight()/2f; + Font font = Minecraft.getInstance().font; + + String line1 = "Exported Frames: " + currentFrame + "/" + totalFrames; + font.drawInBatch(line1, x - font.width(line1)/2f, y - font.lineHeight, + -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); + + long elapsed = currentTime - this.renderStartTime; + String line2 = "Time elapsed: " + formatTime(elapsed); + font.drawInBatch(line2, x - font.width(line2)/2f, y, + -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); + + if (currentFrame > framesPerTick*20) { + long estimatedRemaining = (currentTime - this.renderStartTime) * (totalFrames - currentFrame) / currentFrame; + String line3 = "Estimated time remaining: " + formatTime(estimatedRemaining); + font.drawInBatch(line3, x - font.width(line3)/2f, y + font.lineHeight, + -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); + } + + bufferSource.endBatch(); + RenderSystem.enableDepthTest(); + + mainRenderTarget.unbindWrite(); + mainRenderTarget.blitToScreen(window.getWidth(), window.getHeight()); + window.updateDisplay(); + } + } + + private String formatTime(long millis) { + long seconds = (millis / 1000) % 60; + long minutes = (millis / 1000 / 60) % 60; + long hours = millis / 1000 / 60 / 60; + + if (hours > 0) { + return hours + "h " + minutes + "m " + seconds + "s"; + } else if (minutes > 0) { + return minutes + "m " + seconds + "s"; + } else { + return seconds + "s"; + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java b/src/client/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java new file mode 100644 index 0000000..2c3520c --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java @@ -0,0 +1,11 @@ +package com.moulberry.flashback.ext; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.MultiBufferSource; + +public interface ItemInHandRendererExt { + + void flashback$renderHandsWithItems(float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, AbstractClientPlayer localPlayer, int i); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java b/src/client/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java new file mode 100644 index 0000000..06413a4 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java @@ -0,0 +1,10 @@ +package com.moulberry.flashback.ext; + +import com.moulberry.flashback.ChunkSectionHash; + +public interface LevelChunkSectionExt { + + ChunkSectionHash flashback$hashState(); + boolean flashback$doesHashedStateMatch(ChunkSectionHash hashedState); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/MinecraftExt.java b/src/client/java/com/moulberry/flashback/ext/MinecraftExt.java new file mode 100644 index 0000000..0f4cc15 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/MinecraftExt.java @@ -0,0 +1,13 @@ +package com.moulberry.flashback.ext; + +import net.minecraft.server.WorldStem; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.world.level.storage.LevelStorageSource; + +public interface MinecraftExt { + + void flashback$forceClientTick(); + void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem); + float flashback$getLocalPlayerPartialTick(); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/PaletteExt.java b/src/client/java/com/moulberry/flashback/ext/PaletteExt.java new file mode 100644 index 0000000..e1345a0 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/PaletteExt.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.ext; + +public interface PaletteExt { + + long flashback$hash(); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java b/src/client/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java new file mode 100644 index 0000000..226bcb3 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java @@ -0,0 +1,13 @@ +package com.moulberry.flashback.ext; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.server.network.ConfigurationTask; + +import java.util.List; + +public interface ServerConfigurationPacketListenerImplExt { + + void flashback$startConfiguration(List> initialPackets, List tasks); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java b/src/client/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java new file mode 100644 index 0000000..82f0387 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java @@ -0,0 +1,13 @@ +package com.moulberry.flashback.ext; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.server.network.ConfigurationTask; + +import java.util.List; + +public interface ServerGamePacketListenerImplExt { + + void flashback$switchToConfigWithTasks(List> initialPackets, List tasks); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java b/src/client/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java new file mode 100644 index 0000000..179df82 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.ext; + +public interface ThreadedLevelLightEngineExt { + + void flashback$submitPost(int x, int z, Runnable runnable); + +} diff --git a/src/client/java/com/moulberry/flashback/io/ReplayReader.java b/src/client/java/com/moulberry/flashback/io/ReplayReader.java new file mode 100644 index 0000000..138f2eb --- /dev/null +++ b/src/client/java/com/moulberry/flashback/io/ReplayReader.java @@ -0,0 +1,112 @@ +package com.moulberry.flashback.io; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.action.Action; +import com.moulberry.flashback.action.ActionRegistry; +import io.netty.buffer.ByteBuf; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ReplayReader { + + private FriendlyByteBuf friendlyByteBuf; + private int replaySnapshotOffset; + private int replayActionsOffset; + private RegistryAccess registryAccess; + private Action lastAction = null; + private final Int2ObjectMap actions = new Int2ObjectOpenHashMap<>(); + + public ReplayReader(ByteBuf byteBuf, RegistryAccess registryAccess) { + this.friendlyByteBuf = new FriendlyByteBuf(byteBuf); + this.registryAccess = registryAccess; + + int magic = this.friendlyByteBuf.readInt(); + if (magic != FlashbackClient.MAGIC) { + throw new RuntimeException("Invalid magic"); + } + + int actions = this.friendlyByteBuf.readVarInt(); + for (int i = 0; i < actions; i++) { + ResourceLocation actionName = this.friendlyByteBuf.readResourceLocation(); + Action action = ActionRegistry.getAction(actionName); + + if (action == null) { + throw new RuntimeException("Missing action: " + actionName); + } else { + this.actions.put(this.actions.size(), action); + } + } + + int snapshotSize = this.friendlyByteBuf.readVarInt(); + this.replaySnapshotOffset = this.friendlyByteBuf.readerIndex(); + this.friendlyByteBuf.skipBytes(snapshotSize); + this.replayActionsOffset = this.friendlyByteBuf.readerIndex(); + } + + public void changeRegistryAccess(RegistryAccess registryAccess) { + this.registryAccess = registryAccess; + } + + public void resetToStart() { + this.friendlyByteBuf.readerIndex(this.replayActionsOffset); + } + + public void handleSnapshot(ReplayServer replayServer) { + this.friendlyByteBuf.readerIndex(this.replaySnapshotOffset); + + replayServer.isProcessingSnapshot = true; + + while (this.friendlyByteBuf.readerIndex() < this.replayActionsOffset) { + int id = this.friendlyByteBuf.readVarInt(); + Action action = this.actions.get(id); + if (action == null) { + throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name()); + } + this.lastAction = action; + + int size = this.friendlyByteBuf.readVarInt(); + ByteBuf slice = this.friendlyByteBuf.readSlice(size); + RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess); + action.handle(replayServer, registryFriendlyByteBuf); + + if (slice.readerIndex() < size) { + throw new RuntimeException("Action " + this.lastAction.name() + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); + } + } + + replayServer.isProcessingSnapshot = false; + } + + public boolean handleNextAction(ReplayServer replayServer) { + if (this.friendlyByteBuf.readerIndex() >= this.friendlyByteBuf.writerIndex()) { + return false; + } + if (this.friendlyByteBuf.readerIndex() < this.replayActionsOffset) { + this.friendlyByteBuf.readerIndex(this.replayActionsOffset); + } + + int id = this.friendlyByteBuf.readVarInt(); + Action action = this.actions.get(id); + if (action == null) { + throw new RuntimeException("Unknown action id: " + id + ". Last action was " + this.lastAction.name()); + } + this.lastAction = action; + + int size = this.friendlyByteBuf.readVarInt(); + ByteBuf slice = this.friendlyByteBuf.readSlice(size); + RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess); + action.handle(replayServer, registryFriendlyByteBuf); + + if (slice.readerIndex() < size) { + throw new RuntimeException("Action " + this.lastAction.name() + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex()); + } + + return true; + } + +} diff --git a/src/client/java/com/moulberry/flashback/io/ReplayWriter.java b/src/client/java/com/moulberry/flashback/io/ReplayWriter.java new file mode 100644 index 0000000..79b74e6 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/io/ReplayWriter.java @@ -0,0 +1,166 @@ +package com.moulberry.flashback.io; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.action.Action; +import com.moulberry.flashback.action.ActionRegistry; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import it.unimi.dsi.fastutil.objects.Reference2IntMap; +import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; + +import java.util.List; +import java.util.Objects; + +public class ReplayWriter { + + private FriendlyByteBuf snapshotBuffer = null; + private final FriendlyByteBuf writeBuffer; + private final ByteBuf dataBufferInner; + private RegistryFriendlyByteBuf dataBuffer; + private Reference2IntMap registeredActions; + private Action writingAction = null; + + private static final int STATE_EMPTY = 0; + private static final int STATE_WRITING_SNAPSHOT = 1; + private static final int STATE_WRITING_DATA = 2; + private int state = STATE_EMPTY; + + public ReplayWriter(RegistryAccess registryAccess) { + this.writeBuffer = new FriendlyByteBuf(Unpooled.buffer()); + this.dataBufferInner = Unpooled.buffer(); + this.dataBuffer = new RegistryFriendlyByteBuf(this.dataBufferInner, registryAccess); + this.writeHeader(); + } + + private void writeHeader() { + this.registeredActions = new Reference2IntOpenHashMap<>(); + this.registeredActions.defaultReturnValue(-1); + + // Reset to start + this.writeBuffer.writerIndex(0); + + // Magic + this.writeBuffer.writeInt(FlashbackClient.MAGIC); + + // Actions + List actions = ActionRegistry.getActions(); + this.writeBuffer.writeVarInt(actions.size()); + for (Action action : ActionRegistry.getActions()) { + this.writeBuffer.writeResourceLocation(action.name()); + this.registeredActions.put(action, this.registeredActions.size()); + } + + this.state = STATE_EMPTY; + } + + public void setRegistryAccess(RegistryAccess registryAccess) { + RegistryFriendlyByteBuf newDataBuffer = new RegistryFriendlyByteBuf(this.dataBufferInner, registryAccess); + newDataBuffer.writerIndex(this.dataBuffer.writerIndex()); + newDataBuffer.readerIndex(this.dataBuffer.readerIndex()); + this.dataBuffer = newDataBuffer; + } + + public void startSnapshot() { + if (this.state == STATE_EMPTY) { + this.state = STATE_WRITING_SNAPSHOT; + this.snapshotBuffer = new FriendlyByteBuf(Unpooled.buffer()); + } else { + throw new IllegalStateException("Can only start snapshot in STATE_EMPTY"); + } + } + + public void endSnapshot() { + if (this.state == STATE_WRITING_SNAPSHOT) { + this.state = STATE_WRITING_DATA; + + byte[] written = new byte[this.snapshotBuffer.writerIndex()]; + this.snapshotBuffer.getBytes(0, written); + this.snapshotBuffer.writerIndex(0); + + this.writeBuffer.writeVarInt(written.length); + this.writeBuffer.writeBytes(written); + } else { + throw new IllegalStateException("Can only end snapshot in STATE_WRITING_SNAPSHOT"); + } + } + + private FriendlyByteBuf getWriteBuffer() { + if (this.state == STATE_EMPTY) { + throw new IllegalStateException("No write buffer in STATE_EMPTY"); + } else if (this.state == STATE_WRITING_SNAPSHOT) { + return this.snapshotBuffer; + } else if (this.state == STATE_WRITING_DATA) { + return this.writeBuffer; + } else { + throw new IllegalStateException("Unknown state: " + this.state); + } + } + + public void startAndFinishAction(Action action) { + Objects.requireNonNull(action); + if (this.writingAction != null) { + throw new RuntimeException("startAndFinishAction() called while still writing " + action.name()); + } + + FriendlyByteBuf writeBuffer = this.getWriteBuffer(); + int id = this.registeredActions.getInt(action); + if (id >= 0) { + writeBuffer.writeVarInt(id); + } else { + throw new RuntimeException("Unknown action: " + action.name()); + } + writeBuffer.writeVarInt(0); + } + + public void startAction(Action action) { + Objects.requireNonNull(action); + if (this.writingAction != null) { + throw new RuntimeException("startAction() called while still writing " + action.name()); + } + this.writingAction = action; + + FriendlyByteBuf writeBuffer = this.getWriteBuffer(); + int id = this.registeredActions.getInt(action); + if (id >= 0) { + writeBuffer.writeVarInt(id); + } else { + throw new RuntimeException("Unknown action: " + action.name()); + } + } + + public void finishAction(Action action) { + Objects.requireNonNull(action); + if (this.writingAction == null) { + throw new RuntimeException("finishAction() called before startAction()"); + } + if (this.writingAction != action) { + throw new RuntimeException("finishAction() called with wrong action, expected " + this.writingAction.name() + ", got " + action.name()); + } + this.writingAction = null; + + byte[] written = new byte[this.dataBuffer.writerIndex()]; + this.dataBuffer.getBytes(0, written); + this.dataBuffer.writerIndex(0); + + FriendlyByteBuf writeBuffer = this.getWriteBuffer(); + writeBuffer.writeVarInt(written.length); + writeBuffer.writeBytes(written); + } + + public RegistryFriendlyByteBuf friendlyByteBuf() { + return this.dataBuffer; + } + + public byte[] popBytes() { + byte[] replay = new byte[this.writeBuffer.writerIndex()]; + this.writeBuffer.getBytes(0, replay); + + this.writeHeader(); + + return replay; + } + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/Keyframe.java b/src/client/java/com/moulberry/flashback/keyframe/Keyframe.java new file mode 100644 index 0000000..41f40f5 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/Keyframe.java @@ -0,0 +1,27 @@ +package com.moulberry.flashback.keyframe; + +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; + +public abstract class Keyframe { + + public final Class operandClass; + private InterpolationType interpolationType = InterpolationType.SMOOTH; + + public Keyframe(Class operandClass) { + this.operandClass = operandClass; + } + + public InterpolationType interpolationType() { + return interpolationType; + } + + public void interpolationType(InterpolationType interpolationType) { + this.interpolationType = interpolationType; + } + + public abstract void apply(T t); + public abstract void applyInterpolated(T t, Keyframe other, float amount); + public abstract void applyInterpolatedSmooth(T t, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, + float lerpAmount, boolean lerpFromRight); + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/KeyframeType.java b/src/client/java/com/moulberry/flashback/keyframe/KeyframeType.java new file mode 100644 index 0000000..e75b1d7 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/KeyframeType.java @@ -0,0 +1,18 @@ +package com.moulberry.flashback.keyframe; + +public enum KeyframeType { + + CAMERA("Camera"), + FOV("FOV"), + SPEED("Speed"), + TIME_OF_DAY("Time of day"); + + public static final KeyframeType[] KEYFRAME_TYPES = values(); + + public final String name; + + KeyframeType(String name) { + this.name = name; + } + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/Keyframes.java b/src/client/java/com/moulberry/flashback/keyframe/Keyframes.java new file mode 100644 index 0000000..2f32f11 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/Keyframes.java @@ -0,0 +1,97 @@ +package com.moulberry.flashback.keyframe; + +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.keyframe.interpolation.SidedInterpolationType; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.client.Minecraft; +import org.lwjgl.glfw.GLFW; + +import java.util.EnumMap; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; + +public class Keyframes { + + public static final EnumMap>> keyframes = new EnumMap<>(KeyframeType.class); + + @SuppressWarnings("unchecked") + public static void applyKeyframes(T t, float tick) { + for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { + TreeMap> keyframeTimes = entry.getValue(); + if (keyframeTimes.isEmpty()) { + continue; + } + + Map.Entry> lowerEntry = keyframeTimes.floorEntry((int) tick); + if (lowerEntry == null) { + continue; + } + + if (lowerEntry.getValue().operandClass != t.getClass()) { + continue; + } + Keyframe lowerKeyframe = (Keyframe) lowerEntry.getValue(); + + SidedInterpolationType leftInterpolation = lowerEntry.getValue().interpolationType().rightSide; + if (leftInterpolation == SidedInterpolationType.HOLD) { + lowerKeyframe.apply(t); + continue; + } + + Map.Entry> ceilEntry = keyframeTimes.ceilingEntry((int) tick); + if (ceilEntry == null) { + continue; + } + + if (Objects.equals(lowerEntry.getKey(), ceilEntry.getKey())) { + lowerKeyframe.apply(t); + continue; + } + + float amount = (tick - lowerEntry.getKey()) / (ceilEntry.getKey() - lowerEntry.getKey()); + + SidedInterpolationType rightInterpolation = ceilEntry.getValue().interpolationType().leftSide; + if (rightInterpolation == SidedInterpolationType.HOLD) { + rightInterpolation = leftInterpolation; + } + + boolean isUsingSmooth = leftInterpolation == SidedInterpolationType.SMOOTH || + rightInterpolation == SidedInterpolationType.SMOOTH; + + if (isUsingSmooth) { + Map.Entry> beforeEntry = keyframeTimes.floorEntry(lowerEntry.getKey() - 1); + if (beforeEntry == null) { + beforeEntry = lowerEntry; + } + + Map.Entry> afterAfterEntry = keyframeTimes.ceilingEntry(ceilEntry.getKey() + 1); + if (afterAfterEntry == null) { + afterAfterEntry = ceilEntry; + } + + float lerpAmount = -1f; + boolean lerpFromRight = false; + if (leftInterpolation != SidedInterpolationType.SMOOTH) { + lerpAmount = SidedInterpolationType.interpolate(leftInterpolation, leftInterpolation, amount); + lerpFromRight = false; + } else if (rightInterpolation != SidedInterpolationType.SMOOTH) { + lerpAmount = SidedInterpolationType.interpolate(rightInterpolation, rightInterpolation, amount); + lerpFromRight = true; + } + + ((Keyframe)beforeEntry.getValue()).applyInterpolatedSmooth(t, lowerEntry.getValue(), ceilEntry.getValue(), afterAfterEntry.getValue(), + beforeEntry.getKey(), lowerEntry.getKey(), ceilEntry.getKey(), afterAfterEntry.getKey(), amount, lerpAmount, lerpFromRight); + } else { + amount = SidedInterpolationType.interpolate(leftInterpolation, rightInterpolation, amount); + if (amount == 0.0) { + lowerKeyframe.apply(t); + } else { + lowerKeyframe.applyInterpolated(t, ceilEntry.getValue(), amount); + } + } + + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java b/src/client/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java new file mode 100644 index 0000000..1da7326 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java @@ -0,0 +1,110 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.spline.CatmullRom; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class CameraKeyframe extends Keyframe { + + private final Vec3 position; + private final Quaternionf quaternion; + + public CameraKeyframe(Entity entity) { + this(entity.position(), new Quaternionf().rotationYXZ((float) Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), 0.0f)); + } + + public CameraKeyframe(Vec3 position, Quaternionf quaternion) { + super(Minecraft.class); + this.position = position; + this.quaternion = quaternion; + } + + @Override + public void apply(Minecraft minecraft) { + LocalPlayer player = minecraft.player; + if (player != null) { + Vector3f euler = this.quaternion.getEulerAnglesYXZ(new Vector3f()); + player.moveTo(this.position.x, this.position.y, this.position.z, (float) Mth.wrapDegrees(Math.toDegrees(euler.y)), (float) Mth.wrapDegrees(Math.toDegrees(euler.x))); + player.setDeltaMovement(Vec3.ZERO); + } + } + + @Override + public void applyInterpolated(Minecraft minecraft, Keyframe genericOther, float amount) { + if (!(genericOther instanceof CameraKeyframe other)) { + this.apply(minecraft); + return; + } + + LocalPlayer player = minecraft.player; + if (player != null) { + double x = Interpolation.linear(this.position.x, other.position.x, amount); + double y = Interpolation.linear(this.position.y, other.position.y, amount); + double z = Interpolation.linear(this.position.z, other.position.z, amount); + Quaternionf quaternion = Interpolation.linear(this.quaternion, other.quaternion, amount); + Vector3f euler = quaternion.getEulerAnglesYXZ(new Vector3f()); + player.moveTo(x, y, z, (float) Mth.wrapDegrees(Math.toDegrees(euler.y)), (float) Mth.wrapDegrees(Math.toDegrees(euler.x))); + player.setDeltaMovement(Vec3.ZERO); + } + } + + @Override + public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + LocalPlayer player = minecraft.player; + if (player == null) { + return; + } + + float time1 = t1 - t0; + float time2 = t2 - t0; + float time3 = t3 - t0; + + // Calculate position + Vector3f position = CatmullRom.position(this.position.toVector3f(), + ((CameraKeyframe)p1).position.toVector3f(), ((CameraKeyframe)p2).position.toVector3f(), + ((CameraKeyframe)p3).position.toVector3f(), time1, time2, time3, amount); + + float x = position.x; + float y = position.y; + float z = position.z; + + // Calculate rotation + Quaternionf rotation = CatmullRom.rotation(this.quaternion, + ((CameraKeyframe)p1).quaternion, ((CameraKeyframe)p2).quaternion, + ((CameraKeyframe)p3).quaternion, time1, time2, time3, amount); + + if (lerpAmount >= 0) { + float linearX = (float) Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount); + float linearY = (float) Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount); + float linearZ = (float) Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount); + + Quaternionf linearQuaternion = Interpolation.linear(((CameraKeyframe)p1).quaternion, ((CameraKeyframe)p2).quaternion, lerpAmount); + + if (lerpFromRight) { + x = Interpolation.linear(x, linearX, amount); + y = Interpolation.linear(y, linearY, amount); + z = Interpolation.linear(z, linearZ, amount); + rotation = Interpolation.linear(rotation, linearQuaternion, amount); + } else { + x = Interpolation.linear(linearX, x, amount); + y = Interpolation.linear(linearY, y, amount); + z = Interpolation.linear(linearZ, z, amount); + rotation = Interpolation.linear(linearQuaternion, rotation, amount); + } + } + + Vector3f euler = rotation.getEulerAnglesYXZ(new Vector3f()); + float yaw = (float) Mth.wrapDegrees(Math.toDegrees(euler.y)); + float pitch = (float) Mth.wrapDegrees(Math.toDegrees(euler.x)); + + player.moveTo(x, y, z, yaw, pitch); + player.setDeltaMovement(Vec3.ZERO); + } +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java b/src/client/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java new file mode 100644 index 0000000..7e41d38 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java @@ -0,0 +1,65 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.spline.CatmullRom; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; + +public class FOVKeyframe extends Keyframe { + + private final int fov; + + public FOVKeyframe(int fov) { + super(Minecraft.class); + this.fov = fov; + } + + @Override + public void apply(Minecraft minecraft) { + minecraft.options.fov().set(this.fov); + } + + @Override + public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) { + if (!(otherGeneric instanceof FOVKeyframe other)) { + this.apply(minecraft); + return; + } + + float fov = Interpolation.linear(this.fov, other.fov, amount); + minecraft.options.fov().set(Math.round(fov)); + ReplayVisuals.overrideFov = fov; + } + + @Override + public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + LocalPlayer player = minecraft.player; + if (player == null) { + return; + } + + float time1 = t1 - t0; + float time2 = t2 - t0; + float time3 = t3 - t0; + + float fov = CatmullRom.value(this.fov, + ((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov, + ((FOVKeyframe)p3).fov, time1, time2, time3, amount); + + if (lerpAmount >= 0) { + float linearFov = Interpolation.linear(((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov, lerpAmount); + + if (lerpFromRight) { + fov = Interpolation.linear(fov, linearFov, amount); + } else { + fov = Interpolation.linear(linearFov, fov, amount); + } + } + + minecraft.options.fov().set(Math.round(fov)); + ReplayVisuals.overrideFov = fov; + } + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java b/src/client/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java new file mode 100644 index 0000000..3afd5e4 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java @@ -0,0 +1,56 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.spline.CatmullRom; + +public class TickrateKeyframe extends Keyframe { + + private float tickrate; + + public TickrateKeyframe(float tickrate) { + super(ReplayServer.class); + this.tickrate = tickrate; + } + + @Override + public void apply(ReplayServer replayServer) { + replayServer.desiredTickRate = this.tickrate; + } + + @Override + public void applyInterpolated(ReplayServer replayServer, Keyframe otherGeneric, float amount) { + if (!(otherGeneric instanceof TickrateKeyframe other)) { + this.apply(replayServer); + return; + } + + float tickrate = Interpolation.linear(this.tickrate, other.tickrate, amount); + replayServer.desiredTickRate = tickrate; + } + + @Override + public void applyInterpolatedSmooth(ReplayServer replayServer, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + float time1 = t1 - t0; + float time2 = t2 - t0; + float time3 = t3 - t0; + + float tickrate = CatmullRom.value(this.tickrate, + ((TickrateKeyframe)p1).tickrate, ((TickrateKeyframe)p2).tickrate, + ((TickrateKeyframe)p3).tickrate, time1, time2, time3, amount); + + if (lerpAmount >= 0) { + float linearTickrate = Interpolation.linear(((TickrateKeyframe)p1).tickrate, ((TickrateKeyframe)p2).tickrate, lerpAmount); + + if (lerpFromRight) { + tickrate = Interpolation.linear(tickrate, linearTickrate, amount); + } else { + tickrate = Interpolation.linear(linearTickrate, tickrate, amount); + } + } + + replayServer.desiredTickRate = tickrate; + } +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java b/src/client/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java new file mode 100644 index 0000000..63cfc55 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java @@ -0,0 +1,68 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.spline.CatmullRom; +import net.minecraft.client.Minecraft; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.GameRules; + +public class TimeOfDayKeyframe extends Keyframe { + + private final int time; + + public TimeOfDayKeyframe(int time) { + super(Minecraft.class); + this.time = time; + } + + private void setTime(Minecraft minecraft, int time) { + time = time % 24000; + if (time < 0) { + time += 24000; + } + + ReplayVisuals.overrideTimeOfDay = time; + } + + @Override + public void apply(Minecraft minecraft) { + this.setTime(minecraft, this.time); + } + + @Override + public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) { + if (!(otherGeneric instanceof TimeOfDayKeyframe other)) { + this.apply(minecraft); + return; + } + + int time = Math.round(Interpolation.linear(this.time, other.time, amount)); + this.setTime(minecraft, time); + } + + @Override + public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + float time1 = t1 - t0; + float time2 = t2 - t0; + float time3 = t3 - t0; + + float timeOfDay = CatmullRom.value(this.time, + ((TimeOfDayKeyframe)p1).time, ((TimeOfDayKeyframe)p2).time, + ((TimeOfDayKeyframe)p3).time, time1, time2, time3, amount); + + if (lerpAmount >= 0) { + float linearTimeOfDay = Interpolation.linear(((TimeOfDayKeyframe)p1).time, ((TimeOfDayKeyframe)p2).time, lerpAmount); + + if (lerpFromRight) { + timeOfDay = Interpolation.linear(timeOfDay, linearTimeOfDay, amount); + } else { + timeOfDay = Interpolation.linear(linearTimeOfDay, timeOfDay, amount); + } + } + + this.setTime(minecraft, Math.round(timeOfDay)); + } +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java b/src/client/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java new file mode 100644 index 0000000..f6676e6 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.keyframe.interpolation; + +import com.moulberry.flashback.keyframe.KeyframeType; + +public enum InterpolationType { + + SMOOTH(SidedInterpolationType.SMOOTH, SidedInterpolationType.SMOOTH), + LINEAR(SidedInterpolationType.LINEAR, SidedInterpolationType.LINEAR), + EASE_IN(SidedInterpolationType.EASE, SidedInterpolationType.LINEAR), + EASE_OUT(SidedInterpolationType.LINEAR, SidedInterpolationType.EASE), + EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE), + HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD); + + public static final InterpolationType[] INTERPOLATION_TYPES = values(); + + public static String[] NAMES = new String[] { + "Smooth", + "Linear", + "Ease In (Linear Out)", + "Ease Out (Linear In)", + "Ease In/Out", + "Hold" + }; + + public SidedInterpolationType leftSide; + public SidedInterpolationType rightSide; + + InterpolationType(SidedInterpolationType leftSide, SidedInterpolationType rightSide) { + this.leftSide = leftSide; + this.rightSide = rightSide; + } + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java b/src/client/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java new file mode 100644 index 0000000..b4d56ab --- /dev/null +++ b/src/client/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java @@ -0,0 +1,47 @@ +package com.moulberry.flashback.keyframe.interpolation; + +public enum SidedInterpolationType { + + SMOOTH, + LINEAR, + EASE, + HOLD; + + public static float interpolate(SidedInterpolationType left, SidedInterpolationType right, float amount) { + if (left == SidedInterpolationType.SMOOTH || right == SidedInterpolationType.SMOOTH) { + throw new IllegalArgumentException("SMOOTH not allowed"); + } + + if (left == SidedInterpolationType.HOLD) { + return 0.0f; + } + if (right == SidedInterpolationType.HOLD) { + right = left; + } + + if (left == SidedInterpolationType.LINEAR) { + if (right == SidedInterpolationType.LINEAR) { + return amount; + } else if (right == SidedInterpolationType.EASE) { + // https://easings.net/#easeOutCubic + return 1 - (float) Math.pow(1 - amount, 3); + } + } else if (left == SidedInterpolationType.EASE) { + if (right == SidedInterpolationType.LINEAR) { + // https://easings.net/#easeInCubic + return amount * amount * amount; + } else if (right == SidedInterpolationType.EASE) { + // https://easings.net/#easeInOutCubic + if (amount < 0.5) { + return 4 * amount * amount * amount; + } else { + return 1 - (float) Math.pow(-2 * amount + 2, 3) / 2; + } + } + } + + throw new IllegalArgumentException("Don't know how to interpolate " + left + " and " + right); + + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinLevelRenderer.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinLevelRenderer.java new file mode 100644 index 0000000..1ef246d --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/MixinLevelRenderer.java @@ -0,0 +1,23 @@ +package com.moulberry.flashback.mixin.client; + +import com.moulberry.flashback.ui.ReplayUI; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.LightTexture; +import org.joml.Matrix4f; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(LevelRenderer.class) +public class MixinLevelRenderer { + + @Inject(method = "renderLevel", at = @At("HEAD")) + public void renderLevel(float f, long l, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f projection, CallbackInfo ci) { + ReplayUI.lastProjectionMatrix = projection; + ReplayUI.lastViewQuaternion = camera.rotation(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinMinecraft.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinMinecraft.java new file mode 100644 index 0000000..83a1c3d --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/MixinMinecraft.java @@ -0,0 +1,317 @@ +package com.moulberry.flashback.mixin.client; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; +import com.mojang.blaze3d.systems.RenderSystem; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.keyframe.Keyframes; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.ui.ReplayUI; +import it.unimi.dsi.fastutil.floats.FloatUnaryOperator; +import net.minecraft.CrashReport; +import net.minecraft.ReportedException; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.Timer; +import net.minecraft.client.User; +import net.minecraft.client.gui.screens.LevelLoadingScreen; +import net.minecraft.client.gui.screens.Overlay; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.main.GameConfig; +import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.chat.report.ReportEnvironment; +import net.minecraft.client.particle.ParticleEngine; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.server.IntegratedServer; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.login.ServerboundHelloPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.Services; +import net.minecraft.server.WorldStem; +import net.minecraft.server.level.progress.ProcessorChunkProgressListener; +import net.minecraft.server.level.progress.StoringChunkProgressListener; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.players.GameProfileCache; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.TickRateManager; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.block.entity.SkullBlockEntity; +import net.minecraft.world.level.storage.LevelStorageSource; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.io.File; +import java.net.SocketAddress; +import java.time.Duration; +import java.time.Instant; +import java.util.Queue; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicReference; + +@Mixin(Minecraft.class) +public abstract class MixinMinecraft implements MinecraftExt { + + @Shadow + public abstract void disconnect(); + + @Shadow + @Final + private AtomicReference progressListener; + + @Shadow + @Final + private YggdrasilAuthenticationService authenticationService; + + @Shadow + @Final + public File gameDirectory; + + @Shadow + private @Nullable IntegratedServer singleplayerServer; + + @Shadow + private boolean isLocalServer; + + @Shadow + public abstract void updateReportEnvironment(ReportEnvironment reportEnvironment); + + @Shadow + public abstract void setScreen(@Nullable Screen screen); + + @Shadow + private ProfilerFiller profiler; + + @Shadow + private @Nullable Overlay overlay; + + @Shadow + protected abstract void runTick(boolean bl); + + @Shadow + protected abstract void handleDelayedCrash(); + + @Shadow + public abstract User getUser(); + + @Shadow + private @Nullable Connection pendingConnection; + + @Shadow + @Final + private Queue progressTasks; + + @Shadow + @Nullable + public ClientLevel level; + + @Shadow + @Nullable + public LocalPlayer player; + + @Shadow + @Final + public ParticleEngine particleEngine; + + @Shadow + public abstract float getFrameTime(); + + @Inject(method="", at=@At("RETURN")) + public void init(GameConfig gameConfig, CallbackInfo ci) { + ReplayUI.init(); + } + + @Inject(method = "runTick", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V", shift = At.Shift.AFTER)) + public void afterMainBlit(boolean bl, CallbackInfo ci) { + if (!RenderSystem.isOnRenderThread()) return; + ReplayUI.drawOverlay(); + } + + @Unique + private boolean inReplayLast = false; + + @Inject(method = "tick", at = @At("RETURN")) + public void tick(CallbackInfo ci) { + if (FlashbackClient.RECORDER != null) { + FlashbackClient.RECORDER.endTick(false); + } + + ReplayServer replayServer = FlashbackClient.getReplayServer(); + + boolean inReplay = replayServer != null; + if (inReplay != inReplayLast) { + inReplayLast = inReplay; + if (inReplay) { + ReplayVisuals.setupReplay(); + } else { + ReplayVisuals.disable(); + } + } + + if (inReplay && ReplayVisuals.forceEntityLerpTicks > 0) { + ReplayVisuals.forceEntityLerpTicks -= 1; + if (replayServer.replayPaused && this.level != null && !this.level.tickRateManager().runsNormally()) { + for (Entity entity : this.level.entitiesForRendering()) { + if (entity == this.player) { + continue; + } + if (entity instanceof LivingEntity livingEntity) { + if (livingEntity.lerpSteps > 0) { + livingEntity.lerpPositionAndRotationStep(livingEntity.lerpSteps, livingEntity.lerpTargetX(), + livingEntity.lerpTargetY(), livingEntity.lerpTargetZ(), livingEntity.lerpTargetYRot(), livingEntity.lerpTargetXRot()); + --livingEntity.lerpSteps; + } + if (livingEntity.lerpHeadSteps > 0) { + livingEntity.lerpHeadRotationStep(livingEntity.lerpHeadSteps, livingEntity.lerpYHeadRot); + --livingEntity.lerpHeadSteps; + } + livingEntity.setOldPosAndRot(); + livingEntity.tickHeadTurn(livingEntity.yBodyRot, 0.0f); + } else { + entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), + entity.lerpTargetYRot(), entity.lerpTargetXRot()); + } + } + } + } + } + + @Unique + private volatile boolean forceClientTick = false; + + @Override + public void flashback$forceClientTick() { + this.forceClientTick = true; + } + + @WrapOperation(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Timer;advanceTime(J)I")) + public int runTick_advanceTime(Timer instance, long l, Operation original) { + int ticks = original.call(instance, l); + if (this.forceClientTick) { + this.forceClientTick = false; + this.particleEngine.clearParticles(); + return Math.max(1, ticks); + } + return ticks; + } + + @Inject(method = "getTickTargetMillis", at = @At("HEAD"), cancellable = true) + public void getTickTargetMillis(float f, CallbackInfoReturnable cir) { + if (FlashbackClient.isInReplay()) { + if (this.level == null) { + return; + } + + TickRateManager tickRateManager = this.level.tickRateManager(); + if (tickRateManager.runsNormally()) { + cir.setReturnValue(tickRateManager.millisecondsPerTick()); + } + } + } + + @Unique + private final Timer localPlayerTimer = new Timer(20.0f, 0, FloatUnaryOperator.identity()); + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runAllTasks()V", shift = At.Shift.AFTER)) + public void runTick_runAllTasks(boolean bl, CallbackInfo ci) { + if (FlashbackClient.EXPORT_JOB != null && !ReplayUI.isActive()) { + FlashbackClient.EXPORT_JOB.run(); + FlashbackClient.EXPORT_JOB = null; + } + + if (FlashbackClient.isInReplay()) { + int localPlayerTicks = localPlayerTimer.advanceTime(Util.getMillis()); + if (this.level != null && this.player != null && !this.player.isPassenger() && !this.player.isRemoved()) { + localPlayerTicks = Math.min(10, localPlayerTicks); + for (int i = 0; i < localPlayerTicks; i++) { + this.level.tickNonPassenger(this.player); + } + } + } + } + + @Override + public float flashback$getLocalPlayerPartialTick() { + return localPlayerTimer.partialTick; + } + + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", ordinal = 1), cancellable = true) + public void runTick_setErrorSection(boolean bl, CallbackInfo ci) { + ReplayServer replayServer = FlashbackClient.getReplayServer(); + if (replayServer == null) { + return; + } + + if (!replayServer.replayPaused) { + Keyframes.applyKeyframes((Minecraft) (Object) this, replayServer.getPartialReplayTick()); + } + if (!replayServer.doClientRendering()) { + ci.cancel(); + } + } + + @Override + public void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem) { + this.disconnect(); + this.progressListener.set(null); + Instant instant = Instant.now(); + try { +// levelStorageAccess.saveDataTag((RegistryAccess)worldStem.registries().compositeAccess(), worldStem.worldData()); + Services services = Services.create((YggdrasilAuthenticationService)this.authenticationService, (File)this.gameDirectory); + services.profileCache().setExecutor((Executor)this); + SkullBlockEntity.setup(services, (Executor)this); + GameProfileCache.setUsesAuthentication(false); + this.singleplayerServer = MinecraftServer.spin(thread -> new ReplayServer((Thread)thread, (Minecraft) (Object) this, + levelStorageAccess, packRepository, stem, services, i -> { + StoringChunkProgressListener storingChunkProgressListener = StoringChunkProgressListener.createFromGameruleRadius((int)(i + 0)); + this.progressListener.set(storingChunkProgressListener); + return ProcessorChunkProgressListener.createStarted(storingChunkProgressListener, this.progressTasks::add); + })); + this.isLocalServer = true; + this.updateReportEnvironment(ReportEnvironment.local()); +// this.quickPlayLog.setWorldData(QuickPlayLog.Type.SINGLEPLAYER, levelStorageAccess.getLevelId(), worldStem.worldData().getLevelName()); + } catch (Throwable throwable) { + CrashReport crashReport = CrashReport.forThrowable((Throwable)throwable, (String)"Starting replay server"); +// CrashReportCategory crashReportCategory = crashReport.addCategory("Starting integrated server"); +// crashReportCategory.setDetail("Level ID", (Object)levelStorageAccess.getLevelId()); +// crashReportCategory.setDetail("Level Name", () -> worldStem.worldData().getLevelName()); + throw new ReportedException(crashReport); + } + while (this.progressListener.get() == null) { + Thread.yield(); + } + LevelLoadingScreen levelLoadingScreen = new LevelLoadingScreen(this.progressListener.get()); + this.setScreen(levelLoadingScreen); + this.profiler.push("waitForServer"); + while (!this.singleplayerServer.isReady() || this.overlay != null) { + levelLoadingScreen.tick(); + this.runTick(false); + try { + Thread.sleep(16L); + } catch (InterruptedException crashReport) { + // empty catch block + } + this.handleDelayedCrash(); + } + this.profiler.pop(); + Duration duration = Duration.between(instant, Instant.now()); + SocketAddress socketAddress = this.singleplayerServer.getConnection().startMemoryChannel(); + Connection connection = Connection.connectToLocalServer(socketAddress); + connection.initiateServerboundPlayConnection(socketAddress.toString(), 0, new ClientHandshakePacketListenerImpl(connection, + (Minecraft) (Object) this, null, null, false, duration, component -> {}, null)); + connection.send(new ServerboundHelloPacket(this.getUser().getName(), this.getUser().getProfileId())); + this.pendingConnection = connection; + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinMouseHandler.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinMouseHandler.java new file mode 100644 index 0000000..68d1ac3 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/MixinMouseHandler.java @@ -0,0 +1,32 @@ +package com.moulberry.flashback.mixin.client; + +import com.moulberry.flashback.ui.CustomImGuiImplGlfw; +import com.moulberry.flashback.ui.ReplayUI; +import net.minecraft.client.MouseHandler; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(MouseHandler.class) +public class MixinMouseHandler { + + @Inject(method = "isMouseGrabbed", at=@At("HEAD"), cancellable = true) + public void isMouseGrabbed(CallbackInfoReturnable cir) { + if (ReplayUI.isActive()) { + cir.setReturnValue(ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME); + } + } + + @Inject(method = "grabMouse", at=@At("HEAD"), cancellable = true) + public void grabMouse(CallbackInfo ci) { + if (ReplayUI.isActive()) ci.cancel(); + } + + @Inject(method = "releaseMouse", at=@At("HEAD"), cancellable = true) + public void releaseMouse(CallbackInfo ci) { + if (ReplayUI.isActive()) ci.cancel(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinRenderTarget.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinRenderTarget.java new file mode 100644 index 0000000..8904bb3 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/MixinRenderTarget.java @@ -0,0 +1,24 @@ +package com.moulberry.flashback.mixin.client; + +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.platform.GlStateManager; +import com.moulberry.flashback.ui.ReplayUI; +import net.minecraft.client.Minecraft; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(RenderTarget.class) +public class MixinRenderTarget { + + @Redirect(method = "_blitToScreen", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_viewport(IIII)V", remap = false)) + public void blitToScreenViewport(int left, int bottom, int width, int height) { + if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive()) { + ReplayUI.setupMainViewport(); + } else { + GlStateManager._viewport(left, bottom, width, height); + } + } + + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinThreadedLevelLightEngine.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinThreadedLevelLightEngine.java new file mode 100644 index 0000000..b576b12 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/MixinThreadedLevelLightEngine.java @@ -0,0 +1,24 @@ +package com.moulberry.flashback.mixin.client; + +import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.world.level.chunk.LightChunkGetter; +import net.minecraft.world.level.lighting.LevelLightEngine; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(ThreadedLevelLightEngine.class) +public abstract class MixinThreadedLevelLightEngine extends LevelLightEngine implements ThreadedLevelLightEngineExt { + + @Shadow + protected abstract void addTask(int i, int j, ThreadedLevelLightEngine.TaskType taskType, Runnable runnable); + + public MixinThreadedLevelLightEngine(LightChunkGetter lightChunkGetter, boolean bl, boolean bl2) { + super(lightChunkGetter, bl, bl2); + } + + @Override + public void flashback$submitPost(int x, int z, Runnable runnable) { + this.addTask(x, z, ThreadedLevelLightEngine.TaskType.POST_UPDATE, runnable); + } +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinWindow.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinWindow.java new file mode 100644 index 0000000..c87949b --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/MixinWindow.java @@ -0,0 +1,124 @@ +package com.moulberry.flashback.mixin.client; + +import com.mojang.blaze3d.platform.Window; +import com.moulberry.flashback.ui.ReplayUI; +import org.lwjgl.glfw.GLFW; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(Window.class) +public abstract class MixinWindow { + + @Shadow private int framebufferWidth; + @Shadow private int framebufferHeight; + + @Shadow private int width; + @Shadow private int height; + + @Shadow private double guiScale; + + @Shadow private int guiScaledWidth; + + @Shadow private int guiScaledHeight; + + @Shadow + private int windowedWidth; + + @Shadow + @Final + private long window; + + @Inject(method = "getWidth", at=@At("HEAD"), cancellable = true) + public void getWidth(CallbackInfoReturnable cir) { + if (ReplayUI.isActive()) { + cir.setReturnValue(ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width)); + } + } + + @Inject(method = "getHeight", at=@At("HEAD"), cancellable = true) + public void getHeight(CallbackInfoReturnable cir) { + if (ReplayUI.isActive()) { + cir.setReturnValue(ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height)); + } + } + + @Inject(method = "getScreenWidth", at=@At("HEAD"), cancellable = true) + public void getScreenWidth(CallbackInfoReturnable cir) { + if (ReplayUI.isActive()) { + cir.setReturnValue(ReplayUI.getNewGameWidth(1)); + } + } + + @Inject(method = "getScreenHeight", at=@At("HEAD"), cancellable = true) + public void getScreenHeight(CallbackInfoReturnable cir) { + if (ReplayUI.isActive()) { + cir.setReturnValue(ReplayUI.getNewGameHeight(1)); + } + } + + @Inject(method = "onFramebufferResize", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/WindowEventHandler;resizeDisplay()V", shift = At.Shift.BEFORE)) + public void onFramebufferResize(long l, int i, int j, CallbackInfo ci) { + int[] widthB = new int[1]; + int[] heightB = new int[1]; + GLFW.glfwGetWindowSize(this.window, widthB, heightB); + if (widthB[0] > 0 && heightB[0] > 0) { + this.width = widthB[0]; + this.height = heightB[0]; + } + } + + @Inject(method = "onResize", at=@At("HEAD"), cancellable = true) + public void onResize(long l, int i, int j, CallbackInfo ci) { + if (l != this.window) { + ci.cancel(); + return; + } + + int[] widthB = new int[1]; + int[] heightB = new int[1]; + GLFW.glfwGetFramebufferSize(this.window, widthB, heightB); + if (widthB[0] > 0 && heightB[0] > 0) { + this.framebufferWidth = widthB[0]; + this.framebufferHeight = heightB[0]; + } + } + + @Inject(method = "calculateScale", at=@At("HEAD"), cancellable = true) + public void calculateScale(int scale, boolean forceEven, CallbackInfoReturnable cir) { + if (ReplayUI.isActive()) { + int fbw = ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width); + int fbh = ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height); + + int j = 1; + while (j != scale && j < fbw && j < fbh && fbw / (j + 1) >= 320 && fbh / (j + 1) >= 240) { + j++; + } + if (forceEven && j % 2 != 0) { + j++; + } + cir.setReturnValue(j); + } + } + + @Inject(method = "setGuiScale", at=@At("HEAD"), cancellable = true) + public void setGuiScale(double d, CallbackInfo ci) { + if (ReplayUI.isActive()) { + int fbw = ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width); + int fbh = ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height); + + this.guiScale = d; + int i = (int)((double)fbw / d); + this.guiScaledWidth = (double)fbw / d > (double)i ? i + 1 : i; + int j = (int)((double)fbh / d); + this.guiScaledHeight = (double)fbh / d > (double)j ? j + 1 : j; + + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/packet_fix/MixinBossHealthOverlay.java b/src/client/java/com/moulberry/flashback/mixin/client/packet_fix/MixinBossHealthOverlay.java new file mode 100644 index 0000000..b69b40a --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/packet_fix/MixinBossHealthOverlay.java @@ -0,0 +1,64 @@ +package com.moulberry.flashback.mixin.client.packet_fix; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.gui.components.BossHealthOverlay; +import net.minecraft.client.gui.components.LerpingBossEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundBossEventPacket; +import net.minecraft.world.BossEvent; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Map; +import java.util.UUID; + +@Mixin(BossHealthOverlay.class) +public class MixinBossHealthOverlay { + + @Shadow + @Final + Map events; + + /** + * Prevent disconnection if boss state is incorrect + */ + @Inject(method = "update", at = @At("HEAD"), cancellable = true) + public void update(ClientboundBossEventPacket clientboundBossEventPacket, CallbackInfo ci) { + if (FlashbackClient.isInReplay()) { + clientboundBossEventPacket.dispatch(new ClientboundBossEventPacket.Handler() { + @Override + public void updateProgress(UUID uuid, float f) { + if (!events.containsKey(uuid)) { + ci.cancel(); + } + } + + @Override + public void updateName(UUID uuid, Component component) { + if (!events.containsKey(uuid)) { + ci.cancel(); + } + } + + @Override + public void updateStyle(UUID uuid, BossEvent.BossBarColor bossBarColor, BossEvent.BossBarOverlay bossBarOverlay) { + if (!events.containsKey(uuid)) { + ci.cancel(); + } + } + + @Override + public void updateProperties(UUID uuid, boolean bl, boolean bl2, boolean bl3) { + if (!events.containsKey(uuid)) { + ci.cancel(); + } + } + }); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinArmorStandRenderer.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinArmorStandRenderer.java new file mode 100644 index 0000000..3af4760 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinArmorStandRenderer.java @@ -0,0 +1,29 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.renderer.entity.ArmorStandRenderer; +import net.minecraft.world.entity.decoration.ArmorStand; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ArmorStandRenderer.class) +public class MixinArmorStandRenderer { + + /* + * Disable armor stand hit animation + * If the game time isn't updated, it'll just keep on playing it (even if it wasn't hit) + */ + + @Inject(method = "setupRotations(Lnet/minecraft/world/entity/decoration/ArmorStand;Lcom/mojang/blaze3d/vertex/PoseStack;FFFF)V", at = @At("HEAD"), cancellable = true) + public void setupRotations(ArmorStand armorStand, PoseStack poseStack, float f, float g, float h, float i, CallbackInfo ci) { + if (FlashbackClient.isInReplay()) { + poseStack.mulPose(Axis.YP.rotationDegrees(180.0F - g)); + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinClientCommonPacketListenerImpl.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinClientCommonPacketListenerImpl.java new file mode 100644 index 0000000..3c3c7d5 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinClientCommonPacketListenerImpl.java @@ -0,0 +1,52 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.net.URL; +import java.util.UUID; + +@Mixin(ClientCommonPacketListenerImpl.class) +public abstract class MixinClientCommonPacketListenerImpl { + + @Shadow + @Final + protected Minecraft minecraft; + + @Shadow + @Nullable + private static URL parseResourcePackUrl(String string) { + return null; + } + + /** + * Removes the resource pack prompt screen in replays + */ + @Inject(method = "handleResourcePackPush", at = @At("HEAD"), cancellable = true) + public void handleResourcePackPush(ClientboundResourcePackPushPacket clientboundResourcePackPushPacket, CallbackInfo ci) { + if (FlashbackClient.isInReplay()) { + PacketUtils.ensureRunningOnSameThread(clientboundResourcePackPushPacket, (ClientCommonPacketListenerImpl)(Object)this, this.minecraft); + + UUID uuid = clientboundResourcePackPushPacket.id(); + URL uRL = parseResourcePackUrl(clientboundResourcePackPushPacket.url()); + if (uRL != null) { + String string = clientboundResourcePackPushPacket.hash(); + this.minecraft.getDownloadedPackSource().allowServerPacks(); + this.minecraft.getDownloadedPackSource().pushPack(uuid, uRL, string); + } + + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinEntity.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinEntity.java new file mode 100644 index 0000000..86efda4 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinEntity.java @@ -0,0 +1,44 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.client.Minecraft; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(Entity.class) +public abstract class MixinEntity { + + @Shadow + public abstract boolean isInvisible(); + + @Shadow + private Level level; + + @Shadow + public abstract boolean isInvisibleTo(Player player); + + @Inject(method = "isInvisibleTo", at = @At("HEAD"), cancellable = true) + public void isInvisibleTo(Player player, CallbackInfoReturnable cir) { + ReplayServer replayServer = FlashbackClient.getReplayServer(); + if (replayServer != null && player == Minecraft.getInstance().player) { + int localId = replayServer.getLocalPlayerId(); + if (this.level.getEntity(localId) instanceof Player localPlayer) { + if ((Object)this == localPlayer) { + cir.setReturnValue(false); + } else { + cir.setReturnValue(this.isInvisibleTo(localPlayer)); + } + } else { + cir.setReturnValue(this.isInvisible()); + } + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinGameRenderer.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinGameRenderer.java new file mode 100644 index 0000000..e6a9e47 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinGameRenderer.java @@ -0,0 +1,94 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.blaze3d.vertex.PoseStack; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.ext.ItemInHandRendererExt; +import com.moulberry.flashback.ext.MinecraftExt; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.GameType; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(GameRenderer.class) +public class MixinGameRenderer { + + /* + * Render item in hand for spectators in a replay + */ + + @Shadow + @Final + private Minecraft minecraft; + + @WrapOperation(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;")) + public GameType getPlayerMode(MultiPlayerGameMode instance, Operation original) { + if (FlashbackClient.getSpectatingPlayer() != null) { + return GameType.SURVIVAL; + } + return original.call(instance); + } + + @WrapOperation(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderHandsWithItems(FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/player/LocalPlayer;I)V")) + public void renderItemInHand_renderHandsWithItems(ItemInHandRenderer instance, float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, LocalPlayer localPlayer, int i, Operation original) { + AbstractClientPlayer spectatingPlayer = FlashbackClient.getSpectatingPlayer(); + if (spectatingPlayer != null) { + ((ItemInHandRendererExt)instance).flashback$renderHandsWithItems(f, poseStack, bufferSource, spectatingPlayer, i); + } else { + original.call(instance, f, poseStack, bufferSource, localPlayer, i); + } + } + + @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setup(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/world/entity/Entity;ZZF)V")) + public void renderLevel_setupCamera(Camera instance, BlockGetter blockGetter, Entity entity, boolean bl, boolean bl2, float f, Operation original) { + if (FlashbackClient.isInReplay()) { + f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(); + } + original.call(instance, blockGetter, entity, bl, bl2, f); + } + + @Inject(method = "tryTakeScreenshotIfNeeded", at = @At("HEAD"), cancellable = true) + public void tryTakeScreenshotIfNeeded(CallbackInfo ci) { + if (FlashbackClient.isInReplay()) { + ci.cancel(); + } + } + + @Inject(method = "getFov", at = @At("HEAD"), cancellable = true) + public void getFov(Camera camera, float f, boolean bl, CallbackInfoReturnable cir) { + if (FlashbackClient.isInReplay()) { + if (!bl) { + cir.setReturnValue(70.0); + return; + } + + int fov = this.minecraft.options.fov().get().intValue(); + if (ReplayVisuals.overrideFov > 0.0) { + if (Math.abs(ReplayVisuals.overrideFov - fov) < 1) { + cir.setReturnValue((double) ReplayVisuals.overrideFov); + return; + } else { + ReplayVisuals.overrideFov = 0.0f; + } + } + cir.setReturnValue((double) fov); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinItemInHandRenderer.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinItemInHandRenderer.java new file mode 100644 index 0000000..856e9a6 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinItemInHandRenderer.java @@ -0,0 +1,126 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.google.common.base.MoreObjects; +import com.mojang.blaze3d.vertex.PoseStack; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.ext.ItemInHandRendererExt; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.UUID; + +@Mixin(ItemInHandRenderer.class) +public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt { + + @Shadow + private float oMainHandHeight; + + @Shadow + private float mainHandHeight; + + @Shadow + private float oOffHandHeight; + + @Shadow + private float offHandHeight; + + @Shadow + protected abstract void renderArmWithItem(AbstractClientPlayer abstractClientPlayer, float f, float g, InteractionHand interactionHand, float h, ItemStack itemStack, float i, PoseStack poseStack, MultiBufferSource multiBufferSource, int j); + + @Shadow + private ItemStack mainHandItem; + + @Shadow + private ItemStack offHandItem; + + @Override + public void flashback$renderHandsWithItems(float partialTick, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, AbstractClientPlayer clientPlayer, int i) { + float m; + float l; + float g = clientPlayer.getAttackAnim(partialTick); + InteractionHand interactionHand = MoreObjects.firstNonNull(clientPlayer.swingingArm, InteractionHand.MAIN_HAND); + float h = Mth.lerp(partialTick, clientPlayer.xRotO, clientPlayer.getXRot()); + // todo: hand selection + // ItemInHandRenderer.HandRenderSelection handRenderSelection = evaluateWhichHandsToRender(clientPlayer); + // todo: bob +// float j = Mth.lerp((float)f, (float)clientPlayer.xBobO, (float)clientPlayer.xBob); +// float k = Mth.lerp((float)f, (float)clientPlayer.yBobO, (float)clientPlayer.yBob); +// poseStack.mulPose(Axis.XP.rotationDegrees((clientPlayer.getViewXRot(f) - j) * 0.1f)); +// poseStack.mulPose(Axis.YP.rotationDegrees((clientPlayer.getViewYRot(f) - k) * 0.1f)); + if (true) { + l = interactionHand == InteractionHand.MAIN_HAND ? g : 0.0f; + m = 1.0f - Mth.lerp(partialTick, this.oMainHandHeight, this.mainHandHeight); + renderArmWithItem(clientPlayer, partialTick, h, InteractionHand.MAIN_HAND, l, this.mainHandItem, m, poseStack, bufferSource, i); + } + if (true) { + l = interactionHand == InteractionHand.OFF_HAND ? g : 0.0f; + m = 1.0f - Mth.lerp(partialTick, this.oOffHandHeight, this.offHandHeight); + renderArmWithItem(clientPlayer, partialTick, h, InteractionHand.OFF_HAND, l, this.offHandItem, m, poseStack, bufferSource, i); + } + bufferSource.endBatch(); + } + + // todo: change first person FOV when pulling bows, etc. + + // todo: show arm (need to replace usage of LocalPlayer in renderPlayerArm + + @Unique + private UUID lastSpectatingPlayer = null; + + @Inject(method = "tick", at = @At("HEAD"), cancellable = true) + public void tick(CallbackInfo ci) { + AbstractClientPlayer spectatingPlayer = FlashbackClient.getSpectatingPlayer(); + if (spectatingPlayer == null) { + this.lastSpectatingPlayer = null; + } else { + ItemStack newMainHandItem = spectatingPlayer.getMainHandItem(); + ItemStack newOffHandItem = spectatingPlayer.getOffhandItem(); + + if (!spectatingPlayer.getUUID().equals(lastSpectatingPlayer)) { + this.lastSpectatingPlayer = spectatingPlayer.getUUID(); + this.mainHandItem = newMainHandItem; + this.offHandItem = newOffHandItem; + this.oMainHandHeight = this.mainHandHeight = 1.0f; + this.oOffHandHeight = this.offHandHeight = 1.0f; + ci.cancel(); + return; + } + + this.oMainHandHeight = this.mainHandHeight; + this.oOffHandHeight = this.offHandHeight; + if (ItemStack.matches(this.mainHandItem, newMainHandItem)) { + this.mainHandItem = newMainHandItem; + } + if (ItemStack.matches(this.offHandItem, newOffHandItem)) { + this.offHandItem = newOffHandItem; + } + if (false /*clientPlayer.isHandsBusy()*/) { + this.mainHandHeight = Mth.clamp((float)(this.mainHandHeight - 0.4f), (float)0.0f, (float)1.0f); + this.offHandHeight = Mth.clamp((float)(this.offHandHeight - 0.4f), (float)0.0f, (float)1.0f); + } else { + // todo: attack strength + float f = 1.0f;//spectatingPlayer.getAttackStrengthScale(1.0f); + this.mainHandHeight += Mth.clamp((this.mainHandItem == newMainHandItem ? f * f * f : 0.0f) - this.mainHandHeight, -0.4f, 0.4f); + this.offHandHeight += Mth.clamp((float)(this.offHandItem == newOffHandItem ? 1 : 0) - this.offHandHeight, -0.4f, 0.4f); + } + if (this.mainHandHeight < 0.1f) { + this.mainHandItem = newMainHandItem; + } + if (this.offHandHeight < 0.1f) { + this.offHandItem = newOffHandItem; + } + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLevelChunkSection.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLevelChunkSection.java new file mode 100644 index 0000000..6900903 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLevelChunkSection.java @@ -0,0 +1,70 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.moulberry.flashback.ChunkSectionHash; +import com.moulberry.flashback.ext.LevelChunkSectionExt; +import com.moulberry.flashback.ext.PaletteExt; +import net.minecraft.core.Holder; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.GlobalPalette; +import net.minecraft.world.level.chunk.HashMapPalette; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.LinearPalette; +import net.minecraft.world.level.chunk.PalettedContainer; +import net.minecraft.world.level.chunk.PalettedContainerRO; +import net.minecraft.world.level.chunk.SingleValuePalette; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(LevelChunkSection.class) +public class MixinLevelChunkSection implements LevelChunkSectionExt { + + @Shadow + @Final + private PalettedContainer states; + + @Shadow + private short nonEmptyBlockCount; + + @Shadow + private PalettedContainerRO> biomes; + + @Override + public ChunkSectionHash flashback$hashState() { + long blockHash = hashPalettedContainerData(this.states.data); + long biomeHash = hashPalettedContainerData(((PalettedContainer) this.biomes).data); + return new ChunkSectionHash(this.nonEmptyBlockCount, blockHash, biomeHash); + } + + @Unique + private static long hashPalettedContainerData(PalettedContainer.Data data) { + long hash; + if (data.palette() instanceof PaletteExt paletteExt) { + hash = paletteExt.flashback$hash(); + } else { + throw new RuntimeException("Unknown palette type: " + data.palette().getClass()); + } + for (long l : data.storage().getRaw()) { + hash = l + hash*17; + } + return hash; + } + + @Override + public boolean flashback$doesHashedStateMatch(ChunkSectionHash hashedState) { + if (hashedState.nonEmptyBlockCount() != this.nonEmptyBlockCount) { + return false; + } + + long biomeHash = hashPalettedContainerData(((PalettedContainer) this.biomes).data); + if (hashedState.biomeHash() != biomeHash) { + return false; + } + + long blockHash = hashPalettedContainerData(this.states.data); + return hashedState.blockHash() == blockHash; + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLivingEntity.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLivingEntity.java new file mode 100644 index 0000000..94d6ed2 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLivingEntity.java @@ -0,0 +1,47 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +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.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(LivingEntity.class) +public abstract class MixinLivingEntity extends Entity { + + @Shadow + public abstract void lerpTo(double d, double e, double f, float g, float h, int i); + + @Shadow + public abstract void lerpHeadTo(float f, int i); + + public MixinLivingEntity(EntityType entityType, Level level) { + super(entityType, level); + } + + @Inject(method = "lerpTo", at = @At("HEAD"), cancellable = true) + public void lerpTo(double d, double e, double f, float g, float h, int i, CallbackInfo ci) { + if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) { + this.lerpTo(d, e, f, g, h, 1); + ci.cancel(); + } + } + + @Inject(method = "lerpHeadTo", at = @At("HEAD"), cancellable = true) + public void lerpHeadTo(float f, int i, CallbackInfo ci) { + if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) { + this.lerpHeadTo(f, 1); + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinPlayerChunkSender.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinPlayerChunkSender.java new file mode 100644 index 0000000..fef32bd --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinPlayerChunkSender.java @@ -0,0 +1,35 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.PlayerChunkSender; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PlayerChunkSender.class) +public class MixinPlayerChunkSender { + + // Make chunks send faster on replay servers + + @Shadow + private float desiredChunksPerTick; + + @Shadow + private int unacknowledgedBatches; + + @Shadow + private float batchQuota; + + @Inject(method = "sendNextChunks", at = @At("HEAD")) + public void sendNextChunks(ServerPlayer serverPlayer, CallbackInfo ci) { + if (FlashbackClient.isInReplay()) { + this.unacknowledgedBatches = 0; + this.batchQuota = 0.0f; + this.desiredChunksPerTick = Math.max(this.desiredChunksPerTick, 256.0f); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinTickRateManager.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinTickRateManager.java new file mode 100644 index 0000000..b2b8d32 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinTickRateManager.java @@ -0,0 +1,31 @@ +package com.moulberry.flashback.mixin.client.playback; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.Minecraft; +import net.minecraft.server.ServerTickRateManager; +import net.minecraft.world.TickRateManager; +import net.minecraft.world.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(TickRateManager.class) +public abstract class MixinTickRateManager { + + @Shadow + public abstract boolean runsNormally(); + + @Unique + private final boolean isClientTickRateManager = !((Object)this instanceof ServerTickRateManager); + + @Inject(method = "isEntityFrozen", at = @At("HEAD"), cancellable = true) + public void isEntityFrozen(Entity entity, CallbackInfoReturnable cir) { + if (this.isClientTickRateManager && FlashbackClient.isInReplay()) { + cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinGlobalPalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinGlobalPalette.java new file mode 100644 index 0000000..526cc91 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinGlobalPalette.java @@ -0,0 +1,13 @@ +package com.moulberry.flashback.mixin.client.playback.hashing; + +import com.moulberry.flashback.ext.PaletteExt; +import net.minecraft.world.level.chunk.GlobalPalette; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(GlobalPalette.class) +public class MixinGlobalPalette implements PaletteExt { + @Override + public long flashback$hash() { + return 0xCF184DF659428CABL; + } +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinHashMapPalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinHashMapPalette.java new file mode 100644 index 0000000..e4a9c84 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinHashMapPalette.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.mixin.client.playback.hashing; + +import com.moulberry.flashback.ext.PaletteExt; +import net.minecraft.core.IdMap; +import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap; +import net.minecraft.world.level.chunk.HashMapPalette; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(HashMapPalette.class) +public abstract class MixinHashMapPalette implements PaletteExt { + @Shadow + @Final + private IdMap registry; + + @Shadow + @Final + private CrudeIncrementalIntIdentityHashBiMap values; + + @Shadow + public abstract int getSize(); + + @Override + public long flashback$hash() { + long hash = 0; + int size = this.getSize(); + for(int j = 0; j < size; ++j) { + hash = this.registry.getId(this.values.byId(j)) + hash*17; + } + return hash; + } +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinLinearPalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinLinearPalette.java new file mode 100644 index 0000000..fb4680b --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinLinearPalette.java @@ -0,0 +1,32 @@ +package com.moulberry.flashback.mixin.client.playback.hashing; + +import com.moulberry.flashback.ext.PaletteExt; +import net.minecraft.core.IdMap; +import net.minecraft.world.level.chunk.LinearPalette; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(LinearPalette.class) +public class MixinLinearPalette implements PaletteExt { + @Shadow + private int size; + + @Shadow + @Final + private IdMap registry; + + @Shadow + @Final + public T[] values; + + @Override + public long flashback$hash() { + long hash = 0; + int size = this.size; + for(int i = 0; i < size; ++i) { + hash = this.registry.getId(this.values[i]) + hash*17; + } + return hash; + } +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinSingleValuePalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinSingleValuePalette.java new file mode 100644 index 0000000..2e4ebce --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinSingleValuePalette.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.mixin.client.playback.hashing; + +import com.moulberry.flashback.ext.PaletteExt; +import net.minecraft.core.IdMap; +import net.minecraft.world.level.chunk.SingleValuePalette; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(SingleValuePalette.class) +public class MixinSingleValuePalette implements PaletteExt { + @Shadow + @Final + public IdMap registry; + + @Shadow + @Nullable + public T value; + + @Override + public long flashback$hash() { + return this.registry.getId(this.value); + } +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/record/MixinClientConfigurationPacketListenerImpl.java b/src/client/java/com/moulberry/flashback/mixin/client/record/MixinClientConfigurationPacketListenerImpl.java new file mode 100644 index 0000000..0d0a689 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/record/MixinClientConfigurationPacketListenerImpl.java @@ -0,0 +1,30 @@ +package com.moulberry.flashback.mixin.client.record; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; +import net.minecraft.client.multiplayer.ClientConfigurationPacketListenerImpl; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.CommonListenerCookie; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ClientConfigurationPacketListenerImpl.class) +public abstract class MixinClientConfigurationPacketListenerImpl extends ClientCommonPacketListenerImpl { + + protected MixinClientConfigurationPacketListenerImpl(Minecraft minecraft, Connection connection, CommonListenerCookie commonListenerCookie) { + super(minecraft, connection, commonListenerCookie); + } + + @Inject(method = "handleConfigurationFinished", at = @At("RETURN")) + public void handleConfigurationFinished(ClientboundFinishConfigurationPacket clientboundFinishConfigurationPacket, CallbackInfo ci) { + if (FlashbackClient.RECORDER != null) { + FlashbackClient.RECORDER.setRegistryAccess(((ClientPacketListener)this.connection.getPacketListener()).registryAccess()); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/record/MixinConnection.java b/src/client/java/com/moulberry/flashback/mixin/client/record/MixinConnection.java new file mode 100644 index 0000000..3dc94d9 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/record/MixinConnection.java @@ -0,0 +1,29 @@ +package com.moulberry.flashback.mixin.client.record; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.network.Connection; +import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.PacketListener; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Connection.class) +public class MixinConnection { + + @Inject(method = "genericsFtw", at = @At("HEAD")) + private static void genericsFtw(Packet packet, PacketListener packetListener, CallbackInfo ci) { + if (FlashbackClient.RECORDER != null) { + if (packetListener instanceof ClientGamePacketListener) { + FlashbackClient.RECORDER.writePacketAsync(packet, ConnectionProtocol.PLAY); + } else if (packetListener instanceof ClientConfigurationPacketListener) { + FlashbackClient.RECORDER.writePacketAsync(packet, ConnectionProtocol.CONFIGURATION); + } + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkGenerators.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkGenerators.java new file mode 100644 index 0000000..f265ae9 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkGenerators.java @@ -0,0 +1,21 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.mojang.serialization.MapCodec; +import com.moulberry.flashback.playback.EmptyLevelSource; +import net.minecraft.core.Registry; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkGenerators; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ChunkGenerators.class) +public class MixinChunkGenerators { + + @Inject(method = "bootstrap", at = @At("HEAD")) + private static void bootstrap(Registry> registry, CallbackInfoReturnable> cir) { + Registry.register(registry, "flashback/empty", EmptyLevelSource.CODEC); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkStatusTasks.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkStatusTasks.java new file mode 100644 index 0000000..7665aff --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkStatusTasks.java @@ -0,0 +1,31 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.status.ChunkStatusTasks; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.concurrent.CompletableFuture; + +@Mixin(ChunkStatusTasks.class) +public class MixinChunkStatusTasks { + + @Inject(method = "initializeLight", at = @At("HEAD"), cancellable = true) + private static void initializeLight(ThreadedLevelLightEngine threadedLevelLightEngine, ChunkAccess chunkAccess, CallbackInfoReturnable> cir) { + if (FlashbackClient.isInReplay()) { + cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess)); + } + } + + @Inject(method = "lightChunk", at = @At("HEAD"), cancellable = true) + private static void lightChunk(ThreadedLevelLightEngine threadedLevelLightEngine, ChunkAccess chunkAccess, CallbackInfoReturnable> cir) { + if (FlashbackClient.isInReplay()) { + cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess)); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPersistentEntitySectionManager.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPersistentEntitySectionManager.java new file mode 100644 index 0000000..a5df6bd --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPersistentEntitySectionManager.java @@ -0,0 +1,20 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.world.level.entity.PersistentEntitySectionManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PersistentEntitySectionManager.class) +public class MixinPersistentEntitySectionManager { + + @Inject(method = "saveAll", at = @At("HEAD"), cancellable = true) + public void saveAll(CallbackInfo ci) { + if (FlashbackClient.isInReplay()) { + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPlayerList.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPlayerList.java new file mode 100644 index 0000000..ce9c46f --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPlayerList.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.PlayerList; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +import java.util.Optional; +import java.util.function.Function; + +@Mixin(PlayerList.class) +public class MixinPlayerList { + + /* + * Don't change the dimension of replay viewers when spawning them + */ + + @WrapOperation(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Ljava/util/Optional;flatMap(Ljava/util/function/Function;)Ljava/util/Optional;")) + public Optional> placeNewPlayer_flatMap(Optional instance, Function function, Operation>> original, + @Local(argsOnly = true) ServerPlayer serverPlayer) { + if (serverPlayer.server instanceof ReplayServer) { + return Optional.of(serverPlayer.level().dimension()); + } + return original.call(instance, function); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerChunkCache.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerChunkCache.java new file mode 100644 index 0000000..8baf355 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerChunkCache.java @@ -0,0 +1,27 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ServerChunkCache.class) +public class MixinServerChunkCache { + + @Shadow + @Final + ServerLevel level; + + @Inject(method = "save", at = @At("HEAD"), cancellable = true) + public void save(boolean bl, CallbackInfo ci) { + if (this.level.getServer() instanceof ReplayServer) { + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerConfigurationPacketListenerImpl.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerConfigurationPacketListenerImpl.java new file mode 100644 index 0000000..b739ebf --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerConfigurationPacketListenerImpl.java @@ -0,0 +1,57 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.moulberry.flashback.ext.ServerConfigurationPacketListenerImplExt; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.CommonListenerCookie; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerConfigurationPacketListenerImpl; +import net.minecraft.server.network.config.SynchronizeRegistriesTask; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.List; +import java.util.Queue; + +@Mixin(ServerConfigurationPacketListenerImpl.class) +public abstract class MixinServerConfigurationPacketListenerImpl extends ServerCommonPacketListenerImpl implements ServerConfigurationPacketListenerImplExt { + + @Shadow + @Final + private Queue configurationTasks; + + @Shadow + protected abstract void startNextTask(); + + @Shadow + private @Nullable SynchronizeRegistriesTask synchronizeRegistriesTask; + + public MixinServerConfigurationPacketListenerImpl(MinecraftServer minecraftServer, Connection connection, CommonListenerCookie commonListenerCookie) { + super(minecraftServer, connection, commonListenerCookie); + } + + @Override + public void flashback$startConfiguration(List> initialPackets, List tasks) { + for (Packet initialPacket : initialPackets) { + this.send(initialPacket); + } + + for (ConfigurationTask task : tasks) { + if (task instanceof SynchronizeRegistriesTask synchronizeRegistriesTask) { + if (this.synchronizeRegistriesTask != null) { + throw new IllegalStateException("Duplicate SynchronizeRegistriesTask"); + } + this.synchronizeRegistriesTask = synchronizeRegistriesTask; + } + } + + this.configurationTasks.addAll(tasks); + this.startNextTask(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerEntity.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerEntity.java new file mode 100644 index 0000000..a5c11aa --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerEntity.java @@ -0,0 +1,26 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.llamalad7.mixinextras.sugar.Local; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.server.level.ServerLevel; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +@Mixin(ServerEntity.class) +public class MixinServerEntity { + + /* + * Force update interval to be 1 on a replay server + */ + + @ModifyVariable(method = "", at = @At("HEAD"), argsOnly = true) + private static int init_modifyUpdateInterval(int updateInterval, @Local(argsOnly = true) ServerLevel level) { + if (level.getServer() instanceof ReplayServer) { + return 1; + } + return updateInterval; + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerGamePacketListenerImpl.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerGamePacketListenerImpl.java new file mode 100644 index 0000000..ba63f4b --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerGamePacketListenerImpl.java @@ -0,0 +1,78 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.ext.ServerConfigurationPacketListenerImplExt; +import com.moulberry.flashback.ext.ServerGamePacketListenerImplExt; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.game.ServerboundConfigurationAcknowledgedPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerConfigurationPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +@Mixin(ServerGamePacketListenerImpl.class) +public abstract class MixinServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl implements ServerGamePacketListenerImplExt { + + @Shadow + public ServerPlayer player; + + @Shadow + public abstract void switchToConfig(); + + public MixinServerGamePacketListenerImpl(MinecraftServer minecraftServer, Connection connection, CommonListenerCookie commonListenerCookie) { + super(minecraftServer, connection, commonListenerCookie); + } + + @Unique + private List> pendingConfigurationPackets = null; + @Unique + private List pendingTasks = null; + + @Override + public void flashback$switchToConfigWithTasks(List> initialPackets, List tasks) { + this.switchToConfig(); + this.pendingConfigurationPackets = initialPackets; + this.pendingTasks = tasks; + } + + @Inject(method = "switchToConfig", at = @At("HEAD")) + public void switchToConfig(CallbackInfo ci) { + this.pendingConfigurationPackets = null; + this.pendingTasks = null; + } + + @Inject(method = "handleConfigurationAcknowledged", at = @At("HEAD"), cancellable = true) + public void handleConfigurationAcknowledged(ServerboundConfigurationAcknowledgedPacket serverboundConfigurationAcknowledgedPacket, CallbackInfo ci) { + if (this.pendingTasks != null) { + var configurationHandler = new ServerConfigurationPacketListenerImpl(this.server, this.connection, + this.createCookie(this.player.clientInformation())); + ((ServerConfigurationPacketListenerImplExt)configurationHandler).flashback$startConfiguration(this.pendingConfigurationPackets, this.pendingTasks); + this.pendingTasks = null; + this.connection.setupInboundProtocol(ConfigurationProtocols.SERVERBOUND, configurationHandler); + ci.cancel(); + } + } + + // Remove player disconnect logging in replays + @WrapWithCondition(method = "onDisconnect", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;info(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V")) + public boolean onDisconnect_info(Logger instance, String s, Object o1, Object o2) { + return !FlashbackClient.isInReplay(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerLoginPacketListenerImpl.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerLoginPacketListenerImpl.java new file mode 100644 index 0000000..079e94c --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerLoginPacketListenerImpl.java @@ -0,0 +1,41 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.mojang.authlib.GameProfile; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.protocol.login.ServerboundHelloPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerLoginPacketListenerImpl; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.UUID; + +@Mixin(ServerLoginPacketListenerImpl.class) +public abstract class MixinServerLoginPacketListenerImpl { + + @Shadow + @Final + MinecraftServer server; + + @Shadow + abstract void startClientVerification(GameProfile gameProfile); + + @Shadow + @Nullable + String requestedUsername; + + @Inject(method = "handleHello", at = @At("HEAD"), cancellable = true) + public void handleHello(ServerboundHelloPacket serverboundHelloPacket, CallbackInfo ci) { + if (this.server instanceof ReplayServer) { + this.requestedUsername = "ReplayViewer"; + this.startClientVerification(new GameProfile(UUID.randomUUID(), "ReplayViewer")); + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinTickRateManager.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinTickRateManager.java new file mode 100644 index 0000000..6292456 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinTickRateManager.java @@ -0,0 +1,32 @@ +package com.moulberry.flashback.mixin.client.replay_server; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.Minecraft; +import net.minecraft.server.ServerTickRateManager; +import net.minecraft.world.TickRateManager; +import net.minecraft.world.entity.Entity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(TickRateManager.class) +public abstract class MixinTickRateManager { + + @Shadow + protected boolean runGameElements; + + /* + * Freeze the replay server, preventing game elements from running normally + */ + + @Inject(method = "tick", at = @At("RETURN")) + public void tick(CallbackInfo ci) { + if (FlashbackClient.isInReplay() && (Object)this instanceof ServerTickRateManager) { + this.runGameElements = false; + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/ui/MixinTitleScreen.java b/src/client/java/com/moulberry/flashback/mixin/client/ui/MixinTitleScreen.java new file mode 100644 index 0000000..262ddcb --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/ui/MixinTitleScreen.java @@ -0,0 +1,27 @@ +package com.moulberry.flashback.mixin.client.ui; + +import com.moulberry.flashback.FlashbackClient; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.network.chat.Component; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(TitleScreen.class) +public class MixinTitleScreen extends Screen { + + private MixinTitleScreen() { + super(null); + } + + @Inject(method = "createNormalMenuOptions", at = @At("RETURN")) + public void createNormalMenuOptions(int i, int j, CallbackInfo ci) { + this.addRenderableWidget(Button.builder(Component.literal("Replay"), button -> { + FlashbackClient.testReplayWorld(); + }).bounds(this.width / 2 - 100, i + j * 3, 200, 20).build()); + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevel.java b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevel.java new file mode 100644 index 0000000..3989d46 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevel.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.mixin.client.visuals; + +public class MixinClientLevel { + + + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevelData.java b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevelData.java new file mode 100644 index 0000000..580ef88 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevelData.java @@ -0,0 +1,20 @@ +package com.moulberry.flashback.mixin.client.visuals; + +import com.moulberry.flashback.ReplayVisuals; +import net.minecraft.client.multiplayer.ClientLevel; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ClientLevel.ClientLevelData.class) +public class MixinClientLevelData { + + @Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true) + public void getDayTime(CallbackInfoReturnable cir) { + if (ReplayVisuals.overrideTimeOfDay >= 0) { + cir.setReturnValue(ReplayVisuals.overrideTimeOfDay); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinFogRenderer.java b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinFogRenderer.java new file mode 100644 index 0000000..6c0f776 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinFogRenderer.java @@ -0,0 +1,26 @@ +package com.moulberry.flashback.mixin.client.visuals; + +import com.mojang.blaze3d.shaders.FogShape; +import com.mojang.blaze3d.systems.RenderSystem; +import com.moulberry.flashback.ReplayVisuals; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.FogRenderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(FogRenderer.class) +public class MixinFogRenderer { + + @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) + private static void setupFog(Camera camera, FogRenderer.FogMode fogMode, float f, boolean bl, float g, CallbackInfo ci) { + if (ReplayVisuals.overrideFogDistance > 0.0f) { + RenderSystem.setShaderFogStart(0.0f); + RenderSystem.setShaderFogEnd(ReplayVisuals.overrideFogDistance); + RenderSystem.setShaderFogShape(FogShape.SPHERE); + ci.cancel(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java b/src/client/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java new file mode 100644 index 0000000..a46a4b2 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java @@ -0,0 +1,32 @@ +package com.moulberry.flashback.playback; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket; + +import java.util.Set; + +public class AllowPendingEntityPacketSet { + + public static boolean allowPendingEntity(Packet packet) { + return ALLOW_PENDING_ENTITY.contains(packet.getClass()); + } + + private static final Set>> ALLOW_PENDING_ENTITY = Set.of( + ClientboundAddEntityPacket.class, + ClientboundSetEntityDataPacket.class, + ClientboundUpdateAttributesPacket.class, + ClientboundSetEntityMotionPacket.class, + ClientboundSetEquipmentPacket.class, + ClientboundUpdateMobEffectPacket.class, + ClientboundRotateHeadPacket.class, + ClientboundTeleportEntityPacket.class + ); + +} diff --git a/src/client/java/com/moulberry/flashback/playback/EmptyLevelSource.java b/src/client/java/com/moulberry/flashback/playback/EmptyLevelSource.java new file mode 100644 index 0000000..9dcaaba --- /dev/null +++ b/src/client/java/com/moulberry/flashback/playback/EmptyLevelSource.java @@ -0,0 +1,88 @@ +package com.moulberry.flashback.playback; + +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.resources.RegistryOps; +import net.minecraft.server.level.WorldGenRegion; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.biome.FixedBiomeSource; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.GenerationStep; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.RandomState; +import net.minecraft.world.level.levelgen.blending.Blender; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +public class EmptyLevelSource extends ChunkGenerator { + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group(RegistryOps.retrieveElement(Biomes.PLAINS)).apply(instance, instance.stable(EmptyLevelSource::new))); + + public EmptyLevelSource(Holder.Reference reference) { + super(new FixedBiomeSource(reference)); + } + + @Override + protected MapCodec codec() { + return CODEC; + } + + @Override + public void buildSurface(WorldGenRegion worldGenRegion, StructureManager structureManager, RandomState randomState, ChunkAccess chunkAccess) { + } + + @Override + public void applyBiomeDecoration(WorldGenLevel worldGenLevel, ChunkAccess chunkAccess, StructureManager structureManager) { + } + + @Override + public CompletableFuture fillFromNoise(Executor executor, Blender blender, RandomState randomState, StructureManager structureManager, ChunkAccess chunkAccess) { + return CompletableFuture.completedFuture(chunkAccess); + } + + @Override + public int getBaseHeight(int i, int j, Heightmap.Types types, LevelHeightAccessor levelHeightAccessor, RandomState randomState) { + return 0; + } + + @Override + public NoiseColumn getBaseColumn(int i, int j, LevelHeightAccessor levelHeightAccessor, RandomState randomState) { + return new NoiseColumn(0, new BlockState[0]); + } + + @Override + public void addDebugScreenInfo(List list, RandomState randomState, BlockPos blockPos) { + } + + @Override + public void applyCarvers(WorldGenRegion worldGenRegion, long l, RandomState randomState, BiomeManager biomeManager, StructureManager structureManager, ChunkAccess chunkAccess, GenerationStep.Carving carving) { + } + + @Override + public void spawnOriginalMobs(WorldGenRegion worldGenRegion) { + } + + @Override + public int getMinY() { + return 0; + } + + @Override + public int getGenDepth() { + return 384; + } + + @Override + public int getSeaLevel() { + return 63; + } +} diff --git a/src/client/java/com/moulberry/flashback/playback/PlayableChunk.java b/src/client/java/com/moulberry/flashback/playback/PlayableChunk.java new file mode 100644 index 0000000..ec0f4b9 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/playback/PlayableChunk.java @@ -0,0 +1,39 @@ +package com.moulberry.flashback.playback; + +import com.moulberry.flashback.io.ReplayReader; +import com.moulberry.flashback.record.FlashbackChunkMeta; +import io.netty.buffer.Unpooled; +import net.minecraft.core.RegistryAccess; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class PlayableChunk { + + public final FlashbackChunkMeta chunkMeta; + public final Path path; + private ReplayReader replayReader; + + public PlayableChunk(FlashbackChunkMeta chunkMeta, Path path) { + this.chunkMeta = chunkMeta; + this.path = path; + } + + public ReplayReader getOrLoadReplayReader(RegistryAccess registryAccess) { + if (this.replayReader == null) { + try { + byte[] bytes = Files.readAllBytes(this.path); + this.replayReader = new ReplayReader(Unpooled.wrappedBuffer(bytes), registryAccess); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + this.replayReader.changeRegistryAccess(registryAccess); + return this.replayReader; + } + + + +} diff --git a/src/client/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java b/src/client/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java new file mode 100644 index 0000000..e962f4e --- /dev/null +++ b/src/client/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java @@ -0,0 +1,329 @@ +package com.moulberry.flashback.playback; + +import com.google.common.collect.ImmutableMap; +import com.moulberry.flashback.exception.UnsupportedPacketException; +import com.moulberry.flashback.registry.RegistryHelper; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.RegistrySynchronization; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.common.ClientboundStoreCookiePacket; +import net.minecraft.network.protocol.common.ClientboundTransferPacket; +import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; +import net.minecraft.network.protocol.configuration.ClientboundRegistryDataPacket; +import net.minecraft.network.protocol.configuration.ClientboundResetChatPacket; +import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks; +import net.minecraft.network.protocol.configuration.ClientboundUpdateEnabledFeaturesPacket; +import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.server.network.config.JoinWorldTask; +import net.minecraft.server.network.config.SynchronizeRegistriesTask; +import net.minecraft.server.packs.PackLocationInfo; +import net.minecraft.server.packs.repository.KnownPack; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.resources.ResourceProvider; +import net.minecraft.tags.TagNetworkSerialization; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.storage.DerivedLevelData; +import net.minecraft.world.level.storage.PrimaryLevelData; +import net.minecraft.world.level.storage.ServerLevelData; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +public class ReplayConfigurationPacketHandler implements ClientConfigurationPacketListener { + + private final ReplayServer replayServer; + private Map>, List> pendingRegistryMap = null; + private Map>, TagNetworkSerialization.NetworkPayload> pendingTags = null; + private FeatureFlagSet pendingFeatureFlags = null; + private List pendingKnownPacks = null; + private boolean pendingResetChat = false; + private boolean dirty = false; + + public ReplayConfigurationPacketHandler(ReplayServer replayServer) { + this.replayServer = replayServer; + } + + public void flushPendingConfiguration() { + if (!this.dirty) { + return; + } + this.dirty = false; + + boolean sendTags = false; + + if (this.pendingTags != null && !this.pendingTags.isEmpty()) { + this.pendingTags.forEach((resourceKey, networkPayload) -> { + networkPayload.applyToRegistry(this.replayServer.registryAccess().registryOrThrow(resourceKey)); + }); + sendTags = true; + this.pendingTags = null; + } + + List configurationTasks = new ArrayList<>(); + FeatureFlagSet currentFeatureFlags = this.replayServer.worldData.enabledFeatures(); + List currentKnownPacks = this.replayServer.getResourceManager().listPacks().flatMap(packResources -> packResources.location().knownPackInfo().stream()).toList(); + boolean synchronizeRegistries = false; + + List> initialPackets = new ArrayList<>(); + + // Handle enabled features + if (this.pendingFeatureFlags != null) { + if (!currentFeatureFlags.equals(this.pendingFeatureFlags)) { + currentFeatureFlags = this.pendingFeatureFlags; + initialPackets.add(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.pendingFeatureFlags))); + } + this.pendingFeatureFlags = null; + } + + if (this.pendingResetChat) { + initialPackets.add(ClientboundResetChatPacket.INSTANCE); + this.pendingResetChat = false; + } + + if (this.pendingKnownPacks != null) { + Set currentSet = new HashSet<>(currentKnownPacks); + Set pendingSet = new HashSet<>(this.pendingKnownPacks); + + if (!currentSet.equals(pendingSet)) { + currentKnownPacks = this.pendingKnownPacks; + synchronizeRegistries = true; + } + + this.pendingKnownPacks = null; + } + + if (this.pendingRegistryMap != null && !this.pendingRegistryMap.isEmpty()) { + Map>, List> entries = this.pendingRegistryMap; + this.pendingRegistryMap = null; + + ResourceProvider resourceProvider = this.replayServer.getResourceManager(); + RegistryAccess accessForLoading = this.replayServer.registries().getAccessForLoading(RegistryLayer.WORLDGEN); + + RegistryAccess.Frozen synchronizedRegistries = RegistryDataLoader.load(entries, resourceProvider, accessForLoading, + RegistryDataLoader.SYNCHRONIZED_REGISTRIES); + + if (!RegistryHelper.equals(this.replayServer.registryAccess(), synchronizedRegistries, RegistryDataLoader.SYNCHRONIZED_REGISTRIES)) { + Set> neededRegistries = new HashSet<>(); + for (RegistryDataLoader.RegistryData worldgenRegistry : RegistryDataLoader.WORLDGEN_REGISTRIES) { + neededRegistries.add(worldgenRegistry.key()); + } + + List> registries = new ArrayList<>(); + + // Add all synchronized registries + synchronizedRegistries.registries().forEach(e -> { + if (neededRegistries.remove(e.key())) { + registries.add(e.value()); + } + }); + // Add all other registries + this.replayServer.registryAccess().registries().forEach(e -> { + if (neededRegistries.remove(e.key())) { + registries.add(e.value()); + } + }); + + var finalRegistries = new RegistryAccess.ImmutableRegistryAccess(registries); + + var newRegistries = this.replayServer.registries.replaceFrom(RegistryLayer.WORLDGEN, finalRegistries.freeze()); + + this.replayServer.registries.keys = newRegistries.keys; + this.replayServer.registries.values = newRegistries.values; + ((RegistryAccess.ImmutableRegistryAccess)this.replayServer.registries.composite).registries = + ((RegistryAccess.ImmutableRegistryAccess)newRegistries.composite).registries; + + synchronizeRegistries = true; + } + } + + if (synchronizeRegistries) { + configurationTasks.add(new SynchronizeRegistriesTask(currentKnownPacks, this.replayServer.registries)); + sendTags = false; + } + + if (sendTags) { + this.replayServer.getPlayerList().broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.replayServer.registries))); + } + + if (initialPackets.isEmpty() && configurationTasks.isEmpty()) { + return; + } + + configurationTasks.add(new JoinWorldTask()); + + Collection selectedPacks = knownPacksToIds(this.replayServer.getPackRepository(), currentKnownPacks); + this.replayServer.updateRegistry(currentFeatureFlags, selectedPacks, initialPackets, configurationTasks); + + // Remove all players + for (ServerPlayer player : new ArrayList<>(this.replayServer.getPlayerList().getPlayers())) { + player.connection.disconnect(Component.empty()); + } + + // Remove all levels + for (ServerLevel value : this.replayServer.levels.values()) { + this.replayServer.closeLevel(value); + } + this.replayServer.levels.clear(); + + // Recreate overworld + ServerLevelData serverLevelData = this.replayServer.worldData.overworldData(); + Holder.Reference plains = this.replayServer.registryAccess().registryOrThrow(Registries.BIOME).getHolderOrThrow(Biomes.PLAINS); + LevelStem levelStem = new LevelStem(this.replayServer.registryAccess().registryOrThrow(Registries.DIMENSION_TYPE).getHolderOrThrow(BuiltinDimensionTypes.OVERWORLD), new EmptyLevelSource(plains)); + var progressListener = this.replayServer.progressListenerFactory.create(this.replayServer.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS)); + ServerLevel serverLevel = new ServerLevel(this.replayServer, this.replayServer.executor, this.replayServer.storageSource, + serverLevelData, Level.OVERWORLD, levelStem, progressListener, + false, 0, List.of(), false, null); + serverLevel.noSave = true; + this.replayServer.levels.put(Level.OVERWORLD, serverLevel); + } + + private static Collection knownPacksToIds(PackRepository packRepository, Collection knownPacks) { + Collection selectedPacks = new ArrayList<>(); + ImmutableMap.Builder builder = ImmutableMap.builder(); + packRepository.getAvailablePacks().forEach(pack -> { + PackLocationInfo packLocationInfo = pack.location(); + packLocationInfo.knownPackInfo().ifPresent(knownPack -> builder.put(knownPack, packLocationInfo.id())); + }); + Map knownPackToId = builder.build(); + for (KnownPack knownPack : knownPacks) { + String selectedId = knownPackToId.get(knownPack); + if (selectedId != null) { + selectedPacks.add(selectedId); + } + } + return selectedPacks; + } + + @Override + public void handleConfigurationFinished(ClientboundFinishConfigurationPacket clientboundFinishConfigurationPacket) { + throw new UnsupportedPacketException(clientboundFinishConfigurationPacket); + } + + @Override + public void handleRegistryData(ClientboundRegistryDataPacket clientboundRegistryDataPacket) { + this.dirty = true; + if (this.pendingRegistryMap == null) { + this.pendingRegistryMap = new HashMap<>(); + } + this.pendingRegistryMap.put(clientboundRegistryDataPacket.registry(), clientboundRegistryDataPacket.entries()); + } + + @Override + public void handleEnabledFeatures(ClientboundUpdateEnabledFeaturesPacket clientboundUpdateEnabledFeaturesPacket) { + this.dirty = true; + this.pendingFeatureFlags = FeatureFlags.REGISTRY.fromNames(clientboundUpdateEnabledFeaturesPacket.features()); + } + + @Override + public void handleSelectKnownPacks(ClientboundSelectKnownPacks clientboundSelectKnownPacks) { + this.dirty = true; + this.pendingKnownPacks = clientboundSelectKnownPacks.knownPacks(); + } + + @Override + public void handleResetChat(ClientboundResetChatPacket clientboundResetChatPacket) { + this.dirty = true; + this.pendingResetChat = true; + } + + @Override + public void handleKeepAlive(ClientboundKeepAlivePacket clientboundKeepAlivePacket) { + throw new UnsupportedPacketException(clientboundKeepAlivePacket); + } + + @Override + public void handlePing(ClientboundPingPacket clientboundPingPacket) { + throw new UnsupportedPacketException(clientboundPingPacket); + } + + @Override + public void handleCustomPayload(ClientboundCustomPayloadPacket clientboundCustomPayloadPacket) { + } + + @Override + public void handleDisconnect(ClientboundDisconnectPacket clientboundDisconnectPacket) { + throw new UnsupportedPacketException(clientboundDisconnectPacket); + } + + @Override + public void handleResourcePackPush(ClientboundResourcePackPushPacket clientboundResourcePackPushPacket) { + this.replayServer.pushRemotePack(clientboundResourcePackPushPacket.id(), + clientboundResourcePackPushPacket.url(), clientboundResourcePackPushPacket.hash()); + } + + @Override + public void handleResourcePackPop(ClientboundResourcePackPopPacket clientboundResourcePackPopPacket) { + if (clientboundResourcePackPopPacket.id().isEmpty()) { + this.replayServer.popAllRemotePacks(); + } else { + this.replayServer.popRemotePack(clientboundResourcePackPopPacket.id().get()); + } + } + + @Override + public void handleUpdateTags(ClientboundUpdateTagsPacket clientboundUpdateTagsPacket) { + this.dirty = true; + if (this.pendingTags == null) { + this.pendingTags = new HashMap<>(); + } + this.pendingTags.putAll(clientboundUpdateTagsPacket.getTags()); + } + + @Override + public void handleStoreCookie(ClientboundStoreCookiePacket clientboundStoreCookiePacket) { + throw new UnsupportedPacketException(clientboundStoreCookiePacket); + } + + @Override + public void handleTransfer(ClientboundTransferPacket clientboundTransferPacket) { + throw new UnsupportedPacketException(clientboundTransferPacket); + } + + @Override + public void handleRequestCookie(ClientboundCookieRequestPacket clientboundCookieRequestPacket) { + throw new UnsupportedPacketException(clientboundCookieRequestPacket); + } + + @Override + public void onDisconnect(Component component) { + + } + + @Override + public boolean isAcceptingMessages() { + return false; + } +} diff --git a/src/client/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/client/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java new file mode 100644 index 0000000..7d829e8 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -0,0 +1,1380 @@ +package com.moulberry.flashback.playback; + +import com.google.common.collect.Multimap; +import com.mojang.authlib.GameProfile; +import com.moulberry.flashback.ChunkSectionHash; +import com.moulberry.flashback.exception.UnsupportedPacketException; +import com.moulberry.flashback.ext.LevelChunkSectionExt; +import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; +import com.moulberry.flashback.player.ReplayPlayer; +import io.netty.channel.embedded.EmbeddedChannel; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.core.SectionPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.Connection; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.common.ClientboundStoreCookiePacket; +import net.minecraft.network.protocol.common.ClientboundTransferPacket; +import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; +import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; +import net.minecraft.network.protocol.game.*; +import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket; +import net.minecraft.network.syncher.EntityDataAccessor; +import net.minecraft.network.syncher.SynchedEntityData; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.server.network.CommonListenerCookie; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.util.ExtraCodecs; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.LivingEntity; +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.ArmorStand; +import net.minecraft.world.entity.decoration.Painting; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LightLayer; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.DataLayer; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.status.ChunkStatus; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.lighting.LevelLightEngine; +import net.minecraft.world.level.storage.DerivedLevelData; +import net.minecraft.world.level.storage.ServerLevelData; +import net.minecraft.world.phys.Vec3; +import org.apache.commons.io.FileUtils; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +public class ReplayGamePacketHandler implements ClientGamePacketListener { + + private final ReplayServer replayServer; + private final Map playerInfoMap = new HashMap<>(); + private Int2ObjectMap pendingEntities = new Int2ObjectOpenHashMap<>(); + private ResourceKey currentDimension = null; + public int localPlayerId = -1; + + public ReplayGamePacketHandler(ReplayServer replayServer) { + this.replayServer = replayServer; + } + + private void forward(Packet packet) { + for (ServerPlayer replayViewer : this.replayServer.getReplayViewers()) { + replayViewer.connection.send(packet); + } + } + + private void forward(Entity entity, Packet packet) { + if (entity == null) { + return; + } + + ServerChunkCache serverChunkCache = this.level().getChunkSource(); + serverChunkCache.broadcast(entity, packet); + } + + public void flushPendingEntities() { + ServerLevel level = this.level(); + for (Entity pendingEntity : this.pendingEntities.values()) { + Entity existingEntity = level.getEntity(pendingEntity.getId()); + if (existingEntity != null) { + if (existingEntity.getType().equals(pendingEntity.getType())) { + existingEntity.restoreFrom(pendingEntity); + existingEntity.setPos(pendingEntity.getX(), pendingEntity.getY(), pendingEntity.getZ()); + existingEntity.setXRot(pendingEntity.getXRot()); + existingEntity.setYRot(pendingEntity.getYRot()); + existingEntity.setYHeadRot(pendingEntity.getYHeadRot()); + if (pendingEntity instanceof LivingEntity pendingLiving) { + existingEntity.setYBodyRot(pendingLiving.yBodyRot); + } + for (SynchedEntityData.DataItem dataItem : pendingEntity.getEntityData().itemsById) { + existingEntity.getEntityData().set((EntityDataAccessor) dataItem.getAccessor(), dataItem.getValue()); + } + continue; + } else { + existingEntity.discard(); + } + } + + level.addFreshEntity(pendingEntity); + ChunkPos chunkPos = new ChunkPos(pendingEntity.blockPosition()); + level.getChunkSource().addRegionTicket(ReplayServer.ENTITY_LOAD_TICKET, chunkPos, 3, chunkPos); + } + this.pendingEntities.clear(); + } + + private Entity getEntityOrPending(int entityId) { + if (this.pendingEntities.containsKey(entityId)) { + return this.pendingEntities.get(entityId); + } + this.flushPendingEntities(); + return this.level().getEntity(entityId); + } + + public ServerLevel level() { + return this.replayServer.getLevel(this.currentDimension); + } + + @Override + public void handleAddEntity(ClientboundAddEntityPacket clientboundAddEntityPacket) { + if (Entity.ENTITY_COUNTER.get() <= clientboundAddEntityPacket.getId()) { + Entity.ENTITY_COUNTER.set(clientboundAddEntityPacket.getId() + 1); + } + + Entity entity = this.createEntityFromPacket(clientboundAddEntityPacket); + if (entity != null) { + if (entity instanceof Painting) { + Direction direction = Direction.from3DDataValue(clientboundAddEntityPacket.getData()); + if (!direction.getAxis().isHorizontal()) { + clientboundAddEntityPacket.data = Direction.NORTH.get3DDataValue(); + } + } + entity.recreateFromPacket(clientboundAddEntityPacket); + this.pendingEntities.put(clientboundAddEntityPacket.getId(), entity); + } + } + + private void spawnPlayer(ClientboundAddEntityPacket addEntityPacket, GameProfile gameProfile, GameType gameType) { + CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false); + ServerPlayer serverPlayer = new ServerPlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()){ + @Override + public boolean isSpectator() { + return false; + } + + @Override + public boolean isCreative() { + return true; + } + }; + Connection connection = new Connection(PacketFlow.SERVERBOUND); + EmbeddedChannel embeddedChannel = new EmbeddedChannel(connection); + serverPlayer.recreateFromPacket(addEntityPacket); + this.replayServer.getPlayerList().placeNewPlayer(connection, serverPlayer, commonListenerCookie); + serverPlayer.setGameMode(gameType); + } + + @Nullable + private Entity createEntityFromPacket(ClientboundAddEntityPacket packet) { + EntityType entityType = packet.getType(); + if (entityType == EntityType.PLAYER) { + PlayerInfo playerInfo = this.playerInfoMap.get(packet.getUUID()); + if (playerInfo == null) { + return null; + } + + this.spawnPlayer(packet, playerInfo.getProfile(), playerInfo.getGameMode()); + return null; + } else { + return entityType.create(this.level()); + } + } + + @Override + public void handleAddExperienceOrb(ClientboundAddExperienceOrbPacket clientboundAddExperienceOrbPacket) { + double x = clientboundAddExperienceOrbPacket.getX(); + double y = clientboundAddExperienceOrbPacket.getY(); + double z = clientboundAddExperienceOrbPacket.getZ(); + ExperienceOrb entity = new ExperienceOrb(this.level(), x, y, z, clientboundAddExperienceOrbPacket.getValue()); + entity.syncPacketPositionCodec(x, y, z); + entity.setYRot(0.0f); + entity.setXRot(0.0f); + entity.setId(clientboundAddExperienceOrbPacket.getId()); + + Entity existingEntity = this.level().getEntity(clientboundAddExperienceOrbPacket.getId()); + if (existingEntity instanceof ExperienceOrb) { + existingEntity.restoreFrom(entity); + return; + } else if (existingEntity != null) { + existingEntity.discard(); + } + + this.level().addFreshEntity(entity); + } + + @Override + public void handleAddObjective(ClientboundSetObjectivePacket clientboundSetObjectivePacket) { + forward(clientboundSetObjectivePacket); + } + + @Override + public void handleAnimate(ClientboundAnimatePacket clientboundAnimatePacket) { + Entity entity = this.level().getEntity(clientboundAnimatePacket.getId()); + forward(entity, clientboundAnimatePacket); + } + + @Override + public void handleHurtAnimation(ClientboundHurtAnimationPacket clientboundHurtAnimationPacket) { + Entity entity = this.level().getEntity(clientboundHurtAnimationPacket.id()); + forward(entity, clientboundHurtAnimationPacket); + } + + @Override + public void handleAwardStats(ClientboundAwardStatsPacket clientboundAwardStatsPacket) { + throw new UnsupportedPacketException(clientboundAwardStatsPacket); + } + + @Override + public void handleAddOrRemoveRecipes(ClientboundRecipePacket clientboundRecipePacket) { + throw new UnsupportedPacketException(clientboundRecipePacket); + } + + @Override + public void handleBlockDestruction(ClientboundBlockDestructionPacket clientboundBlockDestructionPacket) { + forward(clientboundBlockDestructionPacket); + } + + @Override + public void handleOpenSignEditor(ClientboundOpenSignEditorPacket clientboundOpenSignEditorPacket) { + throw new UnsupportedPacketException(clientboundOpenSignEditorPacket); + } + + @Override + public void handleBlockEntityData(ClientboundBlockEntityDataPacket clientboundBlockEntityDataPacket) { + BlockPos blockPos = clientboundBlockEntityDataPacket.getPos(); + this.level().getBlockEntity(blockPos, clientboundBlockEntityDataPacket.getType()).ifPresent(blockEntity -> { + // Update data + blockEntity.loadWithComponents(clientboundBlockEntityDataPacket.getTag(), this.replayServer.registryAccess()); + + // Sync + blockEntity.setChanged(); + BlockState blockState = this.level().getBlockState(blockPos); + Level level = blockEntity.getLevel(); + if (level != null) { + level.sendBlockUpdated(blockPos, blockState, blockState, 3); + } + }); + } + + @Override + public void handleBlockEvent(ClientboundBlockEventPacket clientboundBlockEventPacket) { + BlockPos pos = clientboundBlockEventPacket.getPos(); + this.replayServer.getPlayerList().broadcast(null, pos.getX(), pos.getY(), pos.getZ(), + 64.0, this.level().dimension(), clientboundBlockEventPacket); + } + + @Override + public void handleBlockUpdate(ClientboundBlockUpdatePacket clientboundBlockUpdatePacket) { + this.level().setBlock(clientboundBlockUpdatePacket.getPos(), + clientboundBlockUpdatePacket.getBlockState(), 2); + } + + @Override + public void handleSystemChat(ClientboundSystemChatPacket clientboundSystemChatPacket) { + forward(clientboundSystemChatPacket); + } + + @Override + public void handlePlayerChat(ClientboundPlayerChatPacket clientboundPlayerChatPacket) { + throw new UnsupportedPacketException(clientboundPlayerChatPacket); + } + + @Override + public void handleDisguisedChat(ClientboundDisguisedChatPacket clientboundDisguisedChatPacket) { + forward(clientboundDisguisedChatPacket); + } + + @Override + public void handleDeleteChat(ClientboundDeleteChatPacket clientboundDeleteChatPacket) { + throw new UnsupportedPacketException(clientboundDeleteChatPacket); + } + + @Override + public void handleChunkBlocksUpdate(ClientboundSectionBlocksUpdatePacket clientboundSectionBlocksUpdatePacket) { + clientboundSectionBlocksUpdatePacket.runUpdates((blockPos, blockState) -> { + this.level().setBlock(blockPos, blockState, 2); + }); + } + + @Override + public void handleMapItemData(ClientboundMapItemDataPacket clientboundMapItemDataPacket) { + forward(clientboundMapItemDataPacket); + } + + @Override + public void handleContainerClose(ClientboundContainerClosePacket clientboundContainerClosePacket) { + throw new UnsupportedPacketException(clientboundContainerClosePacket); + } + + @Override + public void handleContainerContent(ClientboundContainerSetContentPacket clientboundContainerSetContentPacket) { + throw new UnsupportedPacketException(clientboundContainerSetContentPacket); + } + + @Override + public void handleHorseScreenOpen(ClientboundHorseScreenOpenPacket clientboundHorseScreenOpenPacket) { + throw new UnsupportedPacketException(clientboundHorseScreenOpenPacket); + } + + @Override + public void handleContainerSetData(ClientboundContainerSetDataPacket clientboundContainerSetDataPacket) { + throw new UnsupportedPacketException(clientboundContainerSetDataPacket); + } + + @Override + public void handleContainerSetSlot(ClientboundContainerSetSlotPacket clientboundContainerSetSlotPacket) { + throw new UnsupportedPacketException(clientboundContainerSetSlotPacket); + } + + @Override + public void handleEntityEvent(ClientboundEntityEventPacket clientboundEntityEventPacket) { + Entity entity = clientboundEntityEventPacket.getEntity(this.level()); + forward(entity, clientboundEntityEventPacket); + } + + @Override + public void handleEntityLinkPacket(ClientboundSetEntityLinkPacket clientboundSetEntityLinkPacket) { + Entity source = this.level().getEntity(clientboundSetEntityLinkPacket.getSourceId()); + if (source instanceof Mob mob) { + Entity dest = this.level().getEntity(clientboundSetEntityLinkPacket.getDestId()); + mob.setLeashedTo(dest, true); + } + } + + @Override + public void handleSetEntityPassengersPacket(ClientboundSetPassengersPacket clientboundSetPassengersPacket) { + Entity vehicle = this.level().getEntity(clientboundSetPassengersPacket.getVehicle()); + if (vehicle == null) { + return; + } + vehicle.ejectPassengers(); + for (int passengerId : clientboundSetPassengersPacket.getPassengers()) { + Entity passenger = this.level().getEntity(passengerId); + if (passenger == null) { + continue; + } + + passenger.startRiding(vehicle, true); + } + } + + @Override + public void handleExplosion(ClientboundExplodePacket e) { + ClientboundExplodePacket withoutKnockback = new ClientboundExplodePacket(e.getX(), e.getY(), e.getZ(), + e.getPower(), e.getToBlow(), null, e.getBlockInteraction(), e.getSmallExplosionParticles(), e.getLargeExplosionParticles(), + e.getExplosionSound()); + forward(withoutKnockback); + } + + @Override + public void handleGameEvent(ClientboundGameEventPacket clientboundGameEventPacket) { + if (clientboundGameEventPacket.getEvent() != ClientboundGameEventPacket.CHANGE_GAME_MODE) { + forward(clientboundGameEventPacket); + } + } + + @Override + public void handleLevelChunkWithLight(ClientboundLevelChunkWithLightPacket levelChunkWithLightPacket) { + int x = levelChunkWithLightPacket.getX(); + int z = levelChunkWithLightPacket.getZ(); + + LevelLightEngine levelLightEngine = this.level().getChunkSource().getLightEngine(); + LevelChunk chunk = this.level().getChunk(x, z); + + var chunkData = levelChunkWithLightPacket.getChunkData(); + boolean shouldSendChunkData = true; + + if (this.replayServer.isProcessingSnapshot) { + boolean blockDataChanged = false; + + FriendlyByteBuf readBuffer = chunkData.getReadBuffer(); + CompoundTag heightmaps = chunkData.getHeightmaps(); + + chunk.clearAllBlockEntities(); + for (LevelChunkSection levelChunkSection : chunk.getSections()) { + if (!blockDataChanged) { + ChunkSectionHash hash = ((LevelChunkSectionExt)levelChunkSection).flashback$hashState(); + levelChunkSection.read(readBuffer); + blockDataChanged = !((LevelChunkSectionExt)levelChunkSection).flashback$doesHashedStateMatch(hash); + } else { + levelChunkSection.read(readBuffer); + } + } + for (Heightmap.Types heightmapType : Heightmap.Types.values()) { + String key = heightmapType.getSerializationKey(); + if (heightmaps.contains(key, CompoundTag.TAG_LONG_ARRAY)) { + chunk.setHeightmap(heightmapType, heightmaps.getLongArray(key)); + } + } + if (blockDataChanged) { + chunk.initializeLightSources(); + } + chunkData.getBlockEntitiesTagsConsumer(x, z).accept((blockPos, blockEntityType, compoundTag) -> { + BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.IMMEDIATE); + if (blockEntity != null && compoundTag != null && blockEntity.getType() == blockEntityType) { + blockEntity.loadWithComponents(compoundTag, this.level().registryAccess()); + } + }); + + shouldSendChunkData = blockDataChanged; + } else { + chunk.replaceWithPacketData(chunkData.getReadBuffer(), chunkData.getHeightmaps(), chunkData.getBlockEntitiesTagsConsumer(x, z)); + } + + // todo: can we avoid updating the light data? + var lightData = levelChunkWithLightPacket.getLightData(); + this.applyLightData(levelLightEngine, x, z, lightData); + + if (shouldSendChunkData) { + ChunkPos chunkPos = chunk.getPos(); + for (ServerPlayer serverPlayer : this.replayServer.getReplayViewers()) { + if (serverPlayer.getChunkTrackingView().contains(chunkPos)) { + serverPlayer.connection.chunkSender.markChunkPendingToSend(chunk); + } + } + } + + chunk.setUnsaved(true); + } + + private void applyLightData(LevelLightEngine levelLightEngine, int x, int z, ClientboundLightUpdatePacketData clientboundLightUpdatePacketData) { + levelLightEngine.retainData(new ChunkPos(x, z), true); + + BitSet skyYMask = clientboundLightUpdatePacketData.getSkyYMask(); + BitSet emptySkyYMask = clientboundLightUpdatePacketData.getEmptySkyYMask(); + Iterator iterator = clientboundLightUpdatePacketData.getSkyUpdates().iterator(); + this.readSectionList(x, z, levelLightEngine, LightLayer.SKY, skyYMask, emptySkyYMask, iterator); + + BitSet blockYMask = clientboundLightUpdatePacketData.getBlockYMask(); + BitSet emptyBlockYMask = clientboundLightUpdatePacketData.getEmptyBlockYMask(); + Iterator iterator2 = clientboundLightUpdatePacketData.getBlockUpdates().iterator(); + this.readSectionList(x, z, levelLightEngine, LightLayer.BLOCK, blockYMask, emptyBlockYMask, iterator2); + + ((ThreadedLevelLightEngineExt)levelLightEngine).flashback$submitPost(x, z, () -> { + // Initialize light + LevelChunk chunkAccess = this.level().getChunk(x, z); + // todo: do we need to do this if replaceWithPacketData already does it? + chunkAccess.initializeLightSources(); + boolean isLightCorrect = chunkAccess.getStatus().isOrAfter(ChunkStatus.LIGHT) && chunkAccess.isLightCorrect(); + ((ThreadedLevelLightEngine)levelLightEngine).initializeLight(chunkAccess, isLightCorrect).thenRun(() -> { + // Send light data + LevelChunk chunkAccess2 = this.level().getChunk(x, z); + chunkAccess2.setLightCorrect(true); + + ChunkPos chunkPos = new ChunkPos(x, z); + var lightPacket = new ClientboundLightUpdatePacket(chunkPos, levelLightEngine, null, null); + for (ServerPlayer serverPlayer : this.replayServer.getReplayViewers()) { + if (serverPlayer.getChunkTrackingView().contains(chunkPos)) { + serverPlayer.connection.send(lightPacket); + } + } + }); + }); + } + + private void readSectionList(int x, int z, LevelLightEngine levelLightEngine, LightLayer lightLayer, BitSet yMask, BitSet emptyYMask, Iterator iterator) { + for(int index = 0; index < levelLightEngine.getLightSectionCount(); ++index) { + int y = levelLightEngine.getMinLightSection() + index; + boolean hasData = yMask.get(index); + boolean isEmpty = emptyYMask.get(index); + if (hasData || isEmpty) { + levelLightEngine.queueSectionData(lightLayer, SectionPos.of(x, y, z), hasData ? new DataLayer(iterator.next().clone()) : new DataLayer()); + } + } + } + + @Override + public void handleChunksBiomes(ClientboundChunksBiomesPacket clientboundChunksBiomesPacket) { + List chunks = new ArrayList<>(clientboundChunksBiomesPacket.chunkBiomeData().size()); + for (ClientboundChunksBiomesPacket.ChunkBiomeData chunkBiomeData : clientboundChunksBiomesPacket.chunkBiomeData()) { + LevelChunk chunk = this.level().getChunk(chunkBiomeData.pos().x, chunkBiomeData.pos().z); + chunk.replaceBiomes(chunkBiomeData.getReadBuffer()); + chunks.add(chunk); + } + this.level().getChunkSource().chunkMap.resendBiomesForChunks(chunks); + } + + @Override + public void handleForgetLevelChunk(ClientboundForgetLevelChunkPacket clientboundForgetLevelChunkPacket) { + throw new UnsupportedPacketException(clientboundForgetLevelChunkPacket); + } + + @Override + public void handleLevelEvent(ClientboundLevelEventPacket clientboundLevelEventPacket) { + if (clientboundLevelEventPacket.isGlobalEvent()) { + this.replayServer.getPlayerList().broadcastAll(clientboundLevelEventPacket); + } else { + BlockPos blockPos = clientboundLevelEventPacket.getPos(); + ResourceKey dimension = this.level().dimension(); + this.replayServer.getPlayerList().broadcast(null, blockPos.getX(), blockPos.getY(), blockPos.getZ(), 64.0, dimension, clientboundLevelEventPacket); + } + } + + @Override + public void handleLogin(ClientboundLoginPacket clientboundLoginPacket) { + ServerPlayer localPlayer = null; + boolean recreatePlayer = false; + + ServerLevel level = this.level(); + if (level != null && level.getEntity(this.localPlayerId) instanceof ServerPlayer serverPlayer) { + localPlayer = serverPlayer; + if (this.localPlayerId != clientboundLoginPacket.playerId()) { + localPlayer.connection.disconnect(Component.empty()); + recreatePlayer = true; + } + } + + this.localPlayerId = clientboundLoginPacket.playerId(); + this.ensureWorldCreated(clientboundLoginPacket.commonPlayerSpawnInfo(), recreatePlayer ? null : localPlayer, true); + + if (recreatePlayer) { + ClientboundAddEntityPacket addEntityPacket = new ClientboundAddEntityPacket(localPlayer); + addEntityPacket.id = clientboundLoginPacket.playerId(); + this.spawnPlayer(addEntityPacket, localPlayer.getGameProfile(), localPlayer.gameMode.getGameModeForPlayer()); + } + } + + public void handleCreateLocalPlayer(RegistryFriendlyByteBuf registryFriendlyByteBuf) { + UUID uuid = registryFriendlyByteBuf.readUUID(); + double x = registryFriendlyByteBuf.readDouble(); + double y = registryFriendlyByteBuf.readDouble(); + double z = registryFriendlyByteBuf.readDouble(); + float xRot = registryFriendlyByteBuf.readFloat(); + float yRot = registryFriendlyByteBuf.readFloat(); + float yHeadRot = registryFriendlyByteBuf.readFloat(); + Vec3 velocity = registryFriendlyByteBuf.readVec3(); + + ClientboundAddEntityPacket addEntityPacket = new ClientboundAddEntityPacket(this.localPlayerId, uuid, x, y, z, xRot, yRot, EntityType.PLAYER, 0, velocity, yHeadRot); + GameProfile gameProfile = ByteBufCodecs.GAME_PROFILE.decode(registryFriendlyByteBuf); + GameType gameType = GameType.byId(registryFriendlyByteBuf.readVarInt()); + + ServerLevel level = this.level(); + if (level.getEntity(this.localPlayerId) == null) { + this.spawnPlayer(addEntityPacket, gameProfile, gameType); + } + } + + private void ensureWorldCreated(CommonPlayerSpawnInfo commonPlayerSpawnInfo, Entity localPlayer, boolean forceReset) { + ResourceKey dimension = commonPlayerSpawnInfo.dimension(); + + if (forceReset) { + this.replayServer.clearReplayTempFolder(); + if (this.currentDimension == dimension) { + this.replayServer.clearLevel(this.level()); + } + } + + if (!this.replayServer.levels.containsKey(dimension)) { + ServerLevelData serverLevelData = this.replayServer.worldData.overworldData(); + if (dimension != Level.OVERWORLD) { + serverLevelData = new DerivedLevelData(this.replayServer.worldData, serverLevelData); + } + Holder.Reference plains = this.replayServer.registryAccess().registryOrThrow(Registries.BIOME).getHolder(Biomes.PLAINS).get(); + LevelStem levelStem = new LevelStem(commonPlayerSpawnInfo.dimensionType(), new EmptyLevelSource(plains)); + var progressListener = this.replayServer.progressListenerFactory.create(this.replayServer.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS)); + ServerLevel serverLevel = new ServerLevel(this.replayServer, this.replayServer.executor, this.replayServer.storageSource, + serverLevelData, dimension, levelStem, progressListener, + false, commonPlayerSpawnInfo.seed(), List.of(), false, null); + serverLevel.noSave = true; + this.replayServer.levels.put(dimension, serverLevel); + this.replayServer.followLocalPlayerNextTick = true; + } + + if (this.currentDimension == dimension) { + if (!this.replayServer.isProcessingSnapshot) { + this.replayServer.followLocalPlayerNextTick = true; + } + return; + } + + // Move local player and replay viewer + if (localPlayer != null) { + localPlayer.teleportTo(this.replayServer.getLevel(dimension), 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f); + } + for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { + replayViewer.teleportTo(this.replayServer.getLevel(dimension), 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f); + } + this.replayServer.followLocalPlayerNextTick = true; + + // Delete current dimension + if (this.currentDimension == Level.OVERWORLD) { + this.replayServer.clearLevel(this.level()); + } else if (this.currentDimension != null) { + ServerLevel level = this.replayServer.levels.remove(this.currentDimension); + if (level != null) { + this.replayServer.closeLevel(level); + } + } + + // Change to new dimension + this.currentDimension = commonPlayerSpawnInfo.dimension(); + this.replayServer.spawnLevel = this.currentDimension; + } + + @Override + public void handleMoveEntity(ClientboundMoveEntityPacket clientboundMoveEntityPacket) { + throw new UnsupportedPacketException(clientboundMoveEntityPacket); +// Entity entity = clientboundMoveEntityPacket.getEntity(this.level()); +// if (entity == null) { +// return; +// } +// if (entity.getId() == this.localPlayerId) { +// return; +// } +// +// if (clientboundMoveEntityPacket.hasPosition()) { +// VecDeltaCodec vecDeltaCodec = entity.getPositionCodec(); +// Vec3 position = vecDeltaCodec.decode(clientboundMoveEntityPacket.getXa(), clientboundMoveEntityPacket.getYa(), clientboundMoveEntityPacket.getZa()); +// vecDeltaCodec.setBase(position); +// float yaw = clientboundMoveEntityPacket.hasRotation() ? (float)(clientboundMoveEntityPacket.getyRot() * 360) / 256.0f : entity.lerpTargetYRot(); +// float pitch = clientboundMoveEntityPacket.hasRotation() ? (float)(clientboundMoveEntityPacket.getxRot() * 360) / 256.0f : entity.lerpTargetXRot(); +// entity.moveTo(position.x(), position.y(), position.z(), yaw, pitch); +// } else if (clientboundMoveEntityPacket.hasRotation()) { +// float yaw = (float)(clientboundMoveEntityPacket.getyRot() * 360) / 256.0f; +// float pitch = (float)(clientboundMoveEntityPacket.getxRot() * 360) / 256.0f; +// entity.setYRot(yaw); +// entity.setXRot(pitch); +// } +// +// entity.setOnGround(clientboundMoveEntityPacket.isOnGround()); + } + + @Override + public void handleMovePlayer(ClientboundPlayerPositionPacket clientboundPlayerPositionPacket) { + throw new UnsupportedPacketException(clientboundPlayerPositionPacket); + +// Entity entity = this.level().getEntity(this.localPlayerId); +// if (entity == null) { +// return; +// } +// +// Set flags = clientboundPlayerPositionPacket.getRelativeArguments(); +// +// double x = entity.getX(); +// double y = entity.getY(); +// double z = entity.getZ(); +// float yaw = entity.getYRot(); +// float pitch = entity.getXRot(); +// +// if (flags.contains(RelativeMovement.X)) { +// x += clientboundPlayerPositionPacket.getX(); +// } else { +// x = clientboundPlayerPositionPacket.getX(); +// } +// if (flags.contains(RelativeMovement.Y)) { +// y += clientboundPlayerPositionPacket.getY(); +// } else { +// y = clientboundPlayerPositionPacket.getY(); +// } +// if (flags.contains(RelativeMovement.Z)) { +// z += clientboundPlayerPositionPacket.getZ(); +// } else { +// z = clientboundPlayerPositionPacket.getZ(); +// } +// if (flags.contains(RelativeMovement.Y_ROT)) { +// yaw += clientboundPlayerPositionPacket.getYRot(); +// } else { +// yaw = clientboundPlayerPositionPacket.getYRot(); +// } +// if (flags.contains(RelativeMovement.X_ROT)) { +// pitch += clientboundPlayerPositionPacket.getXRot(); +// } else { +// pitch = clientboundPlayerPositionPacket.getXRot(); +// } +// +// entity.moveTo(x, y, z, Mth.wrapDegrees(yaw), Mth.wrapDegrees(pitch)); +// entity.setYHeadRot(entity.getYRot()); + } + + @Override + public void handleParticleEvent(ClientboundLevelParticlesPacket clientboundLevelParticlesPacket) { + for (ServerPlayer viewer : this.replayServer.getReplayViewers()) { + boolean overrideLimiter = clientboundLevelParticlesPacket.isOverrideLimiter(); + double x = clientboundLevelParticlesPacket.getX(); + double y = clientboundLevelParticlesPacket.getY(); + double z = clientboundLevelParticlesPacket.getZ(); + this.level().sendParticles(viewer, overrideLimiter, x, y, z, clientboundLevelParticlesPacket); + } + } + + @Override + public void handlePlayerAbilities(ClientboundPlayerAbilitiesPacket clientboundPlayerAbilitiesPacket) { + throw new UnsupportedPacketException(clientboundPlayerAbilitiesPacket); + } + + @Override + public void handlePlayerInfoRemove(ClientboundPlayerInfoRemovePacket clientboundPlayerInfoRemovePacket) { + for (UUID uuid : clientboundPlayerInfoRemovePacket.profileIds()) { + this.playerInfoMap.remove(uuid); + } + forward(clientboundPlayerInfoRemovePacket); + } + + @Override + public void handlePlayerInfoUpdate(ClientboundPlayerInfoUpdatePacket clientboundPlayerInfoUpdatePacket) { + for (ClientboundPlayerInfoUpdatePacket.Entry entry : clientboundPlayerInfoUpdatePacket.newEntries()) { + PlayerInfo playerInfo = new PlayerInfo(Objects.requireNonNull(entry.profile()), false); + this.playerInfoMap.putIfAbsent(entry.profileId(), playerInfo); + } + forward(clientboundPlayerInfoUpdatePacket); + } + + @Override + public void handleRemoveEntities(ClientboundRemoveEntitiesPacket clientboundRemoveEntitiesPacket) { + clientboundRemoveEntitiesPacket.getEntityIds().forEach(i -> { + Entity entity = this.level().getEntity(i); + if (entity != null) { + if (entity instanceof ServerPlayer serverPlayer) { + serverPlayer.connection.disconnect(Component.empty()); + } else { + entity.discard(); + } + } + }); + } + + @Override + public void handleRemoveMobEffect(ClientboundRemoveMobEffectPacket clientboundRemoveMobEffectPacket) { + Entity entity = clientboundRemoveMobEffectPacket.getEntity(this.level()); + if (entity instanceof LivingEntity livingEntity) { + livingEntity.removeEffect(clientboundRemoveMobEffectPacket.effect()); + } + } + + @Override + public void handleRespawn(ClientboundRespawnPacket clientboundRespawnPacket) { + Entity localPlayer = null; + ServerLevel level = this.level(); + if (level != null) { + localPlayer = level.getEntity(this.localPlayerId); + } + + this.ensureWorldCreated(clientboundRespawnPacket.commonPlayerSpawnInfo(), localPlayer, false); + } + + @Override + public void handleRotateMob(ClientboundRotateHeadPacket clientboundRotateHeadPacket) { + Entity entity = this.getEntityOrPending(clientboundRotateHeadPacket.entityId); + if (entity == null || entity.getId() == this.localPlayerId) { + return; + } + + entity.setYHeadRot(clientboundRotateHeadPacket.getYHeadRot()); + } + + @Override + public void handleSetCarriedItem(ClientboundSetCarriedItemPacket clientboundSetCarriedItemPacket) { + throw new UnsupportedPacketException(clientboundSetCarriedItemPacket); + } + + @Override + public void handleSetDisplayObjective(ClientboundSetDisplayObjectivePacket clientboundSetDisplayObjectivePacket) { + forward(clientboundSetDisplayObjectivePacket); + } + + @Override + public void handleSetEntityData(ClientboundSetEntityDataPacket clientboundSetEntityDataPacket) { + Entity entity = this.getEntityOrPending(clientboundSetEntityDataPacket.id()); + if (entity == null) { + return; + } + + SynchedEntityData entityData = entity.getEntityData(); + for (SynchedEntityData.DataValue dataValue : clientboundSetEntityDataPacket.packedItems()) { + SynchedEntityData.DataItem dataItem = entityData.itemsById[dataValue.id()]; + entityData.set((EntityDataAccessor) dataItem.getAccessor(), dataValue.value()); + } + } + + @Override + public void handleSetEntityMotion(ClientboundSetEntityMotionPacket clientboundSetEntityMotionPacket) { + Entity entity = this.getEntityOrPending(clientboundSetEntityMotionPacket.getId()); + if (entity == null) { + return; + } + + double motionX = clientboundSetEntityMotionPacket.getXa() / 8000.0; + double motionY = clientboundSetEntityMotionPacket.getYa() / 8000.0; + double motionZ = clientboundSetEntityMotionPacket.getZa() / 8000.0; + entity.setDeltaMovement(motionX, motionY, motionZ); + } + + @Override + public void handleSetEquipment(ClientboundSetEquipmentPacket clientboundSetEquipmentPacket) { + Entity entity = this.getEntityOrPending(clientboundSetEquipmentPacket.getEntity()); + if (entity instanceof LivingEntity livingEntity) { + clientboundSetEquipmentPacket.getSlots().forEach((pair) -> { + livingEntity.setItemSlot(pair.getFirst(), pair.getSecond()); + }); + forward(entity, clientboundSetEquipmentPacket); + } + } + + @Override + public void handleSetExperience(ClientboundSetExperiencePacket clientboundSetExperiencePacket) { + Entity entity = this.level().getEntity(this.localPlayerId); + if (entity instanceof Player player) { + player.experienceProgress = clientboundSetExperiencePacket.getExperienceProgress(); + player.totalExperience = clientboundSetExperiencePacket.getTotalExperience(); + player.experienceLevel = clientboundSetExperiencePacket.getExperienceLevel(); + } + } + + @Override + public void handleSetHealth(ClientboundSetHealthPacket clientboundSetHealthPacket) { + 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()); + } + } + + @Override + public void handleSetPlayerTeamPacket(ClientboundSetPlayerTeamPacket clientboundSetPlayerTeamPacket) { + forward(clientboundSetPlayerTeamPacket); + } + + @Override + public void handleSetScore(ClientboundSetScorePacket clientboundSetScorePacket) { + forward(clientboundSetScorePacket); + } + + @Override + public void handleResetScore(ClientboundResetScorePacket clientboundResetScorePacket) { + forward(clientboundResetScorePacket); + } + + @Override + public void handleSetSpawn(ClientboundSetDefaultSpawnPositionPacket clientboundSetDefaultSpawnPositionPacket) { + this.level().setDefaultSpawnPos(clientboundSetDefaultSpawnPositionPacket.getPos(), clientboundSetDefaultSpawnPositionPacket.getAngle()); + } + + @Override + public void handleSetTime(ClientboundSetTimePacket clientboundSetTimePacket) { + boolean updateTime = true; + + long dayTime = clientboundSetTimePacket.getDayTime(); + if (dayTime < 0) { + dayTime = -dayTime; + updateTime = false; + } + + for (ServerLevel level : this.replayServer.getAllLevels()) { + if (level.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT) != updateTime) { + level.getGameRules().getRule(GameRules.RULE_DAYLIGHT).set(updateTime, this.replayServer); + } + + level.setDayTime(dayTime); + + if (level.getLevelData() instanceof ServerLevelData serverLevelData) { + serverLevelData.setGameTime(clientboundSetTimePacket.getGameTime()); + } + } + this.replayServer.forceTimeSynchronization(); + } + + @Override + public void handleSoundEvent(ClientboundSoundPacket clientboundSoundPacket) { + Holder sound = clientboundSoundPacket.getSound(); + double x = clientboundSoundPacket.getX(); + double y = clientboundSoundPacket.getY(); + double z = clientboundSoundPacket.getZ(); + float volume = clientboundSoundPacket.getVolume(); + ResourceKey dimension = this.level().dimension(); + this.replayServer.getPlayerList().broadcast(null, x, y, z, sound.value().getRange(volume), dimension, clientboundSoundPacket); + } + + @Override + public void handleSoundEntityEvent(ClientboundSoundEntityPacket clientboundSoundEntityPacket) { + Entity entity = this.level().getEntity(clientboundSoundEntityPacket.getId()); + if (entity == null) { + return; + } + + Holder sound = clientboundSoundEntityPacket.getSound(); + double x = entity.getX(); + double y = entity.getY(); + double z = entity.getZ(); + float volume = clientboundSoundEntityPacket.getVolume(); + ResourceKey dimension = this.level().dimension(); + this.replayServer.getPlayerList().broadcast(null, x, y, z, sound.value().getRange(volume), dimension, clientboundSoundEntityPacket); + } + + @Override + public void handleTakeItemEntity(ClientboundTakeItemEntityPacket clientboundTakeItemEntityPacket) { + Entity taker = this.level().getEntity(clientboundTakeItemEntityPacket.getPlayerId()); + forward(taker, clientboundTakeItemEntityPacket); + + Entity taken = this.level().getEntity(clientboundTakeItemEntityPacket.getItemId()); + if (taken != null) { + taken.discard(); + } + } + + @Override + public void handleTeleportEntity(ClientboundTeleportEntityPacket clientboundTeleportEntityPacket) { + Entity entity = this.getEntityOrPending(clientboundTeleportEntityPacket.getId()); + if (entity == null) { + return; + } + + double x = clientboundTeleportEntityPacket.getX(); + double y = clientboundTeleportEntityPacket.getY(); + double z = clientboundTeleportEntityPacket.getZ(); + float yaw = (float)(clientboundTeleportEntityPacket.getyRot() * 360) / 256.0F; + float pitch = (float)(clientboundTeleportEntityPacket.getxRot() * 360) / 256.0F; + entity.moveTo(x, y, z, yaw, pitch); + entity.setOnGround(clientboundTeleportEntityPacket.isOnGround()); + entity.setYHeadRot(entity.getYRot()); + } + + @Override + public void handleTickingState(ClientboundTickingStatePacket clientboundTickingStatePacket) { + throw new UnsupportedPacketException(clientboundTickingStatePacket); + } + + @Override + public void handleTickingStep(ClientboundTickingStepPacket clientboundTickingStepPacket) { + throw new UnsupportedPacketException(clientboundTickingStepPacket); + } + + @Override + public void handleUpdateAttributes(ClientboundUpdateAttributesPacket clientboundUpdateAttributesPacket) { + Entity entity = this.getEntityOrPending(clientboundUpdateAttributesPacket.getEntityId()); + if (entity instanceof LivingEntity livingEntity) { + AttributeMap attributeMap = livingEntity.getAttributes(); + for (ClientboundUpdateAttributesPacket.AttributeSnapshot snapshot : clientboundUpdateAttributesPacket.getValues()) { + AttributeInstance attributeInstance = attributeMap.getInstance(snapshot.attribute()); + if (attributeInstance == null) { + continue; + } + + attributeInstance.setBaseValue(snapshot.base()); + attributeInstance.removeModifiers(); + for (AttributeModifier modifier : snapshot.modifiers()) { + attributeInstance.addTransientModifier(modifier); + } + } + } + } + + @Override + public void handleUpdateMobEffect(ClientboundUpdateMobEffectPacket clientboundUpdateMobEffectPacket) { + Entity entity = this.getEntityOrPending(clientboundUpdateMobEffectPacket.getEntityId()); + if (entity instanceof LivingEntity livingEntity) { + Holder holder = clientboundUpdateMobEffectPacket.getEffect(); + MobEffectInstance mobEffectInstance = new MobEffectInstance(holder, clientboundUpdateMobEffectPacket.getEffectDurationTicks(), clientboundUpdateMobEffectPacket.getEffectAmplifier(), + clientboundUpdateMobEffectPacket.isEffectAmbient(), clientboundUpdateMobEffectPacket.isEffectVisible(), clientboundUpdateMobEffectPacket.effectShowsIcon(), null); + if (!clientboundUpdateMobEffectPacket.shouldBlend()) { + mobEffectInstance.skipBlending(); + } + + livingEntity.forceAddEffect(mobEffectInstance, null); + } + } + + @Override + public void handlePlayerCombatEnd(ClientboundPlayerCombatEndPacket clientboundPlayerCombatEndPacket) { + throw new UnsupportedPacketException(clientboundPlayerCombatEndPacket); + } + + @Override + public void handlePlayerCombatEnter(ClientboundPlayerCombatEnterPacket clientboundPlayerCombatEnterPacket) { + throw new UnsupportedPacketException(clientboundPlayerCombatEnterPacket); + } + + @Override + public void handlePlayerCombatKill(ClientboundPlayerCombatKillPacket clientboundPlayerCombatKillPacket) { + throw new UnsupportedPacketException(clientboundPlayerCombatKillPacket); + } + + @Override + public void handleChangeDifficulty(ClientboundChangeDifficultyPacket clientboundChangeDifficultyPacket) { + this.replayServer.setDifficultyLocked(clientboundChangeDifficultyPacket.isLocked()); + this.replayServer.setDifficulty(clientboundChangeDifficultyPacket.getDifficulty(), true); + } + + @Override + public void handleSetCamera(ClientboundSetCameraPacket clientboundSetCameraPacket) { + throw new UnsupportedPacketException(clientboundSetCameraPacket); + } + + @Override + public void handleInitializeBorder(ClientboundInitializeBorderPacket clientboundInitializeBorderPacket) { + WorldBorder worldBorder = this.level().getWorldBorder(); + + worldBorder.setCenter(clientboundInitializeBorderPacket.getNewCenterX(), clientboundInitializeBorderPacket.getNewCenterZ()); + long lerpTime = clientboundInitializeBorderPacket.getLerpTime(); + if (lerpTime > 0L) { + worldBorder.lerpSizeBetween(clientboundInitializeBorderPacket.getOldSize(), clientboundInitializeBorderPacket.getNewSize(), lerpTime); + } else { + worldBorder.setSize(clientboundInitializeBorderPacket.getNewSize()); + } + worldBorder.setAbsoluteMaxSize(clientboundInitializeBorderPacket.getNewAbsoluteMaxSize()); + worldBorder.setWarningBlocks(clientboundInitializeBorderPacket.getWarningBlocks()); + worldBorder.setWarningTime(clientboundInitializeBorderPacket.getWarningTime()); + } + + @Override + public void handleSetBorderLerpSize(ClientboundSetBorderLerpSizePacket clientboundSetBorderLerpSizePacket) { + WorldBorder worldBorder = this.level().getWorldBorder(); + + long lerpTime = clientboundSetBorderLerpSizePacket.getLerpTime(); + if (lerpTime > 0L) { + worldBorder.lerpSizeBetween(clientboundSetBorderLerpSizePacket.getOldSize(), clientboundSetBorderLerpSizePacket.getNewSize(), lerpTime); + } else { + worldBorder.setSize(clientboundSetBorderLerpSizePacket.getNewSize()); + } + } + + @Override + public void handleSetBorderSize(ClientboundSetBorderSizePacket clientboundSetBorderSizePacket) { + WorldBorder worldBorder = this.level().getWorldBorder(); + worldBorder.setSize(clientboundSetBorderSizePacket.getSize()); + } + + @Override + public void handleSetBorderWarningDelay(ClientboundSetBorderWarningDelayPacket clientboundSetBorderWarningDelayPacket) { + WorldBorder worldBorder = this.level().getWorldBorder(); + worldBorder.setWarningTime(clientboundSetBorderWarningDelayPacket.getWarningDelay()); + } + + @Override + public void handleSetBorderWarningDistance(ClientboundSetBorderWarningDistancePacket clientboundSetBorderWarningDistancePacket) { + WorldBorder worldBorder = this.level().getWorldBorder(); + worldBorder.setWarningBlocks(clientboundSetBorderWarningDistancePacket.getWarningBlocks()); + } + + @Override + public void handleSetBorderCenter(ClientboundSetBorderCenterPacket clientboundSetBorderCenterPacket) { + WorldBorder worldBorder = this.level().getWorldBorder(); + worldBorder.setCenter(clientboundSetBorderCenterPacket.getNewCenterX(), clientboundSetBorderCenterPacket.getNewCenterZ()); + } + + @Override + public void handleTabListCustomisation(ClientboundTabListPacket clientboundTabListPacket) { + this.replayServer.setTabListCustomization(clientboundTabListPacket.header(), + clientboundTabListPacket.footer()); + } + + @Override + public void handleBossUpdate(ClientboundBossEventPacket clientboundBossEventPacket) { + this.replayServer.updateBossBar(clientboundBossEventPacket); + } + + @Override + public void handleItemCooldown(ClientboundCooldownPacket clientboundCooldownPacket) { + throw new UnsupportedPacketException(clientboundCooldownPacket); + } + + @Override + public void handleMoveVehicle(ClientboundMoveVehiclePacket clientboundMoveVehiclePacket) { + Entity player = this.level().getEntity(this.localPlayerId); + if (player instanceof Player) { + Entity vehicle = player.getRootVehicle(); + if (vehicle != player) { + double x = clientboundMoveVehiclePacket.getX(); + double y = clientboundMoveVehiclePacket.getY(); + double z = clientboundMoveVehiclePacket.getZ(); + float yaw = clientboundMoveVehiclePacket.getYRot(); + float pitch = clientboundMoveVehiclePacket.getXRot(); + vehicle.moveTo(x, y, z, yaw, pitch); + } + } + } + + @Override + public void handleUpdateAdvancementsPacket(ClientboundUpdateAdvancementsPacket clientboundUpdateAdvancementsPacket) { + throw new UnsupportedPacketException(clientboundUpdateAdvancementsPacket); + } + + @Override + public void handleSelectAdvancementsTab(ClientboundSelectAdvancementsTabPacket clientboundSelectAdvancementsTabPacket) { + throw new UnsupportedPacketException(clientboundSelectAdvancementsTabPacket); + } + + @Override + public void handlePlaceRecipe(ClientboundPlaceGhostRecipePacket clientboundPlaceGhostRecipePacket) { + throw new UnsupportedPacketException(clientboundPlaceGhostRecipePacket); + } + + @Override + public void handleCommands(ClientboundCommandsPacket clientboundCommandsPacket) { + throw new UnsupportedPacketException(clientboundCommandsPacket); + } + + @Override + public void handleStopSoundEvent(ClientboundStopSoundPacket clientboundStopSoundPacket) { + forward(clientboundStopSoundPacket); + } + + @Override + public void handleCommandSuggestions(ClientboundCommandSuggestionsPacket clientboundCommandSuggestionsPacket) { + throw new UnsupportedPacketException(clientboundCommandSuggestionsPacket); + } + + @Override + public void handleUpdateRecipes(ClientboundUpdateRecipesPacket clientboundUpdateRecipesPacket) { + throw new UnsupportedPacketException(clientboundUpdateRecipesPacket); + } + + @Override + public void handleLookAt(ClientboundPlayerLookAtPacket clientboundPlayerLookAtPacket) { + Vec3 position = clientboundPlayerLookAtPacket.getPosition(this.level()); + if (position != null) { + Entity player = this.level().getEntity(this.localPlayerId); + if (player instanceof Player) { + player.lookAt(clientboundPlayerLookAtPacket.getFromAnchor(), position); + } + } + } + + @Override + public void handleTagQueryPacket(ClientboundTagQueryPacket clientboundTagQueryPacket) { + throw new UnsupportedPacketException(clientboundTagQueryPacket); + } + + @Override + public void handleLightUpdatePacket(ClientboundLightUpdatePacket clientboundLightUpdatePacket) { + int x = clientboundLightUpdatePacket.getX(); + int z = clientboundLightUpdatePacket.getZ(); + + LevelLightEngine levelLightEngine = this.level().getChunkSource().getLightEngine(); + LevelChunk chunk = this.level().getChunk(x, z); + + var lightData = clientboundLightUpdatePacket.getLightData(); + this.applyLightData(levelLightEngine, x, z, lightData); + + chunk.setUnsaved(true); + } + + @Override + public void handleOpenBook(ClientboundOpenBookPacket clientboundOpenBookPacket) { + throw new UnsupportedPacketException(clientboundOpenBookPacket); + } + + @Override + public void handleOpenScreen(ClientboundOpenScreenPacket clientboundOpenScreenPacket) { + throw new UnsupportedPacketException(clientboundOpenScreenPacket); + } + + @Override + public void handleMerchantOffers(ClientboundMerchantOffersPacket clientboundMerchantOffersPacket) { + throw new UnsupportedPacketException(clientboundMerchantOffersPacket); + } + + @Override + public void handleSetChunkCacheRadius(ClientboundSetChunkCacheRadiusPacket clientboundSetChunkCacheRadiusPacket) { + throw new UnsupportedPacketException(clientboundSetChunkCacheRadiusPacket); + } + + @Override + public void handleSetSimulationDistance(ClientboundSetSimulationDistancePacket clientboundSetSimulationDistancePacket) { + throw new UnsupportedPacketException(clientboundSetSimulationDistancePacket); + } + + @Override + public void handleSetChunkCacheCenter(ClientboundSetChunkCacheCenterPacket clientboundSetChunkCacheCenterPacket) { + throw new UnsupportedPacketException(clientboundSetChunkCacheCenterPacket); + } + + @Override + public void handleBlockChangedAck(ClientboundBlockChangedAckPacket clientboundBlockChangedAckPacket) { + throw new UnsupportedPacketException(clientboundBlockChangedAckPacket); + } + + @Override + public void setActionBarText(ClientboundSetActionBarTextPacket clientboundSetActionBarTextPacket) { + forward(clientboundSetActionBarTextPacket); + } + + @Override + public void setSubtitleText(ClientboundSetSubtitleTextPacket clientboundSetSubtitleTextPacket) { + forward(clientboundSetSubtitleTextPacket); + } + + @Override + public void setTitleText(ClientboundSetTitleTextPacket clientboundSetTitleTextPacket) { + forward(clientboundSetTitleTextPacket); + } + + @Override + public void setTitlesAnimation(ClientboundSetTitlesAnimationPacket clientboundSetTitlesAnimationPacket) { + forward(clientboundSetTitlesAnimationPacket); + } + + @Override + public void handleTitlesClear(ClientboundClearTitlesPacket clientboundClearTitlesPacket) { + forward(clientboundClearTitlesPacket); + } + + @Override + public void handleServerData(ClientboundServerDataPacket clientboundServerDataPacket) { + forward(clientboundServerDataPacket); + } + + @Override + public void handleCustomChatCompletions(ClientboundCustomChatCompletionsPacket clientboundCustomChatCompletionsPacket) { + throw new UnsupportedPacketException(clientboundCustomChatCompletionsPacket); + } + + @Override + public void handleBundlePacket(ClientboundBundlePacket clientboundBundlePacket) { + for (Packet subPacket : clientboundBundlePacket.subPackets()) { + subPacket.handle(this); + } + } + + @Override + public void handleDamageEvent(ClientboundDamageEventPacket clientboundDamageEventPacket) { + Entity entity = this.level().getEntity(clientboundDamageEventPacket.entityId()); + forward(entity, clientboundDamageEventPacket); + } + + @Override + public void handleConfigurationStart(ClientboundStartConfigurationPacket clientboundStartConfigurationPacket) { + throw new UnsupportedPacketException(clientboundStartConfigurationPacket); + } + + @Override + public void handleChunkBatchStart(ClientboundChunkBatchStartPacket clientboundChunkBatchStartPacket) { + throw new UnsupportedPacketException(clientboundChunkBatchStartPacket); + } + + @Override + public void handleChunkBatchFinished(ClientboundChunkBatchFinishedPacket clientboundChunkBatchFinishedPacket) { + throw new UnsupportedPacketException(clientboundChunkBatchFinishedPacket); + } + + @Override + public void handleDebugSample(ClientboundDebugSamplePacket clientboundDebugSamplePacket) { + throw new UnsupportedPacketException(clientboundDebugSamplePacket); + } + + @Override + public void handleProjectilePowerPacket(ClientboundProjectilePowerPacket clientboundProjectilePowerPacket) { + Entity entity = this.level().getEntity(clientboundProjectilePowerPacket.getId()); + forward(entity, clientboundProjectilePowerPacket); + } + + @Override + public void handleKeepAlive(ClientboundKeepAlivePacket clientboundKeepAlivePacket) { + throw new UnsupportedPacketException(clientboundKeepAlivePacket); + } + + @Override + public void handlePing(ClientboundPingPacket clientboundPingPacket) { + throw new UnsupportedPacketException(clientboundPingPacket); + } + + @Override + public void handleCustomPayload(ClientboundCustomPayloadPacket clientboundCustomPayloadPacket) { + // todo: handle some custom packets here? + forward(clientboundCustomPayloadPacket); + } + + @Override + public void handleDisconnect(ClientboundDisconnectPacket clientboundDisconnectPacket) { + throw new UnsupportedPacketException(clientboundDisconnectPacket); + } + + @Override + public void handleResourcePackPush(ClientboundResourcePackPushPacket clientboundResourcePackPushPacket) { + this.replayServer.pushRemotePack(clientboundResourcePackPushPacket.id(), + clientboundResourcePackPushPacket.url(), clientboundResourcePackPushPacket.hash()); + } + + @Override + public void handleResourcePackPop(ClientboundResourcePackPopPacket clientboundResourcePackPopPacket) { + if (clientboundResourcePackPopPacket.id().isEmpty()) { + this.replayServer.popAllRemotePacks(); + } else { + this.replayServer.popRemotePack(clientboundResourcePackPopPacket.id().get()); + } + } + + @Override + public void handleUpdateTags(ClientboundUpdateTagsPacket clientboundUpdateTagsPacket) { + clientboundUpdateTagsPacket.getTags().forEach((resourceKey, networkPayload) -> { + networkPayload.applyToRegistry(this.replayServer.registryAccess().registryOrThrow(resourceKey)); + }); + forward(clientboundUpdateTagsPacket); + } + + @Override + public void handleStoreCookie(ClientboundStoreCookiePacket clientboundStoreCookiePacket) { + throw new UnsupportedPacketException(clientboundStoreCookiePacket); + } + + @Override + public void handleTransfer(ClientboundTransferPacket clientboundTransferPacket) { + throw new UnsupportedPacketException(clientboundTransferPacket); + } + + @Override + public void handleRequestCookie(ClientboundCookieRequestPacket clientboundCookieRequestPacket) { + throw new UnsupportedPacketException(clientboundCookieRequestPacket); + } + + @Override + public void handlePongResponse(ClientboundPongResponsePacket clientboundPongResponsePacket) { + throw new UnsupportedPacketException(clientboundPongResponsePacket); + } + + @Override + public void onDisconnect(Component component) { + } + + @Override + public boolean isAcceptingMessages() { + return false; + } + +} diff --git a/src/client/java/com/moulberry/flashback/playback/ReplayServer.java b/src/client/java/com/moulberry/flashback/playback/ReplayServer.java new file mode 100644 index 0000000..eed8aa4 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/playback/ReplayServer.java @@ -0,0 +1,736 @@ +package com.moulberry.flashback.playback; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.ext.ServerGamePacketListenerImplExt; +import com.moulberry.flashback.io.ReplayReader; +import com.moulberry.flashback.keyframe.Keyframes; +import com.moulberry.flashback.player.ReplayPlayer; +import com.moulberry.flashback.record.FlashbackChunkMeta; +import com.moulberry.flashback.record.FlashbackMeta; +import io.netty.buffer.ByteBuf; +import net.fabricmc.loader.api.FabricLoader; +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.RegistryFriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundBossEventPacket; +import net.minecraft.network.protocol.game.ClientboundTabListPacket; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Services; +import net.minecraft.server.WorldStem; +import net.minecraft.server.level.ClientInformation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.TicketType; +import net.minecraft.server.level.progress.ChunkProgressListenerFactory; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.players.PlayerList; +import net.minecraft.world.BossEvent; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.storage.LevelStorageSource; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class ReplayServer extends IntegratedServer { + + private static final Gson GSON = new Gson(); + + public volatile int jumpToTick = -1; + public volatile boolean replayPaused = true; + public volatile float desiredTickRate = 20.0f; + public AtomicBoolean finishedServerTick = new AtomicBoolean(false); + + private int currentTick = 0; + private int targetTick = 0; + private final int totalTicks; + public ResourceKey spawnLevel = null; + private final ReplayGamePacketHandler gamePacketHandler; + private final ReplayConfigurationPacketHandler configurationPacketHandler; + private StreamCodec> gamePacketCodec; + private final StreamCodec> configurationPacketCodec; + private final List replayViewers = new ArrayList<>(); + public boolean followLocalPlayerNextTick = false; + public boolean isProcessingSnapshot = false; + private boolean processedSnapshot = false; + + private final UUID playbackUUID = UUID.randomUUID(); + private final FlashbackMeta metadata; + private final TreeMap playableChunksByStart = new TreeMap<>(); + private ReplayReader currentReplayReader = null; + + private record RemotePack(UUID id, String url, String hash){} + private final Map oldRemotePacks = new HashMap<>(); + private final Map remotePacks = new HashMap<>(); + private final Map bossEvents = new HashMap<>(); + private Component tabListHeader = Component.empty(); + private Component tabListFooter = Component.empty(); + + public ReplayServer(Thread thread, Minecraft minecraft, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory) { + super(thread, minecraft, levelStorageAccess, packRepository, worldStem, services, chunkProgressListenerFactory); + this.gamePacketHandler = new ReplayGamePacketHandler(this); + this.configurationPacketHandler = new ReplayConfigurationPacketHandler(this); + + this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(this.registryAccess())).codec(); + this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); + + Path path = FabricLoader.getInstance().getGameDir().resolve("debug_recording.zip"); + try { + Path playbackFolder = FlashbackClient.getReplayPlaybackTemp(playbackUUID); + + byte[] buffer = new byte[1024]; + ZipInputStream zis = new ZipInputStream(Files.newInputStream(path)); + ZipEntry zipEntry = zis.getNextEntry(); + while (zipEntry != null) { + File newFile = newFile(playbackFolder.toFile(), zipEntry); + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory " + newFile); + } + } else { + // fix for Windows-created archives + File parent = newFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory " + parent); + } + + // write file content + FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + fos.close(); + } + zipEntry = zis.getNextEntry(); + } + + + String metadataJson = Files.readString(playbackFolder.resolve("metadata.json")); + this.metadata = FlashbackMeta.fromJson(GSON.fromJson(metadataJson, JsonObject.class)); + if (this.metadata == null) { + throw new RuntimeException("Invalid metadata file"); + } + + int ticks = 0; + for (Map.Entry entry : this.metadata.chunks.entrySet()) { + var chunkMetaWithPath = new PlayableChunk(entry.getValue(), playbackFolder.resolve(entry.getKey())); + this.playableChunksByStart.put(ticks, chunkMetaWithPath); + ticks += entry.getValue().duration; + } + + this.totalTicks = ticks; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { + File destFile = new File(destinationDir, zipEntry.getName()); + + String destDirPath = destinationDir.getCanonicalPath(); + String destFilePath = destFile.getCanonicalPath(); + + if (!destFilePath.startsWith(destDirPath + File.separator)) { + throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); + } + + return destFile; + } + + public void updateRegistry(FeatureFlagSet featureFlagSet, Collection selectedPacks, List> initialPackets, + List configurationTasks) { + this.worldData.setDataConfiguration(new WorldDataConfiguration( + this.worldData.getDataConfiguration().dataPacks(), + featureFlagSet + )); + this.reloadResources(selectedPacks); + + this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(this.registryAccess())).codec(); + + if (this.currentReplayReader != null) { + this.currentReplayReader.changeRegistryAccess(this.registryAccess()); + } + + List players = new ArrayList<>(this.getPlayerList().getPlayers()); + for (ServerPlayer player : players) { + if (player instanceof ReplayPlayer) { + ((ServerGamePacketListenerImplExt)player.connection).flashback$switchToConfigWithTasks(initialPackets, configurationTasks); + } + } + this.replayViewers.clear(); + } + + @Override + public boolean initServer() { + AtomicInteger newPlayerIds = new AtomicInteger(-981723987); + this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, 1) { + @Override + public ServerPlayer getPlayerForLogin(GameProfile gameProfile, ClientInformation clientInformation) { + ServerLevel level = ReplayServer.this.overworld(); + if (spawnLevel != null) { + ServerLevel serverLevel = ReplayServer.this.getLevel(spawnLevel); + if (serverLevel != null) { + level = serverLevel; + } + } + + ReplayPlayer player = new ReplayPlayer(ReplayServer.this, level, gameProfile, clientInformation); + player.setId(newPlayerIds.getAndDecrement()); + player.followLocalPlayerNextTick = true; + return player; + } + + @Override + public boolean canBypassPlayerLimit(GameProfile gameProfile) { + return true; + } + + @Override + public void broadcastSystemMessage(Component component, Function function, boolean bl) { + } + + @Override + public void sendLevelInfo(ServerPlayer serverPlayer, ServerLevel serverLevel) { + super.sendLevelInfo(serverPlayer, serverLevel); + + // Send all resource packs + serverPlayer.connection.send(new ClientboundResourcePackPopPacket(Optional.empty())); + for (RemotePack remotePack : remotePacks.values()) { + serverPlayer.connection.send(new ClientboundResourcePackPushPacket(remotePack.id, + remotePack.url, remotePack.hash, true, Optional.empty())); + } + + // Send tab list customization + serverPlayer.connection.send(new ClientboundTabListPacket(tabListHeader, tabListFooter)); + } + + @Override + protected void save(ServerPlayer serverPlayer) { + } + + @Override + public void saveAll() { + } + }); + + this.loadLevel(); + this.overworld().noSave = true; + + // Play initial snapshot + ReplayReader replayReader = this.playableChunksByStart.get(0).getOrLoadReplayReader(this.registryAccess()); + replayReader.handleSnapshot(this); + + return true; + } + + public void pushRemotePack(UUID uuid, String url, String hash) { + this.remotePacks.put(uuid, new RemotePack(uuid, url, hash)); + } + + public void popRemotePack(UUID uuid) { + this.remotePacks.remove(uuid); + } + + public void popAllRemotePacks() { + this.remotePacks.clear(); + } + + public void setTabListCustomization(Component header, Component footer) { + this.tabListHeader = header; + this.tabListFooter = footer; + this.getPlayerList().broadcastAll(new ClientboundTabListPacket(header, footer)); + } + + public void goToReplayTick(int tick) { + this.jumpToTick = tick; + } + + public int getReplayTick() { + return this.targetTick; + } + + private int lastReplayTick; + private long lastTickTimeNanos; + + public float getPartialReplayTick() { + int lastReplayTick = this.lastReplayTick; + if (this.replayPaused || this.isPaused()) { + return lastReplayTick; + } else { + long currentNanos = Util.getNanos(); + long nanosPerTick = this.tickRateManager().nanosecondsPerTick(); + + double partial = (currentNanos - this.lastTickTimeNanos) / (double) nanosPerTick; + partial = Math.max(0, Math.min(1, partial)); + + return lastReplayTick + (float) partial; + } + } + + public int getTotalReplayTicks() { + return this.totalTicks; + } + + public boolean doClientRendering() { + return !this.isProcessingSnapshot && !this.processedSnapshot; + } + + public void updateBossBar(ClientboundBossEventPacket packet) { + packet.dispatch(new ClientboundBossEventPacket.Handler() { + @Override + public void add(UUID uuid, Component component, float progress, BossEvent.BossBarColor bossBarColor, BossEvent.BossBarOverlay bossBarOverlay, boolean darkenScreen, boolean playBossMusic, boolean createWorldFog) { + BossEvent old = bossEvents.remove(uuid); + BossEvent newEvent = new BossEvent(uuid, component, bossBarColor, bossBarOverlay) {}; + newEvent.setProgress(progress); + newEvent.setDarkenScreen(darkenScreen); + newEvent.setPlayBossMusic(playBossMusic); + newEvent.setCreateWorldFog(createWorldFog); + if (old != null) { + if (old.getProgress() != progress) { + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdateProgressPacket(newEvent)); + } + if (!old.getName().equals(component)) { + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdateNamePacket(newEvent)); + } + if (!old.getColor().equals(bossBarColor) || !old.getOverlay().equals(bossBarOverlay)) { + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdateStylePacket(newEvent)); + } + if (old.shouldDarkenScreen() != darkenScreen || old.shouldPlayBossMusic() != playBossMusic || old.shouldCreateWorldFog() != createWorldFog) { + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdatePropertiesPacket(newEvent)); + } + } else { + getPlayerList().broadcastAll(ClientboundBossEventPacket.createAddPacket(newEvent)); + } + bossEvents.put(uuid, newEvent); + } + + @Override + public void remove(UUID uuid) { + if (bossEvents.remove(uuid) != null) { + getPlayerList().broadcastAll(ClientboundBossEventPacket.createRemovePacket(uuid)); + } + } + + @Override + public void updateProgress(UUID uuid, float progress) { + BossEvent current = bossEvents.get(uuid); + if (current != null) { + current.setProgress(progress); + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdateProgressPacket(current)); + } + } + + @Override + public void updateName(UUID uuid, Component component) { + BossEvent current = bossEvents.get(uuid); + if (current != null) { + current.setName(component); + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdateNamePacket(current)); + } + } + + @Override + public void updateStyle(UUID uuid, BossEvent.BossBarColor bossBarColor, BossEvent.BossBarOverlay bossBarOverlay) { + BossEvent current = bossEvents.get(uuid); + if (current != null) { + current.setColor(bossBarColor); + current.setOverlay(bossBarOverlay); + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdateStylePacket(current)); + } + } + + @Override + public void updateProperties(UUID uuid, boolean darkenScreen, boolean playBossMusic, boolean createWorldFog) { + BossEvent current = bossEvents.get(uuid); + if (current != null) { + current.setDarkenScreen(darkenScreen); + current.setPlayBossMusic(playBossMusic); + current.setCreateWorldFog(createWorldFog); + getPlayerList().broadcastAll(ClientboundBossEventPacket.createUpdatePropertiesPacket(current)); + } + } + }); + } + + public Collection getReplayViewers() { + return this.replayViewers; + } + + public int getLocalPlayerId() { + return this.gamePacketHandler.localPlayerId; + } + + public void handleNextTick() { + if (this.isProcessingSnapshot) { + throw new IllegalStateException("Can't go to next tick while processing snapshot"); + } + + this.gamePacketHandler.flushPendingEntities(); + currentTick += 1; + } + + public void handleConfigurationPacket(RegistryFriendlyByteBuf friendlyByteBuf) { + Packet packet = this.configurationPacketCodec.decode(friendlyByteBuf); + this.gamePacketHandler.flushPendingEntities(); + packet.handle(this.configurationPacketHandler); + } + + public void handleGamePacket(RegistryFriendlyByteBuf friendlyByteBuf) { + this.configurationPacketHandler.flushPendingConfiguration(); + + Packet packet = this.gamePacketCodec.decode(friendlyByteBuf); + if (!AllowPendingEntityPacketSet.allowPendingEntity(packet)) { + this.gamePacketHandler.flushPendingEntities(); + } + packet.handle(this.gamePacketHandler); + } + + public void handleCreateLocalPlayer(RegistryFriendlyByteBuf friendlyByteBuf) { + this.configurationPacketHandler.flushPendingConfiguration(); + this.gamePacketHandler.flushPendingEntities(); + this.gamePacketHandler.handleCreateLocalPlayer(friendlyByteBuf); + } + + public void handleMoveEntities(RegistryFriendlyByteBuf friendlyByteBuf) { + this.gamePacketHandler.flushPendingEntities(); + this.configurationPacketHandler.flushPendingConfiguration(); + + int levelCount = friendlyByteBuf.readVarInt(); + for (int i = 0; i < levelCount; i++) { + ResourceKey dimension = friendlyByteBuf.readResourceKey(Registries.DIMENSION); + ServerLevel level = this.levels.get(dimension); + + int count = friendlyByteBuf.readVarInt(); + for (int j = 0; j < count; j++) { + int id = friendlyByteBuf.readVarInt(); + double x = friendlyByteBuf.readDouble(); + double y = friendlyByteBuf.readDouble(); + double z = friendlyByteBuf.readDouble(); + float yaw = friendlyByteBuf.readFloat(); + float pitch = friendlyByteBuf.readFloat(); + float headYaw = friendlyByteBuf.readFloat(); + boolean onGround = friendlyByteBuf.readBoolean(); + + if (level != null) { + Entity entity = level.getEntity(id); + if (entity != null) { + entity.moveTo(x, y, z, yaw, pitch); + entity.setYHeadRot(headYaw); + entity.setOnGround(onGround); + } + } + } + } + } + + public static final TicketType ENTITY_LOAD_TICKET = TicketType.create("replay_entity_load", Comparator.comparingLong(ChunkPos::toLong), 5); + + public void closeLevel(ServerLevel serverLevel) { + this.clearLevel(serverLevel); + try { + serverLevel.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void clearLevel(ServerLevel serverLevel) { + for (ServerPlayer player : new ArrayList<>(serverLevel.players())) { + if (player instanceof ReplayPlayer) { + continue; + } + player.connection.disconnect(Component.empty()); + } + List entities = new ArrayList<>(); + for (Entity entity : serverLevel.getAllEntities()) { + if (entity instanceof ReplayPlayer) { + continue; + } + entities.add(entity); + } + for (Entity entity : entities) { + if (entity != null) { + entity.discard(); + } + } + serverLevel.setDayTime(0); + } + + @Override + public boolean haveTime() { + return super.haveTime() && this.jumpToTick < 0; + } + + @Override + public void tickServer(BooleanSupplier booleanSupplier) { + this.lastReplayTick = this.currentTick; + this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick(); + + Keyframes.applyKeyframes(this, this.lastReplayTick); + + // Update list of replay viewers + this.replayViewers.clear(); + for (ServerPlayer player : this.getPlayerList().getPlayers()) { + if (player instanceof ReplayPlayer replayPlayer) { + this.replayViewers.add(replayPlayer); + } + } + + // Update resourcepacks + if (this.remotePacks.isEmpty()) { + if (!this.oldRemotePacks.isEmpty()) { + this.oldRemotePacks.clear(); + this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.empty())); + } + } else { + for (Map.Entry entry : this.remotePacks.entrySet()) { + RemotePack remotePack = entry.getValue(); + RemotePack oldRemotePack = this.oldRemotePacks.get(entry.getKey()); + if (oldRemotePack == null) { + this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash, + true, Optional.empty())); + } else if (!oldRemotePack.equals(remotePack)) { + this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.of(remotePack.id))); + this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash, + true, Optional.empty())); + } + this.oldRemotePacks.put(entry.getKey(), remotePack); + } + this.oldRemotePacks.keySet().removeIf(uuid -> { + if (!this.remotePacks.containsKey(uuid)) { + this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.of(uuid))); + return true; + } else { + return false; + } + }); + } + + int extraForceEntityLerpTicks = 0; + if (this.jumpToTick >= 0) { + this.targetTick = this.jumpToTick; + this.jumpToTick = -1; + extraForceEntityLerpTicks = Math.max(0, Math.abs(this.targetTick - this.currentTick) - 1); + } else if (!this.isPaused() && !this.replayPaused && this.targetTick < this.totalTicks) { + // Normal playback + this.targetTick += 1; + } + + // Update tick rate & frozen state + if (this.tickRateManager().tickrate() != this.desiredTickRate) { + this.tickRateManager().setTickRate(this.desiredTickRate); + } + + boolean wantFrozen = this.replayPaused && this.targetTick == this.currentTick; + if (this.tickRateManager().isFrozen() != wantFrozen) { + this.tickRateManager().setFrozen(wantFrozen); + } + + this.handleActions(); + this.tryFollowLocalPlayer(); + + if (extraForceEntityLerpTicks > 0) { + ReplayVisuals.forceEntityLerpTicks = Math.min(10, ReplayVisuals.forceEntityLerpTicks + extraForceEntityLerpTicks); + } + + // Add tickets for keeping entities loaded + for (ServerLevel level : this.getAllLevels()) { + for (Entity entity : level.getAllEntities()) { + ChunkPos chunkPos = new ChunkPos(entity.blockPosition()); + level.getChunkSource().addRegionTicket(ENTITY_LOAD_TICKET, chunkPos, 3, chunkPos); + } + } + + // Tick underlying server + super.tickServer(booleanSupplier); + + if (this.processedSnapshot) { + this.processedSnapshot = false; + + for (ReplayPlayer replayViewer : this.replayViewers) { + replayViewer.connection.chunkSender.sendNextChunks(replayViewer); + } + for (ServerLevel level : this.getAllLevels()) { + for (ServerPlayer player : level.players()) { + if (player instanceof ReplayPlayer) { + // Called twice, first one will update the chunk tracking & second one will update the entity tracking + level.getChunkSource().move(player); + level.getChunkSource().move(player); + } + } + } + + if (FlashbackClient.EXPORT_JOB == null) { + ReplayVisuals.forceEntityLerpTicks = 10; + ((MinecraftExt)Minecraft.getInstance()).flashback$forceClientTick(); + } + } + + this.finishedServerTick.set(true); + } + + private void handleActions() { + this.targetTick = Math.max(0, Math.min(this.totalTicks, this.targetTick)); + + if (this.targetTick == this.currentTick) { + return; + } + + if (this.targetTick < this.currentTick) { + this.processedSnapshot = true; + Map.Entry entry = this.playableChunksByStart.floorEntry(this.targetTick); + ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); + replayReader.handleSnapshot(this); + this.currentTick = entry.getKey(); + } + + Map.Entry entry = this.playableChunksByStart.floorEntry(this.currentTick); + if (entry == null) { + return; + } + + this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); + // todo: is this problematic if we somehow have a chunk with only 1 tick in it? + if (entry.getKey() == this.currentTick) { + this.currentReplayReader.resetToStart(); + } + + // todo: what do we do when the number of ticks in the chunk doesn't match the number of ticks we think it has + + while (this.currentTick < this.targetTick) { + if (!this.currentReplayReader.handleNextAction(this)) { + Map.Entry newEntry = this.playableChunksByStart.floorEntry(this.currentTick); + if (newEntry.getValue() == entry.getValue()) { + this.targetTick = this.currentTick; + return; + } + entry = newEntry; + + if (newEntry.getKey() != this.currentTick) { + throw new RuntimeException("didn't match?"); + } + + this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); + this.currentReplayReader.resetToStart(); + } + } + + this.currentReplayReader = null; + } + + private void tryFollowLocalPlayer() { + if (this.spawnLevel == null) { + return; + } + + ServerLevel currentLevel = this.getLevel(this.spawnLevel); + if (currentLevel == null) { + return; + } + + Entity follow = currentLevel.getEntity(this.gamePacketHandler.localPlayerId); + if (follow == null) { + return; + } + + for (ReplayPlayer replayViewer : this.getReplayViewers()) { + if (replayViewer.followLocalPlayerNextTick || this.followLocalPlayerNextTick) { + replayViewer.followLocalPlayerNextTick = false; + replayViewer.teleportTo(currentLevel, follow.getX(), follow.getY(), follow.getZ(), + follow.getYRot(), follow.getXRot()); + } + } + this.followLocalPlayerNextTick = false; + } + + @Override + public boolean saveEverything(boolean bl, boolean bl2, boolean bl3) { + return false; + } + + @Override + public boolean saveAllChunks(boolean bl, boolean bl2, boolean bl3) { + return false; + } + + @Override + public void stopServer() { + // Remove all levels + for (ServerLevel level : this.levels.values()) { + if (level == null) { + continue; + } + try { + level.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + this.levels.clear(); + + // Stop server + super.stopServer(); + this.clearReplayTempFolder(); + + Path playbackTemp = FlashbackClient.getReplayPlaybackTemp(this.playbackUUID); + try { + FileUtils.deleteDirectory(playbackTemp.toFile()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void clearReplayTempFolder() { + Path replayTemp = FlashbackClient.getReplayServerTemp(); + try { + FileUtils.deleteDirectory(replayTemp.toFile()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean isSingleplayerOwner(GameProfile gameProfile) { + return gameProfile.getName().equals("ReplayViewer"); + } +} diff --git a/src/client/java/com/moulberry/flashback/player/ReplayPlayer.java b/src/client/java/com/moulberry/flashback/player/ReplayPlayer.java new file mode 100644 index 0000000..92e9e1f --- /dev/null +++ b/src/client/java/com/moulberry/flashback/player/ReplayPlayer.java @@ -0,0 +1,30 @@ +package com.moulberry.flashback.player; + +import com.mojang.authlib.GameProfile; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ClientInformation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.stats.Stat; +import net.minecraft.world.item.crafting.RecipeHolder; + +import java.util.Collection; + +public class ReplayPlayer extends ServerPlayer { + public boolean followLocalPlayerNextTick = false; + + public ReplayPlayer(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation clientInformation) { + super(minecraftServer, serverLevel, gameProfile, clientInformation); + } + + @Override + public int awardRecipes(Collection> collection) { + return 0; + } + + @Override + public void awardStat(Stat stat, int i) { + } + + +} diff --git a/src/client/java/com/moulberry/flashback/record/Exporter.java b/src/client/java/com/moulberry/flashback/record/Exporter.java new file mode 100644 index 0000000..978b741 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/record/Exporter.java @@ -0,0 +1,116 @@ +package com.moulberry.flashback.record; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.moulberry.flashback.FlashbackClient; +import org.apache.commons.io.FileUtils; +import org.jetbrains.annotations.Nullable; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class Exporter { + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static void export(Path recordFolder, Path outputFile) { + FlashbackClient.LOGGER.info("Exporting {} to {}", recordFolder, outputFile); + + FlashbackMeta meta = tryReadMeta(recordFolder.resolve("metadata.json")); + if (meta == null) { + meta = tryReadMeta(recordFolder.resolve("metadata.json.old")); + } + if (meta == null) { + FlashbackClient.LOGGER.error("Cannot export, both metadata files are invalid"); + return; + } + + // Validate + meta.chunks.keySet().removeIf(chunkName -> { + Path chunkPath = recordFolder.resolve(chunkName); + if (!Files.exists(chunkPath)) { + FlashbackClient.LOGGER.warn("Cannot find chunk path: {}, skipping", chunkPath); + return true; + } else { + return false; + } + }); + + if (meta.chunks.isEmpty()) { + FlashbackClient.LOGGER.error("Cannot export, no chunk files exist"); + return; + } + + try { + FileOutputStream fos = new FileOutputStream(outputFile.toFile()); + ZipOutputStream zipOut = new ZipOutputStream(fos); + + // Write metadata + ZipEntry zipEntry = new ZipEntry("metadata.json"); + zipOut.putNextEntry(zipEntry); + zipOut.write(GSON.toJson(meta.toJson()).getBytes(StandardCharsets.UTF_8)); + + // Write chunks + for (String chunkName : meta.chunks.keySet()) { + Path chunkPath = recordFolder.resolve(chunkName); + byte[] chunkData = Files.readAllBytes(chunkPath); + + if (chunkData.length == 0) { + FlashbackClient.LOGGER.warn("Length of chunk data {} is zero, might be corrupted...", chunkName); + } + + zipEntry = new ZipEntry(chunkName); + zipOut.putNextEntry(zipEntry); + zipOut.write(chunkData); + } + + zipOut.close(); + fos.close(); + + // Delete record folder + try { + FileUtils.deleteDirectory(recordFolder.toFile()); + } catch (Exception e) { + FlashbackClient.LOGGER.error("Exception deleting record folder", e); + } + } catch (Exception e) { + FlashbackClient.LOGGER.error("Exception exporting replay", e); + } + } + + @Nullable + private static FlashbackMeta tryReadMeta(Path file) { + FlashbackClient.LOGGER.info("Trying to read metadata json {}", file); + + if (!Files.exists(file)) { + FlashbackClient.LOGGER.error("Metadata JSON doesn't exist!"); + return null; + } + + try { + String metaString = Files.readString(file); + if (metaString.isBlank()) { + FlashbackClient.LOGGER.error("Metadata JSON is blank"); + return null; + } + + JsonObject metaObject = GSON.fromJson(metaString, JsonObject.class); + if (metaObject.isEmpty()) { + FlashbackClient.LOGGER.error("Metadata JSON is empty"); + return null; + } + + return FlashbackMeta.fromJson(metaObject); + } catch (Exception e) { + FlashbackClient.LOGGER.error("Exception while reading metadata", e); + return null; + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/record/FlashbackChunkMeta.java b/src/client/java/com/moulberry/flashback/record/FlashbackChunkMeta.java new file mode 100644 index 0000000..f829559 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/record/FlashbackChunkMeta.java @@ -0,0 +1,26 @@ +package com.moulberry.flashback.record; + +import com.google.gson.JsonObject; +import org.jetbrains.annotations.Nullable; + +public class FlashbackChunkMeta { + public int duration = 0; + + public JsonObject toJson() { + JsonObject chunkMeta = new JsonObject(); + chunkMeta.addProperty("duration", this.duration); + return chunkMeta; + } + + @Nullable + public static FlashbackChunkMeta fromJson(JsonObject chunkMeta) { + FlashbackChunkMeta flashbackChunkMeta = new FlashbackChunkMeta(); + + if (!chunkMeta.has("duration")) { + return null; + } + flashbackChunkMeta.duration = chunkMeta.get("duration").getAsInt(); + + return flashbackChunkMeta; + } +} diff --git a/src/client/java/com/moulberry/flashback/record/FlashbackMeta.java b/src/client/java/com/moulberry/flashback/record/FlashbackMeta.java new file mode 100644 index 0000000..b5ec101 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/record/FlashbackMeta.java @@ -0,0 +1,54 @@ +package com.moulberry.flashback.record; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class FlashbackMeta { + + public String name = "Whatever"; + public LinkedHashMap chunks = new LinkedHashMap<>(); + + public JsonObject toJson() { + JsonObject meta = new JsonObject(); + meta.addProperty("name", this.name); + + JsonObject chunksJson = new JsonObject(); + for (Map.Entry entry : this.chunks.entrySet()) { + chunksJson.add(entry.getKey(), entry.getValue().toJson()); + } + meta.add("chunks", chunksJson); + + return meta; + } + + @Nullable + public static FlashbackMeta fromJson(JsonObject meta) { + FlashbackMeta flashbackMeta = new FlashbackMeta(); + + // Name + if (!meta.has("name")) { + return null; + } + flashbackMeta.name = meta.get("name").getAsString(); + + // Chunks + if (!meta.has("chunks")) { + return null; + } + JsonObject chunksJson = meta.getAsJsonObject("chunks"); + for (Map.Entry entry : chunksJson.entrySet()) { + FlashbackChunkMeta chunkMeta = FlashbackChunkMeta.fromJson(entry.getValue().getAsJsonObject()); + if (chunkMeta == null) { + return null; + } + flashbackMeta.chunks.put(entry.getKey(), chunkMeta); + } + + return flashbackMeta; + } + +} diff --git a/src/client/java/com/moulberry/flashback/record/IgnoredPacketSet.java b/src/client/java/com/moulberry/flashback/record/IgnoredPacketSet.java new file mode 100644 index 0000000..866a5be --- /dev/null +++ b/src/client/java/com/moulberry/flashback/record/IgnoredPacketSet.java @@ -0,0 +1,121 @@ +package com.moulberry.flashback.record; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; +import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; +import net.minecraft.network.protocol.common.ClientboundPingPacket; +import net.minecraft.network.protocol.common.ClientboundStoreCookiePacket; +import net.minecraft.network.protocol.common.ClientboundTransferPacket; +import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; +import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; +import net.minecraft.network.protocol.game.ClientboundAwardStatsPacket; +import net.minecraft.network.protocol.game.ClientboundBlockChangedAckPacket; +import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket; +import net.minecraft.network.protocol.game.ClientboundChunkBatchStartPacket; +import net.minecraft.network.protocol.game.ClientboundCommandSuggestionsPacket; +import net.minecraft.network.protocol.game.ClientboundCommandsPacket; +import net.minecraft.network.protocol.game.ClientboundContainerClosePacket; +import net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket; +import net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket; +import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; +import net.minecraft.network.protocol.game.ClientboundCooldownPacket; +import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket; +import net.minecraft.network.protocol.game.ClientboundDebugSamplePacket; +import net.minecraft.network.protocol.game.ClientboundDeleteChatPacket; +import net.minecraft.network.protocol.game.ClientboundForgetLevelChunkPacket; +import net.minecraft.network.protocol.game.ClientboundHorseScreenOpenPacket; +import net.minecraft.network.protocol.game.ClientboundMerchantOffersPacket; +import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; +import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; +import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket; +import net.minecraft.network.protocol.game.ClientboundOpenSignEditorPacket; +import net.minecraft.network.protocol.game.ClientboundPlaceGhostRecipePacket; +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerCombatEndPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerCombatEnterPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; +import net.minecraft.network.protocol.game.ClientboundRecipePacket; +import net.minecraft.network.protocol.game.ClientboundSelectAdvancementsTabPacket; +import net.minecraft.network.protocol.game.ClientboundSetCameraPacket; +import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ClientboundSetChunkCacheCenterPacket; +import net.minecraft.network.protocol.game.ClientboundSetChunkCacheRadiusPacket; +import net.minecraft.network.protocol.game.ClientboundSetSimulationDistancePacket; +import net.minecraft.network.protocol.game.ClientboundStartConfigurationPacket; +import net.minecraft.network.protocol.game.ClientboundTagQueryPacket; +import net.minecraft.network.protocol.game.ClientboundTickingStatePacket; +import net.minecraft.network.protocol.game.ClientboundTickingStepPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAdvancementsPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateRecipesPacket; +import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket; + +import java.util.Set; + +public class IgnoredPacketSet { + + public static boolean isIgnored(Packet packet) { + return IGNORED.contains(packet.getClass()); + } + + private static final Set> IGNORED = Set.of( + // Common + ClientboundStoreCookiePacket.class, + ClientboundCookieRequestPacket.class, + ClientboundDisconnectPacket.class, + ClientboundPingPacket.class, + ClientboundKeepAlivePacket.class, + ClientboundTransferPacket.class, + + // Configuration + ClientboundFinishConfigurationPacket.class, + + // Game + ClientboundAwardStatsPacket.class, + ClientboundRecipePacket.class, + ClientboundOpenSignEditorPacket.class, + ClientboundMoveEntityPacket.Pos.class, + ClientboundMoveEntityPacket.Rot.class, + ClientboundMoveEntityPacket.PosRot.class, + ClientboundPlayerPositionPacket.class, + ClientboundPlayerChatPacket.class, + ClientboundDeleteChatPacket.class, + ClientboundContainerClosePacket.class, + ClientboundContainerSetContentPacket.class, + ClientboundHorseScreenOpenPacket.class, + ClientboundContainerSetDataPacket.class, + ClientboundContainerSetSlotPacket.class, + ClientboundForgetLevelChunkPacket.class, + ClientboundPlayerAbilitiesPacket.class, + ClientboundSetCarriedItemPacket.class, + ClientboundTickingStatePacket.class, + ClientboundTickingStepPacket.class, + ClientboundPlayerCombatEndPacket.class, + ClientboundPlayerCombatEnterPacket.class, + ClientboundPlayerCombatKillPacket.class, + ClientboundSetCameraPacket.class, + ClientboundCooldownPacket.class, + ClientboundUpdateAdvancementsPacket.class, + ClientboundSelectAdvancementsTabPacket.class, + ClientboundPlaceGhostRecipePacket.class, + ClientboundCommandsPacket.class, + ClientboundCommandSuggestionsPacket.class, + ClientboundUpdateRecipesPacket.class, + ClientboundTagQueryPacket.class, + ClientboundOpenBookPacket.class, + ClientboundOpenScreenPacket.class, + ClientboundMerchantOffersPacket.class, + ClientboundSetChunkCacheRadiusPacket.class, + ClientboundSetSimulationDistancePacket.class, + ClientboundSetChunkCacheCenterPacket.class, + ClientboundBlockChangedAckPacket.class, + ClientboundCustomChatCompletionsPacket.class, + ClientboundStartConfigurationPacket.class, + ClientboundChunkBatchStartPacket.class, + ClientboundChunkBatchFinishedPacket.class, + ClientboundDebugSamplePacket.class, + ClientboundPongResponsePacket.class + ); + +} diff --git a/src/client/java/com/moulberry/flashback/record/Recorder.java b/src/client/java/com/moulberry/flashback/record/Recorder.java new file mode 100644 index 0000000..8cb7812 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/record/Recorder.java @@ -0,0 +1,562 @@ +package com.moulberry.flashback.record; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.mojang.datafixers.util.Pair; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.action.ActionConfigurationPacket; +import com.moulberry.flashback.action.ActionCreateLocalPlayer; +import com.moulberry.flashback.action.ActionGamePacket; +import com.moulberry.flashback.action.ActionMoveEntities; +import com.moulberry.flashback.action.ActionNextTick; +import com.moulberry.flashback.io.ReplayWriter; +import io.netty.buffer.ByteBuf; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.BossHealthOverlay; +import net.minecraft.client.gui.components.LerpingBossEvent; +import net.minecraft.client.gui.components.PlayerTabOverlay; +import net.minecraft.client.multiplayer.ClientChunkCache; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.resources.server.ServerPackManager; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.RegistrySynchronization; +import net.minecraft.nbt.NbtOps; +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.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.configuration.ClientboundRegistryDataPacket; +import net.minecraft.network.protocol.configuration.ClientboundUpdateEnabledFeaturesPacket; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.ClientboundAnimatePacket; +import net.minecraft.network.protocol.game.ClientboundBlockDestructionPacket; +import net.minecraft.network.protocol.game.ClientboundBossEventPacket; +import net.minecraft.network.protocol.game.ClientboundBundlePacket; +import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; +import net.minecraft.network.protocol.game.ClientboundLoginPacket; +import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; +import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; +import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; +import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; +import net.minecraft.network.protocol.game.ClientboundSetTimePacket; +import net.minecraft.network.protocol.game.ClientboundTabListPacket; +import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; +import net.minecraft.network.protocol.game.CommonPlayerSpawnInfo; +import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.syncher.SynchedEntityData; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.RegistryLayer; +import net.minecraft.tags.TagNetworkSerialization; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +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.item.ItemStack; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.chunk.LevelChunk; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Queue; +import java.util.Set; +import java.util.UUID; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.concurrent.locks.ReentrantLock; + +public class Recorder { + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private static final int CHUNK_LENGTH_SECONDS = 15; + + private final ReplayWriter writer; + private final StreamCodec> configurationPacketCodec; + private StreamCodec> gamePacketCodec; + + private int writtenTicksInChunk = 0; + private FlashbackMeta metadata = new FlashbackMeta(); + private final UUID recordUUID = UUID.randomUUID(); + private ReentrantLock fileDataLock = new ReentrantLock(); + + private record PacketWithPhase(Packet packet, ConnectionProtocol phase){} + private final Queue pendingPackets = new ConcurrentLinkedQueue<>(); + + private record Position(double x, double y, double z, float yaw, float pitch, float headYRot, boolean onGround) {} + private final WeakHashMap lastPositions = new WeakHashMap<>(); + + // Local player data + private final List lastPlayerEntityMeta = new ArrayList<>(); + private final Map lastPlayerEquipment = new EnumMap<>(EquipmentSlot.class); + private BlockPos lastDestroyPos = null; + private int lastDestroyProgress = -1; + private boolean wasSwinging = false; + private int lastSwingTime = -1; + + public Recorder(RegistryAccess registryAccess) { + this.writer = new ReplayWriter(registryAccess); + this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); + this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); + } + + public void setRegistryAccess(RegistryAccess registryAccess) { + this.writer.setRegistryAccess(registryAccess); + this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); + } + + public void writeInitial() { + this.writeSnapshot(); + } + + public void endTick(boolean forceSaveToDisk) { + this.flushPackets(); + + if (Minecraft.getInstance().level != null && Minecraft.getInstance().getOverlay() == null && !Minecraft.getInstance().isPaused()) { + this.writeEntityPositions(); + this.writeLocalData(); + this.writer.startAndFinishAction(ActionNextTick.INSTANCE); + this.writtenTicksInChunk += 1; + } + + if (this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || forceSaveToDisk) { + this.fileDataLock.lock(); + try { + Path replayRecordFolder = FlashbackClient.getReplayRecordTemp(recordUUID); + Files.createDirectories(replayRecordFolder); + + int chunkCount = this.metadata.chunks.size(); + String chunkName = "c" + chunkCount + ".flashback"; + + Path chunkFile = replayRecordFolder.resolve(chunkName); + Files.write(chunkFile, this.writer.popBytes()); + + Path metaFile = replayRecordFolder.resolve("metadata.json"); + if (Files.exists(metaFile)) { + Files.move(metaFile, replayRecordFolder.resolve("metadata.json.old"), StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING); + } + + var chunkMeta = new FlashbackChunkMeta(); + chunkMeta.duration = this.writtenTicksInChunk; + this.metadata.chunks.put(chunkName, chunkMeta); + Files.writeString(metaFile, GSON.toJson(this.metadata.toJson())); + + this.writtenTicksInChunk = 0; + + if (!forceSaveToDisk) { + this.writeSnapshot(); + } + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + this.fileDataLock.unlock(); + } + } + } + + public void export(Path outputFile) { + this.fileDataLock.lock(); + try { + Path replayRecordFolder = FlashbackClient.getReplayRecordTemp(this.recordUUID); + Exporter.export(replayRecordFolder, outputFile); + } finally { + this.fileDataLock.unlock(); + } + } + + public void writeLocalData() { + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) { + this.lastPlayerEntityMeta.clear(); + this.lastPlayerEquipment.clear(); + this.lastDestroyPos = null; + this.lastDestroyProgress = -1; + return; + } + + // Update entity data + SynchedEntityData.DataItem[] items = Minecraft.getInstance().player.getEntityData().itemsById; + List> changedData = new ArrayList<>(); + for (int i = 0; i < items.length; i++) { + SynchedEntityData.DataItem dataItem = items[i]; + Object value = dataItem.value().value(); + + if (i >= this.lastPlayerEntityMeta.size()) { + this.lastPlayerEntityMeta.add(i, value); + } else { + Object old = this.lastPlayerEntityMeta.get(i); + if (!Objects.equals(old, value)) { + this.lastPlayerEntityMeta.set(i, value); + changedData.add(dataItem.value()); + } + } + } + + if (!changedData.isEmpty()) { + this.writeGamePacket(new ClientboundSetEntityDataPacket(player.getId(), changedData)); + } + + // Update equipment + List> changedSlots = new ArrayList<>(); + for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) { + ItemStack itemStack = player.getItemBySlot(equipmentSlot); + + if (!this.lastPlayerEquipment.containsKey(equipmentSlot)) { + this.lastPlayerEquipment.put(equipmentSlot, itemStack.copy()); + } else if (!ItemStack.matches(this.lastPlayerEquipment.get(equipmentSlot), itemStack)) { + ItemStack copied = itemStack.copy(); + this.lastPlayerEquipment.put(equipmentSlot, copied); + changedSlots.add(Pair.of(equipmentSlot, copied)); + } + } + if (!changedSlots.isEmpty()) { + this.writeGamePacket(new ClientboundSetEquipmentPacket(player.getId(), changedSlots)); + } + + // Update breaking + MultiPlayerGameMode multiPlayerGameMode = Minecraft.getInstance().gameMode; + if (multiPlayerGameMode == null) { + this.lastDestroyPos = null; + this.lastDestroyProgress = -1; + } else { + BlockPos destroyPos = multiPlayerGameMode.destroyBlockPos.immutable(); + int destroyProgress = multiPlayerGameMode.getDestroyStage(); + + boolean changed = destroyProgress != this.lastDestroyProgress; + if (destroyProgress >= 0) { + changed |= !destroyPos.equals(this.lastDestroyPos); + } + + if (changed) { + this.writeGamePacket(new ClientboundBlockDestructionPacket(player.getId(), destroyPos, destroyProgress)); + } + + this.lastDestroyPos = destroyPos; + this.lastDestroyProgress = destroyProgress; + } + + // Update swinging + if (player.swinging && (!this.wasSwinging || this.lastSwingTime > player.swingTime)) { + int animation = player.swingingArm == InteractionHand.MAIN_HAND ? ClientboundAnimatePacket.SWING_MAIN_HAND : ClientboundAnimatePacket.SWING_OFF_HAND; + this.writeGamePacket(new ClientboundAnimatePacket(player, animation)); + } + this.lastSwingTime = player.swingTime; + this.wasSwinging = player.swinging; + + } + + public void writeEntityPositions() { + ClientLevel level = Minecraft.getInstance().level; + if (level == null) { + this.lastPositions.clear(); + return; + } + + this.writer.startAction(ActionMoveEntities.INSTANCE); + RegistryFriendlyByteBuf friendlyByteBuf = this.writer.friendlyByteBuf(); + + friendlyByteBuf.writeVarInt(1); + friendlyByteBuf.writeResourceKey(level.dimension()); + + record IdWithPosition(int id, Position position) {} + List changedPositions = new ArrayList<>(); + + for (Entity entity : level.entitiesForRendering()) { + if (entity.isPassenger()) { + continue; + } + + Position position; + if (entity instanceof LivingEntity livingEntity) { + double lerpHeadRot = livingEntity.lerpHeadSteps > 0 ? livingEntity.lerpYHeadRot : livingEntity.getYHeadRot(); + position = new Position(livingEntity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), + entity.lerpTargetYRot(), entity.lerpTargetXRot(), (float) lerpHeadRot, entity.onGround()); + } else { + position = new Position(entity.getX(), entity.getY(), entity.getZ(), + entity.getYRot(), entity.getXRot(), entity.getYHeadRot(), entity.onGround()); + } + Position lastPosition = this.lastPositions.get(entity); + + if (!Objects.equals(position, lastPosition)) { + this.lastPositions.put(entity, position); + changedPositions.add(new IdWithPosition(entity.getId(), position)); + } + } + + friendlyByteBuf.writeVarInt(changedPositions.size()); + for (IdWithPosition changedPosition : changedPositions) { + friendlyByteBuf.writeVarInt(changedPosition.id); + friendlyByteBuf.writeDouble(changedPosition.position.x); + friendlyByteBuf.writeDouble(changedPosition.position.y); + friendlyByteBuf.writeDouble(changedPosition.position.z); + friendlyByteBuf.writeFloat(changedPosition.position.yaw); + friendlyByteBuf.writeFloat(changedPosition.position.pitch); + friendlyByteBuf.writeFloat(changedPosition.position.headYRot); + friendlyByteBuf.writeBoolean(changedPosition.position.onGround); + } + + this.writer.finishAction(ActionMoveEntities.INSTANCE); + } + + public void flushPackets() { + PacketWithPhase packet; + while ((packet = this.pendingPackets.poll()) != null) { + if (packet.phase == ConnectionProtocol.PLAY) { + this.writeGamePacket((Packet) packet.packet); + if (packet.packet instanceof ClientboundLoginPacket) { + LocalPlayer localPlayer = Minecraft.getInstance().player; + if (localPlayer == null) { + throw new IllegalStateException("Local player doesn't exist?"); + } + + this.writer.startAction(ActionCreateLocalPlayer.INSTANCE); + RegistryFriendlyByteBuf registryFriendlyByteBuf = this.writer.friendlyByteBuf(); + registryFriendlyByteBuf.writeUUID(localPlayer.getUUID()); + registryFriendlyByteBuf.writeDouble(localPlayer.getX()); + registryFriendlyByteBuf.writeDouble(localPlayer.getY()); + registryFriendlyByteBuf.writeDouble(localPlayer.getZ()); + registryFriendlyByteBuf.writeFloat(localPlayer.getXRot()); + registryFriendlyByteBuf.writeFloat(localPlayer.getYRot()); + registryFriendlyByteBuf.writeFloat(localPlayer.getYHeadRot()); + registryFriendlyByteBuf.writeVec3(localPlayer.getDeltaMovement()); + + ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, localPlayer.getGameProfile()); + + registryFriendlyByteBuf.writeVarInt(Minecraft.getInstance().gameMode.getPlayerMode().getId()); + + this.writer.finishAction(ActionCreateLocalPlayer.INSTANCE); + } + } else if (packet.phase == ConnectionProtocol.CONFIGURATION) { + this.writeConfigurationPacket((Packet) packet.packet); + } else { + throw new IllegalArgumentException("Unsupported phase: " + packet.phase); + } + } + } + + public void writePacketAsync(Packet packet, ConnectionProtocol phase) { + if (packet instanceof ClientboundBundlePacket bundlePacket) { + for (Packet subPacket : bundlePacket.subPackets()) { + this.writePacketAsync(subPacket, phase); + } + return; + } + + if (IgnoredPacketSet.isIgnored(packet)) { + return; + } + + LocalPlayer localPlayer = Minecraft.getInstance().player; + if (localPlayer != null) { + int localPlayerId = localPlayer.getId(); + if (packet instanceof ClientboundSetEntityDataPacket entityDataPacket && entityDataPacket.id() == localPlayerId) { + return; + } + if (packet instanceof ClientboundSetEquipmentPacket entityEquipmentPacket && entityEquipmentPacket.getEntity() == localPlayerId) { + return; + } + } + + this.pendingPackets.add(new PacketWithPhase(packet, phase)); + } + + public void writeGamePacket(Packet packet) { + this.writer.startAction(ActionGamePacket.INSTANCE); + this.gamePacketCodec.encode(this.writer.friendlyByteBuf(), packet); + this.writer.finishAction(ActionGamePacket.INSTANCE); + } + + public void writeConfigurationPacket(Packet packet) { + this.writer.startAction(ActionConfigurationPacket.INSTANCE); + this.configurationPacketCodec.encode(this.writer.friendlyByteBuf(), packet); + this.writer.finishAction(ActionConfigurationPacket.INSTANCE); + } + + public void writeSnapshot() { + this.writer.startSnapshot(); + + ClientLevel level = Minecraft.getInstance().level; + LocalPlayer localPlayer = Minecraft.getInstance().player; + ClientPacketListener connection = Minecraft.getInstance().getConnection(); + MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode; + ClientChunkCache clientChunkCache = level.getChunkSource(); + + AtomicReferenceArray chunks = clientChunkCache.storage.chunks; + + // Configuration data + + // Enabled features + this.writeConfigurationPacket(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(level.enabledFeatures()))); + + // Registry data + RegistryOps dynamicOps = localPlayer.registryAccess().createSerializationContext(NbtOps.INSTANCE); + RegistrySynchronization.packRegistries(dynamicOps, localPlayer.registryAccess(), Set.of(), (resourceKey, list) -> { + this.writeConfigurationPacket(new ClientboundRegistryDataPacket(resourceKey, list)); + }); + + // Tags + Map>, TagNetworkSerialization.NetworkPayload> serializedTags = new HashMap<>(); + RegistryLayer.createRegistryAccess().compositeAccess().registries().forEach(entry -> { + if (entry.value().size() > 0) { + var tags = TagNetworkSerialization.serializeToNetwork(entry.value()); + if (tags.size() > 0) { + serializedTags.put(entry.key(), tags); + } + } + }); + localPlayer.registryAccess().registries().forEach(entry -> { + if (serializedTags.containsKey(entry.key())) { + return; + } + if (RegistrySynchronization.NETWORKABLE_REGISTRIES.contains(entry.key()) && entry.value().size() > 0) { + var tags = TagNetworkSerialization.serializeToNetwork(entry.value()); + if (tags.size() > 0) { + serializedTags.put(entry.key(), tags); + } + } + }); + + this.writeConfigurationPacket(new ClientboundUpdateTagsPacket(serializedTags)); + + // Resource packs + this.writeConfigurationPacket(new ClientboundResourcePackPopPacket(Optional.empty())); + for (ServerPackManager.ServerPackData pack : Minecraft.getInstance().getDownloadedPackSource().manager.packs) { + this.writeConfigurationPacket(new ClientboundResourcePackPushPacket(pack.id, pack.url.toString(), pack.hash == null ? "" : pack.hash.toString(), + true, Optional.empty())); + } + + // Login packet + CommonPlayerSpawnInfo commonPlayerSpawnInfo = new CommonPlayerSpawnInfo(level.dimensionTypeRegistration(), level.dimension(), 0, + gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), false, Optional.empty(), 0); + var loginPacket = new ClientboundLoginPacket(localPlayer.getId(), level.getLevelData().isHardcore(), connection.levels(), + 1, Minecraft.getInstance().options.getEffectiveRenderDistance(), level.getServerSimulationDistance(), + localPlayer.isReducedDebugInfo(), localPlayer.shouldShowDeathScreen(), localPlayer.getDoLimitedCrafting(), commonPlayerSpawnInfo, false); + this.writeGamePacket(loginPacket); + + // Create player info update packet + var infoUpdatePacket = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, + ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LISTED, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), List.of()); + infoUpdatePacket.entries = new ArrayList<>(level.players().size()); + Set addedEntries = new HashSet<>(); + for (AbstractClientPlayer player : level.players()) { + if (addedEntries.add(player.getUUID())) { + PlayerInfo info = connection.getPlayerInfo(player.getUUID()); + if (info != null) { + infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), + player.getGameProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), null)); + } else { + infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), + player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), null)); + } + } + } + for (PlayerInfo info : connection.getListedOnlinePlayers()) { + if (addedEntries.add(info.getProfile().getId())) { + infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(info.getProfile().getId(), + info.getProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), null)); + } + } + this.writeGamePacket(infoUpdatePacket); + + // Tab list + PlayerTabOverlay playerTabOverlay = Minecraft.getInstance().gui.getTabList(); + this.writeGamePacket(new ClientboundTabListPacket( + playerTabOverlay.header != null ? playerTabOverlay.header : Component.empty(), + playerTabOverlay.footer != null ? playerTabOverlay.footer : Component.empty() + )); + + // Boss bar + BossHealthOverlay bossOverlay = Minecraft.getInstance().gui.getBossOverlay(); + for (LerpingBossEvent event : bossOverlay.events.values()) { + this.writeGamePacket(ClientboundBossEventPacket.createAddPacket(event)); + } + + // Time + this.writeGamePacket(new ClientboundSetTimePacket(level.getGameTime(), level.getDayTime(), level.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); + + // Chunk data + for (int i = 0; i < chunks.length(); i++) { + LevelChunk chunk = chunks.get(i); + if (chunk != null) { + this.writeGamePacket(new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), null, null)); + } + } + + // Entity data + for (Entity entity : level.entitiesForRendering()) { + this.writeGamePacket(new ClientboundAddEntityPacket(entity)); + + List> nonDefaultEntityData = entity.getEntityData().getNonDefaultValues(); + if (nonDefaultEntityData != null && !nonDefaultEntityData.isEmpty()) { + this.writeGamePacket(new ClientboundSetEntityDataPacket(entity.getId(), nonDefaultEntityData)); + } + + if (entity instanceof LivingEntity livingEntity) { + Collection syncableAttributes = livingEntity.getAttributes().getSyncableAttributes(); + if (!syncableAttributes.isEmpty()) { + this.writeGamePacket(new ClientboundUpdateAttributesPacket(entity.getId(), syncableAttributes)); + } + + List> changedSlots = new ArrayList<>(); + for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) { + ItemStack itemStack = livingEntity.getItemBySlot(equipmentSlot); + if (!itemStack.isEmpty()) { + changedSlots.add(Pair.of(equipmentSlot, itemStack.copy())); + } + } + if (!changedSlots.isEmpty()) { + this.writeGamePacket(new ClientboundSetEquipmentPacket(entity.getId(), changedSlots)); + } + } + + if (entity.isVehicle()) { + this.writeGamePacket(new ClientboundSetPassengersPacket(entity)); + } + if (entity.isPassenger()) { + this.writeGamePacket(new ClientboundSetPassengersPacket(entity.getVehicle())); + } + + if (entity instanceof Mob mob && mob.isLeashed()) { + this.writeGamePacket(new ClientboundSetEntityLinkPacket(mob, mob.getLeashHolder())); + } + } + + this.writer.endSnapshot(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/registry/RegistryHelper.java b/src/client/java/com/moulberry/flashback/registry/RegistryHelper.java new file mode 100644 index 0000000..bb2e570 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/registry/RegistryHelper.java @@ -0,0 +1,109 @@ +package com.moulberry.flashback.registry; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.JsonOps; +import net.minecraft.client.multiplayer.ClientRegistryLayer; +import net.minecraft.core.LayeredRegistryAccess; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.RegistryOps; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; + +public class RegistryHelper { + + // Checks if all the given registries in one match two + public static boolean equals(RegistryAccess one, RegistryAccess two, List> registries) { + List> listOne = new ArrayList<>(); + List> listTwo = new ArrayList<>(); + + // Check counts first, as a fast path + for (RegistryDataLoader.RegistryData registryData : registries) { + Optional> registryOne = one.registry(registryData.key()); + Optional> registryTwo = two.registry(registryData.key()); + + if (registryOne.isEmpty() || registryTwo.isEmpty()) { + if (registryOne.isEmpty() && registryTwo.isEmpty()) { + continue; + } else { + return false; + } + } + + if (registryOne.get().size() != registryTwo.get().size()) { + return false; + } + + listOne.add(registryOne.get()); + listTwo.add(registryTwo.get()); + } + + class FrozenAccess extends RegistryAccess.ImmutableRegistryAccess implements RegistryAccess.Frozen { + public FrozenAccess(List> list) { + super(list); + } + } + + LayeredRegistryAccess layeredOne = ClientRegistryLayer.createRegistryAccess().replaceFrom(ClientRegistryLayer.REMOTE, new FrozenAccess(listOne)); + LayeredRegistryAccess layeredTwo = ClientRegistryLayer.createRegistryAccess().replaceFrom(ClientRegistryLayer.REMOTE, new FrozenAccess(listTwo)); + + RegistryOps dynamicOpsOne = RegistryOps.create(JsonOps.INSTANCE, layeredOne.compositeAccess()); + RegistryOps dynamicOpsTwo = RegistryOps.create(JsonOps.INSTANCE, layeredTwo.compositeAccess()); + + // Check if all objects match + for (RegistryDataLoader.RegistryData registryData : registries) { + if (!equalsAssumeSameSize(layeredOne.compositeAccess(), layeredTwo.compositeAccess(), dynamicOpsOne, dynamicOpsTwo, registryData)) { + return false; + } + } + + return true; + } + + private static boolean equalsAssumeSameSize(RegistryAccess one, RegistryAccess two, RegistryOps dynamicOpsOne, RegistryOps dynamicOpsTwo, + RegistryDataLoader.RegistryData registryData) { + Optional> registryOne = one.registry(registryData.key()); + Optional> registryTwo = two.registry(registryData.key()); + + if (registryOne.isEmpty() || registryTwo.isEmpty()) { + return true; + } + + Iterator iteratorOne = registryOne.get().iterator(); + Iterator iteratorTwo = registryTwo.get().iterator(); + + while (iteratorOne.hasNext()) { + T valueOne = iteratorOne.next(); + T valueTwo = iteratorTwo.next(); + + if (!equalsUsingCodec(valueOne, valueTwo, dynamicOpsOne, dynamicOpsTwo, registryData.elementCodec())) { + return false; + } + } + + return true; + } + + private static boolean equalsUsingCodec(T one, T two, RegistryOps dynamicOpsOne, RegistryOps dynamicOpsTwo, Codec codec) { + if (one.equals(two)) { + return true; + } + + var resultOne = codec.encodeStart(dynamicOpsOne, one); + if (resultOne.isError()) { + return false; + } + + var resultTwo = codec.encodeStart(dynamicOpsTwo, two); + if (resultTwo.isError()) { + return false; + } + + return resultOne.getOrThrow().equals(resultTwo.getOrThrow()); + } + +} diff --git a/src/client/java/com/moulberry/flashback/spline/CatmullRom.java b/src/client/java/com/moulberry/flashback/spline/CatmullRom.java new file mode 100644 index 0000000..cee394d --- /dev/null +++ b/src/client/java/com/moulberry/flashback/spline/CatmullRom.java @@ -0,0 +1,265 @@ +package com.moulberry.flashback.spline; + +import com.moulberry.flashback.Interpolation; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +public class CatmullRom { + + private static float positionCentripetalTj(Vector3f p1, Vector3f p2) { + float dx = p2.x - p1.x; + float dy = p2.y - p1.y; + float dz = p2.z - p1.z; + return (float) Math.pow(dx*dx + dy*dy + dz*dz, 0.25f); + } + + public static Vector3f position(Vector3f p0, Vector3f p1, Vector3f p2, Vector3f p3, float time1, float time2, float time3, float amount) { + float tj1 = positionCentripetalTj(p0, p1); + float tj2 = positionCentripetalTj(p1, p2); + float tj3 = positionCentripetalTj(p2, p3); + float averageTj = (tj1 + tj2 + tj3) / 3f; + float averageTime = time3 / 3f; + float relation = averageTime / averageTj; + + float deltaTime1 = 0.0f; + if (time1 > 0.0f) { + float factor1 = (tj1 * relation) / time1; + factor1 = Math.max(0.4f, Math.min(2.5f, factor1)); + deltaTime1 = (tj1 * relation) / factor1; + } + + float deltaTime2 = 0.0f; + if (time2 - time1 > 0.0f) { + float factor2 = (tj2 * relation) / (time2 - time1); + factor2 = Math.max(0.4f, Math.min(2.5f, factor2)); + deltaTime2 = (tj2 * relation) / factor2; + } + + float deltaTime3 = 0.0f; + if (time3 - time2 > 0.0f) { + float factor3 = (tj3 * relation) / (time3 - time2); + factor3 = Math.max(0.4f, Math.min(2.5f, factor3)); + deltaTime3 = (tj3 * relation) / factor3; + } + + float t0 = 0; + float t1 = t0 + deltaTime1; + float t2 = t1 + deltaTime2; + float t3 = t2 + deltaTime3; + + float t = t1 + (t2 - t1) * amount; + + Vector3f a1; + if (t0 == t1) { + a1 = p0.lerp(p1, 0.5f, new Vector3f()); + } else { + a1 = p0.lerp(p1, (t - t0)/(t1 - t0), new Vector3f()); + } + + Vector3f a2; + if (t1 == t2) { + a2 = p1.lerp(p2, 0.5f, new Vector3f()); + } else { + a2 = p1.lerp(p2, (t - t1)/(t2 - t1), new Vector3f()); + } + + Vector3f a3; + if (t2 == t3) { + a3 = p2.lerp(p3, 0.5f, new Vector3f()); + } else { + a3 = p2.lerp(p3, (t - t2)/(t3 - t2), new Vector3f()); + } + + Vector3f b1; + if (t0 == t2) { + b1 = a1.lerp(a2, 0.5f, new Vector3f()); + } else { + b1 = a1.lerp(a2, (t - t0)/(t2 - t0), new Vector3f()); + } + + Vector3f b2; + if (t1 == t3) { + b2 = a2.lerp(a3, 0.5f, new Vector3f()); + } else { + b2 = a2.lerp(a3, (t - t1)/(t3 - t1), new Vector3f()); + } + + if (t1 == t2) { + return b1.lerp(b2, 0.5f, new Vector3f()); + } else { + return b1.lerp(b2, (t - t1)/(t2 - t1), new Vector3f()); + } + } + + private static float rotationCentripetalTj(Quaternionf p1, Quaternionf p2) { + Quaternionf delta = p1.invert(new Quaternionf()).mul(p2); + + float lengthSq = delta.x*delta.x + delta.y*delta.y + delta.z*delta.z; + float length = (float) Math.sqrt(lengthSq); + + float angleBetween = (float) Math.abs(2 * Math.atan2(length, delta.w)); + angleBetween = (float) Math.max(0, Math.min(Math.PI, angleBetween)); + return (float) Math.pow(angleBetween, 0.5f); + } + + public static Quaternionf rotation(Quaternionf p0, Quaternionf p1, Quaternionf p2, Quaternionf p3, float time1, float time2, float time3, float amount) { + float tj1 = rotationCentripetalTj(p0, p1); + float tj2 = rotationCentripetalTj(p1, p2); + float tj3 = rotationCentripetalTj(p2, p3); + float averageTj = (tj1 + tj2 + tj3) / 3f; + float averageTime = time3 / 3f; + float relation = averageTime / averageTj; + + float deltaTime1 = 0.0f; + if (time1 > 0.0f) { + float factor1 = (tj1 * relation) / time1; + factor1 = Math.max(0.4f, Math.min(2.5f, factor1)); + deltaTime1 = (tj1 * relation) / factor1; + } + + float deltaTime2 = 0.0f; + if (time2 - time1 > 0.0f) { + float factor2 = (tj2 * relation) / (time2 - time1); + factor2 = Math.max(0.4f, Math.min(2.5f, factor2)); + deltaTime2 = (tj2 * relation) / factor2; + } + + float deltaTime3 = 0.0f; + if (time3 - time2 > 0.0f) { + float factor3 = (tj3 * relation) / (time3 - time2); + factor3 = Math.max(0.4f, Math.min(2.5f, factor3)); + deltaTime3 = (tj3 * relation) / factor3; + } + + float t0 = 0; + float t1 = t0 + deltaTime1; + float t2 = t1 + deltaTime2; + float t3 = t2 + deltaTime3; + + float t = t1 + (t2 - t1) * amount; + + Quaternionf a1; + if (t0 == t1) { + a1 = p0.nlerp(p1, 0.5f, new Quaternionf()).normalize(); + } else { + a1 = p0.nlerp(p1, (t - t0)/(t1 - t0), new Quaternionf()).normalize(); + } + + Quaternionf a2; + if (t1 == t2) { + a2 = p1.nlerp(p2, 0.5f, new Quaternionf()).normalize(); + } else { + a2 = p1.nlerp(p2, (t - t1)/(t2 - t1), new Quaternionf()).normalize(); + } + + Quaternionf a3; + if (t2 == t3) { + a3 = p2.nlerp(p3, 0.5f, new Quaternionf()).normalize(); + } else { + a3 = p2.nlerp(p3, (t - t2)/(t3 - t2), new Quaternionf()).normalize(); + } + + Quaternionf b1; + if (t0 == t2) { + b1 = a1.nlerp(a2, 0.5f, new Quaternionf()).normalize(); + } else { + b1 = a1.nlerp(a2, (t - t0)/(t2 - t0), new Quaternionf()).normalize(); + } + + Quaternionf b2; + if (t1 == t3) { + b2 = a2.nlerp(a3, 0.5f, new Quaternionf()).normalize(); + } else { + b2 = a2.nlerp(a3, (t - t1)/(t3 - t1), new Quaternionf()).normalize(); + } + + if (t1 == t2) { + return b1.nlerp(b2, 0.5f, new Quaternionf()).normalize(); + } else { + return b1.nlerp(b2, (t - t1)/(t2 - t1), new Quaternionf()).normalize(); + } + } + + private static float valueCentripetalTj(float p1, float p2) { + return (float) Math.sqrt(Math.abs(p1 - p2)); + } + + public static float value(float p0, float p1, float p2, float p3, float time1, float time2, float time3, float amount) { + float tj1 = valueCentripetalTj(p0, p1); + float tj2 = valueCentripetalTj(p1, p2); + float tj3 = valueCentripetalTj(p2, p3); + float averageTj = (tj1 + tj2 + tj3) / 3f; + float averageTime = time3 / 3f; + float relation = averageTime / averageTj; + + float deltaTime1 = 0.0f; + if (time1 > 0.0f) { + float factor1 = (tj1 * relation) / time1; + factor1 = Math.max(0.4f, Math.min(2.5f, factor1)); + deltaTime1 = (tj1 * relation) / factor1; + } + + float deltaTime2 = 0.0f; + if (time2 - time1 > 0.0f) { + float factor2 = (tj2 * relation) / (time2 - time1); + factor2 = Math.max(0.4f, Math.min(2.5f, factor2)); + deltaTime2 = (tj2 * relation) / factor2; + } + + float deltaTime3 = 0.0f; + if (time3 - time2 > 0.0f) { + float factor3 = (tj3 * relation) / (time3 - time2); + factor3 = Math.max(0.4f, Math.min(2.5f, factor3)); + deltaTime3 = (tj3 * relation) / factor3; + } + + float t0 = 0; + float t1 = t0 + deltaTime1; + float t2 = t1 + deltaTime2; + float t3 = t2 + deltaTime3; + + float t = t1 + (t2 - t1) * amount; + + float a1; + if (t0 == t1) { + a1 = Interpolation.linear(p0, p1, 0.5f); + } else { + a1 = Interpolation.linear(p0, p1, (t - t0)/(t1 - t0)); + } + + float a2; + if (t1 == t2) { + a2 = Interpolation.linear(p1, p2, 0.5f); + } else { + a2 = Interpolation.linear(p1, p2, (t - t1)/(t2 - t1)); + } + + float a3; + if (t2 == t3) { + a3 = Interpolation.linear(p2, p3, 0.5f); + } else { + a3 = Interpolation.linear(p2, p3, (t - t2)/(t3 - t2)); + } + + float b1; + if (t0 == t2) { + b1 = Interpolation.linear(a1, a2, 0.5f); + } else { + b1 = Interpolation.linear(a1, a2, (t - t0)/(t2 - t0)); + } + + float b2; + if (t1 == t3) { + b2 = Interpolation.linear(a2, a3, 0.5f); + } else { + b2 =Interpolation.linear(a2, a3, (t - t1)/(t3 - t1)); + } + + if (t1 == t2) { + return Interpolation.linear(b1, b2, 0.5f); + } else { + return Interpolation.linear(b1, b2, (t - t1)/(t2 - t1)); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGl3.java b/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGl3.java new file mode 100644 index 0000000..0a34b83 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGl3.java @@ -0,0 +1,592 @@ +package com.moulberry.flashback.ui; + +import imgui.ImDrawData; +import imgui.ImFontAtlas; +import imgui.ImGui; +import imgui.ImGuiIO; +import imgui.ImGuiViewport; +import imgui.ImVec2; +import imgui.ImVec4; +import imgui.callback.ImPlatformFuncViewport; +import imgui.flag.ImGuiBackendFlags; +import imgui.flag.ImGuiConfigFlags; +import imgui.flag.ImGuiViewportFlags; +import imgui.type.ImInt; + +import java.nio.ByteBuffer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.lwjgl.opengl.GL32.*; + +/** + * This class is a straightforward port of the + * imgui_impl_opengl3.cpp. + *

+ * It do support a backup and restoring of the GL state in the same way the original Dear ImGui code does. + * Some of the very specific OpenGL variables may be ignored here, + * yet you can copy-paste this class in your codebase and modify the rendering routine in the way you'd like. + *

+ * This implementation has an ability to use a GLSL version provided during the initialization. + * Please read the documentation for the {@link #init(String)}. + */ +@SuppressWarnings("MagicNumber") +public final class CustomImGuiImplGl3 { + // OpenGL Data + private int glVersion = 0; + private String glslVersion = ""; + private int gFontTexture = -1; + private int gShaderHandle = 0; + private int gVertHandle = 0; + private int gFragHandle = 0; + private int gAttribLocationTex = 0; + private int gAttribLocationProjMtx = 0; + private int gAttribLocationVtxPos = 0; + private int gAttribLocationVtxUV = 0; + private int gAttribLocationVtxColor = 0; + private int gVboHandle = 0; + private int gElementsHandle = 0; + private int gVertexArrayObjectHandle = 0; + + // Used to store tmp renderer data + private final ImVec2 displaySize = new ImVec2(); + private final ImVec2 framebufferScale = new ImVec2(); + private final ImVec2 displayPos = new ImVec2(); + private final ImVec4 clipRect = new ImVec4(); + private final float[] orthoProjMatrix = new float[4 * 4]; + + // Variables used to backup GL state before and after the rendering of Dear ImGui + private final int[] lastActiveTexture = new int[1]; + private final int[] lastProgram = new int[1]; + private final int[] lastTexture = new int[1]; + private final int[] lastArrayBuffer = new int[1]; + private final int[] lastVertexArrayObject = new int[1]; + private final int[] lastFramebuffer = new int[1]; + private final int[] lastViewport = new int[4]; + private final int[] lastScissorBox = new int[4]; + private final int[] lastBlendSrcRgb = new int[1]; + private final int[] lastBlendDstRgb = new int[1]; + private final int[] lastBlendSrcAlpha = new int[1]; + private final int[] lastBlendDstAlpha = new int[1]; + private final int[] lastBlendEquationRgb = new int[1]; + private final int[] lastBlendEquationAlpha = new int[1]; + private boolean lastEnableBlend = false; + private boolean lastEnableCullFace = false; + private boolean lastEnableDepthTest = false; + private boolean lastEnableStencilTest = false; + private boolean lastEnableScissorTest = false; + + /** + * Method to do an initialization of the {@link CustomImGuiImplGl3} state. + * It SHOULD be called before calling of the {@link CustomImGuiImplGl3#renderDrawData(ImDrawData)} method. + *

+ * Unlike in the {@link #init(String)} method, here the glslVersion argument is omitted. + * Thus a "#version 130" string will be used instead. + */ + public void init() { + this.init(null); + } + + /** + * Method to do an initialization of the {@link CustomImGuiImplGl3} state. + * It SHOULD be called before calling of the {@link CustomImGuiImplGl3#renderDrawData(ImDrawData)} method. + *

+ * Method takes an argument, which should be a valid GLSL string with the version to use. + *

+     * ----------------------------------------
+     * OpenGL    GLSL      GLSL
+     * version   version   string
+     * ---------------------------------------
+     *  2.0       110       "#version 110"
+     *  2.1       120       "#version 120"
+     *  3.0       130       "#version 130"
+     *  3.1       140       "#version 140"
+     *  3.2       150       "#version 150"
+     *  3.3       330       "#version 330 core"
+     *  4.0       400       "#version 400 core"
+     *  4.1       410       "#version 410 core"
+     *  4.2       420       "#version 410 core"
+     *  4.3       430       "#version 430 core"
+     *  ES 3.0    300       "#version 300 es"   = WebGL 2.0
+     * ---------------------------------------
+     * 
+ *

+ * If the argument is null, then a "#version 130" string will be used by default. + * + * @param glslVersion string with the version of the GLSL + */ + public void init(final String glslVersion) { + this.readGlVersion(); + this.setupBackendCapabilitiesFlags(); + + if (glslVersion == null) { + this.glslVersion = "#version 130"; + } else { + this.glslVersion = glslVersion; + } + + this.createDeviceObjects(); + + if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { + this.initPlatformInterface(); + } + } + + /** + * Method to render {@link ImDrawData} into current OpenGL context. + * + * @param drawData draw data to render + */ + public void renderDrawData(final ImDrawData drawData) { + if (drawData.getCmdListsCount() <= 0) { + return; + } + + // Will project scissor/clipping rectangles into framebuffer space + drawData.getDisplaySize(this.displaySize); // (0,0) unless using multi-viewports + drawData.getDisplayPos(this.displayPos); + drawData.getFramebufferScale(this.framebufferScale); // (1,1) unless using retina display which are often (2,2) + + final float clipOffX = this.displayPos.x; + final float clipOffY = this.displayPos.y; + final float clipScaleX = this.framebufferScale.x; + final float clipScaleY = this.framebufferScale.y; + + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + final int fbWidth = (int) (this.displaySize.x * this.framebufferScale.x); + final int fbHeight = (int) (this.displaySize.y * this.framebufferScale.y); + + if (fbWidth <= 0 || fbHeight <= 0) { + return; + } + + this.backupGlState(); + this.bind(fbWidth, fbHeight); + + // Render command lists + for (int cmdListIdx = 0; cmdListIdx < drawData.getCmdListsCount(); cmdListIdx++) { + // Upload vertex/index buffers + glBufferData(GL_ARRAY_BUFFER, drawData.getCmdListVtxBufferData(cmdListIdx), GL_STREAM_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, drawData.getCmdListIdxBufferData(cmdListIdx), GL_STREAM_DRAW); + + for (int cmdBufferIdx = 0; cmdBufferIdx < drawData.getCmdListCmdBufferSize(cmdListIdx); cmdBufferIdx++) { + drawData.getCmdListCmdBufferClipRect(cmdListIdx, cmdBufferIdx, this.clipRect); + + final float clipMinX = (this.clipRect.x - clipOffX) * clipScaleX; + final float clipMinY = (this.clipRect.y - clipOffY) * clipScaleY; + final float clipMaxX = (this.clipRect.z - clipOffX) * clipScaleX; + final float clipMaxY = (this.clipRect.w - clipOffY) * clipScaleY; + + if (clipMaxX <= clipMinX || clipMaxY <= clipMinY) { + continue; + } + + // Apply scissor/clipping rectangle (Y is inverted in OpenGL) + glScissor((int) clipMinX, (int) (fbHeight - clipMaxY), (int) (clipMaxX - clipMinX), (int) (clipMaxY - clipMinY)); + + // Bind texture, Draw + final int textureId = drawData.getCmdListCmdBufferTextureId(cmdListIdx, cmdBufferIdx); + final int elemCount = drawData.getCmdListCmdBufferElemCount(cmdListIdx, cmdBufferIdx); + final int idxBufferOffset = drawData.getCmdListCmdBufferIdxOffset(cmdListIdx, cmdBufferIdx); + final int vtxBufferOffset = drawData.getCmdListCmdBufferVtxOffset(cmdListIdx, cmdBufferIdx); + final int indices = idxBufferOffset * ImDrawData.SIZEOF_IM_DRAW_IDX; + + glBindTexture(GL_TEXTURE_2D, textureId); + + if (this.glVersion >= 320) { + glDrawElementsBaseVertex(GL_TRIANGLES, elemCount, GL_UNSIGNED_SHORT, indices, vtxBufferOffset); + } else { + glDrawElements(GL_TRIANGLES, elemCount, GL_UNSIGNED_SHORT, indices); + } + } + } + + this.unbind(); + this.restoreModifiedGlState(); + } + + /** + * Call this method in the end of your application cycle to dispose resources used by {@link CustomImGuiImplGl3}. + */ + public void dispose() { + glDeleteBuffers(this.gVboHandle); + glDeleteBuffers(this.gElementsHandle); + glDetachShader(this.gShaderHandle, this.gVertHandle); + glDetachShader(this.gShaderHandle, this.gFragHandle); + glDeleteProgram(this.gShaderHandle); + glDeleteTextures(this.gFontTexture); + this.shutdownPlatformInterface(); + } + + /** + * Method rebuilds the font atlas for Dear ImGui. Could be used to update application fonts in runtime. + */ + public void updateFontsTexture() { + if (this.gFontTexture != -1) glDeleteTextures(this.gFontTexture); + + final ImFontAtlas fontAtlas = ImGui.getIO().getFonts(); + final ImInt width = new ImInt(); + final ImInt height = new ImInt(); + final ByteBuffer buffer = fontAtlas.getTexDataAsRGBA32(width, height); + + this.gFontTexture = glGenTextures(); + + glBindTexture(GL_TEXTURE_2D, this.gFontTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); + glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width.get(), height.get(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); + + fontAtlas.setTexID(this.gFontTexture); + } + + private void readGlVersion() { + final int[] major = new int[1]; + final int[] minor = new int[1]; + glGetIntegerv(GL_MAJOR_VERSION, major); + glGetIntegerv(GL_MINOR_VERSION, minor); + this.glVersion = major[0] * 100 + minor[0] * 10; + } + + private void setupBackendCapabilitiesFlags() { + final ImGuiIO io = ImGui.getIO(); + io.setBackendRendererName("imgui_java_impl_opengl3"); + + // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + if (this.glVersion >= 320) { + io.addBackendFlags(ImGuiBackendFlags.RendererHasVtxOffset); + } + + // We can create multi-viewports on the Renderer side (optional) + io.addBackendFlags(ImGuiBackendFlags.RendererHasViewports); + } + + private void createDeviceObjects() { + // Backup GL state + final int[] lastTexture = new int[1]; + final int[] lastArrayBuffer = new int[1]; + final int[] lastVertexArray = new int[1]; + glGetIntegerv(GL_TEXTURE_BINDING_2D, lastTexture); + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, lastArrayBuffer); + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, lastVertexArray); + + this.createShaders(); + + this.gAttribLocationTex = glGetUniformLocation(this.gShaderHandle, "Texture"); + this.gAttribLocationProjMtx = glGetUniformLocation(this.gShaderHandle, "ProjMtx"); + this.gAttribLocationVtxPos = glGetAttribLocation(this.gShaderHandle, "Position"); + this.gAttribLocationVtxUV = glGetAttribLocation(this.gShaderHandle, "UV"); + this.gAttribLocationVtxColor = glGetAttribLocation(this.gShaderHandle, "Color"); + + // Create buffers + this.gVboHandle = glGenBuffers(); + this.gElementsHandle = glGenBuffers(); + + this.updateFontsTexture(); + + // Restore modified GL state + glBindTexture(GL_TEXTURE_2D, lastTexture[0]); + glBindBuffer(GL_ARRAY_BUFFER, lastArrayBuffer[0]); + glBindVertexArray(lastVertexArray[0]); + } + + private void createShaders() { + final int glslVersionValue = this.parseGlslVersionString(); + + // Select shaders matching our GLSL versions + final CharSequence vertShaderSource; + final CharSequence fragShaderSource; + + if (glslVersionValue < 130) { + vertShaderSource = this.getVertexShaderGlsl120(); + fragShaderSource = this.getFragmentShaderGlsl120(); + } else if (glslVersionValue == 300) { + vertShaderSource = this.getVertexShaderGlsl300es(); + fragShaderSource = this.getFragmentShaderGlsl300es(); + } else if (glslVersionValue >= 410) { + vertShaderSource = this.getVertexShaderGlsl410Core(); + fragShaderSource = this.getFragmentShaderGlsl410Core(); + } else { + vertShaderSource = this.getVertexShaderGlsl130(); + fragShaderSource = this.getFragmentShaderGlsl130(); + } + + this.gVertHandle = this.createAndCompileShader(GL_VERTEX_SHADER, vertShaderSource); + this.gFragHandle = this.createAndCompileShader(GL_FRAGMENT_SHADER, fragShaderSource); + + this.gShaderHandle = glCreateProgram(); + glAttachShader(this.gShaderHandle, this.gVertHandle); + glAttachShader(this.gShaderHandle, this.gFragHandle); + glLinkProgram(this.gShaderHandle); + + if (glGetProgrami(this.gShaderHandle, GL_LINK_STATUS) == GL_FALSE) { + throw new IllegalStateException("Failed to link shader program:\n" + glGetProgramInfoLog(this.gShaderHandle)); + } + } + + private int parseGlslVersionString() { + final Pattern p = Pattern.compile("\\d+"); + final Matcher m = p.matcher(this.glslVersion); + + if (m.find()) { + return Integer.parseInt(m.group()); + } else { + throw new IllegalArgumentException("Invalid GLSL version string: " + this.glslVersion); + } + } + + private void backupGlState() { + glGetIntegerv(GL_ACTIVE_TEXTURE, this.lastActiveTexture); + glActiveTexture(GL_TEXTURE0); + glGetIntegerv(GL_CURRENT_PROGRAM, this.lastProgram); + glGetIntegerv(GL_TEXTURE_BINDING_2D, this.lastTexture); + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, this.lastArrayBuffer); + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, this.lastVertexArrayObject); + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, this.lastFramebuffer); + glGetIntegerv(GL_VIEWPORT, this.lastViewport); + glGetIntegerv(GL_SCISSOR_BOX, this.lastScissorBox); + glGetIntegerv(GL_BLEND_SRC_RGB, this.lastBlendSrcRgb); + glGetIntegerv(GL_BLEND_DST_RGB, this.lastBlendDstRgb); + glGetIntegerv(GL_BLEND_SRC_ALPHA, this.lastBlendSrcAlpha); + glGetIntegerv(GL_BLEND_DST_ALPHA, this.lastBlendDstAlpha); + glGetIntegerv(GL_BLEND_EQUATION_RGB, this.lastBlendEquationRgb); + glGetIntegerv(GL_BLEND_EQUATION_ALPHA, this.lastBlendEquationAlpha); + this.lastEnableBlend = glIsEnabled(GL_BLEND); + this.lastEnableCullFace = glIsEnabled(GL_CULL_FACE); + this.lastEnableDepthTest = glIsEnabled(GL_DEPTH_TEST); + this.lastEnableStencilTest = glIsEnabled(GL_STENCIL_TEST); + this.lastEnableScissorTest = glIsEnabled(GL_SCISSOR_TEST); + } + + private void restoreModifiedGlState() { + glUseProgram(this.lastProgram[0]); + glBindTexture(GL_TEXTURE_2D, this.lastTexture[0]); + glActiveTexture(this.lastActiveTexture[0]); + glBindVertexArray(this.lastVertexArrayObject[0]); + glBindFramebuffer(GL_FRAMEBUFFER, this.lastFramebuffer[0]); + glBindBuffer(GL_ARRAY_BUFFER, this.lastArrayBuffer[0]); + glBlendEquationSeparate(this.lastBlendEquationRgb[0], this.lastBlendEquationAlpha[0]); + glBlendFuncSeparate(this.lastBlendSrcRgb[0], this.lastBlendDstRgb[0], this.lastBlendSrcAlpha[0], this.lastBlendDstAlpha[0]); + // @formatter:off CHECKSTYLE:OFF + if (this.lastEnableBlend) glEnable(GL_BLEND); else glDisable(GL_BLEND); + if (this.lastEnableCullFace) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); + if (this.lastEnableDepthTest) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); + if (this.lastEnableStencilTest) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); + if (this.lastEnableScissorTest) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); + // @formatter:on CHECKSTYLE:ON + glViewport(this.lastViewport[0], this.lastViewport[1], this.lastViewport[2], this.lastViewport[3]); + glScissor(this.lastScissorBox[0], this.lastScissorBox[1], this.lastScissorBox[2], this.lastScissorBox[3]); + } + + // Setup desired GL state + private void bind(final int fbWidth, final int fbHeight) { + // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) + // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. + this.gVertexArrayObjectHandle = glGenVertexArrays(); + + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_STENCIL_TEST); + glEnable(GL_SCISSOR_TEST); + + // Setup viewport, orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + // DisplayPos is (0,0) for single viewport apps. + glViewport(0, 0, fbWidth, fbHeight); + final float left = this.displayPos.x; + final float right = this.displayPos.x + this.displaySize.x; + final float top = this.displayPos.y; + final float bottom = this.displayPos.y + this.displaySize.y; + + // Orthographic matrix projection + this.orthoProjMatrix[0] = 2.0f / (right - left); + this.orthoProjMatrix[5] = 2.0f / (top - bottom); + this.orthoProjMatrix[10] = -1.0f; + this.orthoProjMatrix[12] = (right + left) / (left - right); + this.orthoProjMatrix[13] = (top + bottom) / (bottom - top); + this.orthoProjMatrix[15] = 1.0f; + + // Bind shader + glUseProgram(this.gShaderHandle); + glUniform1i(this.gAttribLocationTex, 0); + glUniformMatrix4fv(this.gAttribLocationProjMtx, false, this.orthoProjMatrix); + + glBindVertexArray(this.gVertexArrayObjectHandle); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + // Bind vertex/index buffers and setup attributes for ImDrawVert + glBindBuffer(GL_ARRAY_BUFFER, this.gVboHandle); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this.gElementsHandle); + glEnableVertexAttribArray(this.gAttribLocationVtxPos); + glEnableVertexAttribArray(this.gAttribLocationVtxUV); + glEnableVertexAttribArray(this.gAttribLocationVtxColor); + glVertexAttribPointer(this.gAttribLocationVtxPos, 2, GL_FLOAT, false, ImDrawData.SIZEOF_IM_DRAW_VERT, 0); + glVertexAttribPointer(this.gAttribLocationVtxUV, 2, GL_FLOAT, false, ImDrawData.SIZEOF_IM_DRAW_VERT, 8); + glVertexAttribPointer(this.gAttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, true, ImDrawData.SIZEOF_IM_DRAW_VERT, 16); + } + + private void unbind() { + // Destroy the temporary VAO + glDeleteVertexArrays(this.gVertexArrayObjectHandle); + } + + //-------------------------------------------------------------------------------------------------------- + // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT + // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously. + // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. + //-------------------------------------------------------------------------------------------------------- + + private void initPlatformInterface() { + ImGui.getPlatformIO().setRendererRenderWindow(new ImPlatformFuncViewport() { + @Override + public void accept(final ImGuiViewport vp) { + if (!vp.hasFlags(ImGuiViewportFlags.NoRendererClear)) { + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); + } + CustomImGuiImplGl3.this.renderDrawData(vp.getDrawData()); + } + }); + } + + private void shutdownPlatformInterface() { + ImGui.destroyPlatformWindows(); + } + + private int createAndCompileShader(final int type, final CharSequence source) { + final int id = glCreateShader(type); + + glShaderSource(id, source); + glCompileShader(id); + + if (glGetShaderi(id, GL_COMPILE_STATUS) == GL_FALSE) { + throw new IllegalStateException("Failed to compile shader:\n" + glGetShaderInfoLog(id)); + } + + return id; + } + + private String getVertexShaderGlsl120() { + return this.glslVersion + "\n" + + "uniform mat4 ProjMtx;\n" + + "attribute vec2 Position;\n" + + "attribute vec2 UV;\n" + + "attribute vec4 Color;\n" + + "varying vec2 Frag_UV;\n" + + "varying vec4 Frag_Color;\n" + + "void main()\n" + + "{\n" + + " Frag_UV = UV;\n" + + " Frag_Color = Color;\n" + + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + + "}\n"; + } + + private String getVertexShaderGlsl130() { + return this.glslVersion + "\n" + + "uniform mat4 ProjMtx;\n" + + "in vec2 Position;\n" + + "in vec2 UV;\n" + + "in vec4 Color;\n" + + "out vec2 Frag_UV;\n" + + "out vec4 Frag_Color;\n" + + "void main()\n" + + "{\n" + + " Frag_UV = UV;\n" + + " Frag_Color = Color;\n" + + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + + "}\n"; + } + + private String getVertexShaderGlsl300es() { + return this.glslVersion + "\n" + + "precision highp float;\n" + + "layout (location = 0) in vec2 Position;\n" + + "layout (location = 1) in vec2 UV;\n" + + "layout (location = 2) in vec4 Color;\n" + + "uniform mat4 ProjMtx;\n" + + "out vec2 Frag_UV;\n" + + "out vec4 Frag_Color;\n" + + "void main()\n" + + "{\n" + + " Frag_UV = UV;\n" + + " Frag_Color = Color;\n" + + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + + "}\n"; + } + + private String getVertexShaderGlsl410Core() { + return this.glslVersion + "\n" + + "layout (location = 0) in vec2 Position;\n" + + "layout (location = 1) in vec2 UV;\n" + + "layout (location = 2) in vec4 Color;\n" + + "uniform mat4 ProjMtx;\n" + + "out vec2 Frag_UV;\n" + + "out vec4 Frag_Color;\n" + + "void main()\n" + + "{\n" + + " Frag_UV = UV;\n" + + " Frag_Color = Color;\n" + + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + + "}\n"; + } + + private String getFragmentShaderGlsl120() { + return this.glslVersion + "\n" + + "#ifdef GL_ES\n" + + " precision mediump float;\n" + + "#endif\n" + + "uniform sampler2D Texture;\n" + + "varying vec2 Frag_UV;\n" + + "varying vec4 Frag_Color;\n" + + "void main()\n" + + "{\n" + + " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" + + "}\n"; + } + + private String getFragmentShaderGlsl130() { + return this.glslVersion + "\n" + + "uniform sampler2D Texture;\n" + + "in vec2 Frag_UV;\n" + + "in vec4 Frag_Color;\n" + + "out vec4 Out_Color;\n" + + "void main()\n" + + "{\n" + + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + + "}\n"; + } + + private String getFragmentShaderGlsl300es() { + return this.glslVersion + "\n" + + "precision mediump float;\n" + + "uniform sampler2D Texture;\n" + + "in vec2 Frag_UV;\n" + + "in vec4 Frag_Color;\n" + + "layout (location = 0) out vec4 Out_Color;\n" + + "void main()\n" + + "{\n" + + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + + "}\n"; + } + + private String getFragmentShaderGlsl410Core() { + return this.glslVersion + "\n" + + "in vec2 Frag_UV;\n" + + "in vec4 Frag_Color;\n" + + "uniform sampler2D Texture;\n" + + "layout (location = 0) out vec4 Out_Color;\n" + + "void main()\n" + + "{\n" + + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + + "}\n"; + } +} diff --git a/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGlfw.java b/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGlfw.java new file mode 100644 index 0000000..33f9408 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGlfw.java @@ -0,0 +1,1209 @@ +package com.moulberry.flashback.ui; + +import imgui.ImGui; +import imgui.ImGuiIO; +import imgui.ImGuiPlatformIO; +import imgui.ImGuiViewport; +import imgui.ImVec2; +import imgui.callback.ImPlatformFuncViewport; +import imgui.callback.ImPlatformFuncViewportFloat; +import imgui.callback.ImPlatformFuncViewportImVec2; +import imgui.callback.ImPlatformFuncViewportString; +import imgui.callback.ImPlatformFuncViewportSuppBoolean; +import imgui.callback.ImPlatformFuncViewportSuppImVec2; +import imgui.callback.ImStrConsumer; +import imgui.callback.ImStrSupplier; +import imgui.flag.ImGuiBackendFlags; +import imgui.flag.ImGuiConfigFlags; +import imgui.flag.ImGuiKey; +import imgui.flag.ImGuiMouseButton; +import imgui.flag.ImGuiMouseCursor; +import imgui.flag.ImGuiNavInput; +import imgui.flag.ImGuiViewportFlags; +import imgui.lwjgl3.glfw.ImGuiImplGlfwNative; +import net.minecraft.client.Minecraft; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; +import org.lwjgl.PointerBuffer; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.glfw.GLFWCharCallback; +import org.lwjgl.glfw.GLFWCharModsCallback; +import org.lwjgl.glfw.GLFWCursorEnterCallback; +import org.lwjgl.glfw.GLFWCursorPosCallback; +import org.lwjgl.glfw.GLFWErrorCallback; +import org.lwjgl.glfw.GLFWKeyCallback; +import org.lwjgl.glfw.GLFWMonitorCallback; +import org.lwjgl.glfw.GLFWMouseButtonCallback; +import org.lwjgl.glfw.GLFWNativeWin32; +import org.lwjgl.glfw.GLFWScrollCallback; +import org.lwjgl.glfw.GLFWVidMode; +import org.lwjgl.glfw.GLFWWindowFocusCallback; + +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.List; + +import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.system.MemoryUtil.NULL; + +public class CustomImGuiImplGlfw { + private static final String OS = System.getProperty("os.name", "generic").toLowerCase(); + protected static final boolean IS_WINDOWS = OS.contains("win"); + protected static final boolean IS_APPLE = OS.contains("mac") || OS.contains("darwin"); + + // Pointer of the current GLFW window + private long mainWindowPtr; + + // Some features may be available only from a specific version + private boolean glfwHawWindowTopmost; + private boolean glfwHasWindowAlpha; + private boolean glfwHasPerMonitorDpi; + private boolean glfwHasFocusWindow; + private boolean glfwHasFocusOnShow; + private boolean glfwHasMonitorWorkArea; + private boolean glfwHasOsxWindowPosFix; + + // For application window properties + private final int[] winWidth = new int[1]; + private final int[] winHeight = new int[1]; + private final int[] fbWidth = new int[1]; + private final int[] fbHeight = new int[1]; + private final float[] windowScaleX = new float[1]; + private final float[] windowScaleY = new float[1]; + + // Mouse cursors provided by GLFW + private final long[] mouseCursors = new long[ImGuiMouseCursor.COUNT]; + private final long[] keyOwnerWindows = new long[512]; + private final boolean[] keyPressedGame = new boolean[512]; + // private final int[] physicalToPrintableKeys = new int[GLFW_KEY_LAST - GLFW_KEY_SPACE + 1]; + + // Empty array to fill ImGuiIO.NavInputs with zeroes + private final float[] emptyNavInputs = new float[ImGuiNavInput.COUNT]; + + // For mouse tracking + private final boolean[] mouseJustPressed = new boolean[ImGuiMouseButton.COUNT]; + private final ImVec2 mousePosBackup = new ImVec2(); + private final double[] mouseX = new double[1]; + private final double[] mouseY = new double[1]; + + private final int[] windowX = new int[1]; + private final int[] windowY = new int[1]; + + // Monitor properties + private final int[] monitorX = new int[1]; + private final int[] monitorY = new int[1]; + private final int[] monitorWorkAreaX = new int[1]; + private final int[] monitorWorkAreaY = new int[1]; + private final int[] monitorWorkAreaWidth = new int[1]; + private final int[] monitorWorkAreaHeight = new int[1]; + private final float[] monitorContentScaleX = new float[1]; + private final float[] monitorContentScaleY = new float[1]; + + // GLFW callbacks + private GLFWWindowFocusCallback prevUserCallbackWindowFocus = null; + private GLFWMouseButtonCallback prevUserCallbackMouseButton = null; + private GLFWScrollCallback prevUserCallbackScroll = null; + private GLFWCursorPosCallback prevUserCallbackCursorPos = null; + private GLFWKeyCallback prevUserCallbackKey = null; + private GLFWCharModsCallback prevUserCallbackChar = null; + private GLFWMonitorCallback prevUserCallbackMonitor = null; + private GLFWCursorEnterCallback prevUserCallbackCursorEnter = null; + + // Internal data + private boolean callbacksInstalled = false; + private boolean wantUpdateMonitors = true; + private double time = 0.0; + private long mouseWindowPtr; + + private MouseHandledBy grabbed = null; + private int ignoreMouseMovements = 0; + private boolean releasedAllKeysBecauseOfDisable = false; + private final double[] grabbedOriginalMouseX = new double[1]; + private final double[] grabbedOriginalMouseY = new double[1]; + private int grabLinkedKey = -1; + + private List interframeMousePositions = new ArrayList<>(); + private List capturedInterframeMousePositions = new ArrayList<>(); + + public float contentScale = 1.0f; + + public enum MouseHandledBy { + EDITOR_GRABBED, + IMGUI, + GAME, + BOTH; + + public boolean allowImgui() { + return this == IMGUI || this == BOTH; + } + + public boolean allowGame() { + return this == GAME || this == BOTH; + } + } + + public MouseHandledBy getMouseHandledBy() { + if (!ReplayUI.isActive()) return MouseHandledBy.GAME; + if (this.grabbed != null) return this.grabbed; + if (ImGui.getIO().getWantCaptureMouse()) return MouseHandledBy.IMGUI; + return MouseHandledBy.BOTH; + } + + public boolean isGrabbed() { + return this.grabbed != null; + } + + public void ungrab() { + if (this.grabbed == null) return; + this.grabbed = null; + this.grabLinkedKey = 0; + + GLFW.glfwSetInputMode(this.mainWindowPtr, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + GLFW.glfwSetCursorPos(this.mainWindowPtr, this.grabbedOriginalMouseX[0], this.grabbedOriginalMouseY[0]); + } + + public void setGrabbed(boolean passthroughToGame, int grabLinkedKey, double x, double y) { + if (grabLinkedKey != 0) { + if (grabLinkedKey < 0) { + if (GLFW.glfwGetMouseButton(this.mainWindowPtr, -grabLinkedKey-1) == GLFW_RELEASE) { + this.ungrab(); + return; + } + } else if (GLFW.glfwGetKey(this.mainWindowPtr, grabLinkedKey) == GLFW_RELEASE) { + this.ungrab(); + return; + } + } + if (this.grabbed != null) return; + this.grabbed = passthroughToGame ? MouseHandledBy.GAME : MouseHandledBy.EDITOR_GRABBED; + + if (grabLinkedKey != 0) { + this.grabLinkedKey = grabLinkedKey; + } + if (x >= 0 && y >= 0) { + this.grabbedOriginalMouseX[0] = x; + this.grabbedOriginalMouseY[0] = y; + } else { + GLFW.glfwGetCursorPos(this.mainWindowPtr, this.grabbedOriginalMouseX, this.grabbedOriginalMouseY); + } + GLFW.glfwSetInputMode(this.mainWindowPtr, GLFW_CURSOR, GLFW_CURSOR_DISABLED); + this.ignoreMouseMovements = 2; + Minecraft.getInstance().mouseHandler.setIgnoreFirstMove(); + } + + private static double grabbedLastMouseX = 0; + private static double grabbedLastMouseY = 0; + private static double grabbedCurrMouseX = 0; + private static double grabbedCurrMouseY = 0; + + public double getGrabbedMouseDeltaX() { + double delta = grabbedCurrMouseX - grabbedLastMouseX; + grabbedLastMouseX = grabbedCurrMouseX; + return delta; + } + + public double getGrabbedMouseDeltaY() { + double delta = grabbedCurrMouseY - grabbedLastMouseY; + grabbedLastMouseY = grabbedCurrMouseY; + return delta; + } + + /** + * Method to set the {@link GLFWMouseButtonCallback}. + * + * @param windowId pointer to the window + * @param button clicked mouse button + * @param action click action type + * @param mods click modifiers + */ + public void mouseButtonCallback(final long windowId, final int button, final int action, final int mods) { + if (!ReplayUI.isActive()) { + if (this.prevUserCallbackMouseButton != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackMouseButton.invoke(windowId, button, action, mods); + } + return; + } + + if (this.grabbed != null && action == GLFW_RELEASE && this.grabLinkedKey < 0 && button == -this.grabLinkedKey-1) { + this.ungrab(); + } + + MouseHandledBy handledBy = this.getMouseHandledBy(); + + if (handledBy.allowGame() && this.prevUserCallbackMouseButton != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackMouseButton.invoke(windowId, button, action, mods); + } + if (handledBy.allowImgui() && action == GLFW_PRESS && button >= 0 && button < this.mouseJustPressed.length) { + this.mouseJustPressed[button] = true; + } + } + + /** + * Method to set the {@link GLFWScrollCallback}. + * + * @param windowId pointer to the window + * @param xOffset scroll offset by x-axis + * @param yOffset scroll offset by y-axis + */ + public void scrollCallback(final long windowId, final double xOffset, final double yOffset) { + if (ReplayUI.isActive()) { + final ImGuiIO io = ImGui.getIO(); + io.setMouseWheelH(io.getMouseWheelH() + (float) xOffset); + io.setMouseWheel(io.getMouseWheel() + (float) yOffset); + + if (Minecraft.getInstance().screen == null || !ReplayUI.isMainFrameHovered()) { + return; + } + } + + if (this.prevUserCallbackScroll != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackScroll.invoke(windowId, 0, yOffset); + } + } + + /** + * Method to set the {@link GLFWKeyCallback}. + * + * @param windowId pointer to the window + * @param key pressed key + * @param scancode key scancode + * @param action press action + * @param mods press modifiers + */ + public void keyCallback(final long windowId, int key, final int scancode, final int action, final int mods) { + if (key < GLFW_KEY_SPACE || key > GLFW_KEY_LAST) { + if (this.prevUserCallbackKey != null && windowId == this.mainWindowPtr) this.prevUserCallbackKey.invoke(windowId, key, scancode, action, mods); + return; + } + + boolean shiftMod = (mods & GLFW_MOD_SHIFT) != 0; + boolean ctrlMod = (mods & GLFW_MOD_CONTROL) != 0; + boolean altMod = (mods & GLFW_MOD_ALT) != 0; + boolean superMod = (mods & GLFW_MOD_SUPER) != 0; + int minecraftKey = key; + boolean keyInBoundsForGame = minecraftKey >= 0 && minecraftKey < this.keyPressedGame.length; + + final ImGuiIO io = ImGui.getIO(); + + if (this.grabbed != null && action == GLFW_RELEASE && this.grabLinkedKey > 0 && key == this.grabLinkedKey) { + this.ungrab(); + } + + if (!ReplayUI.isActive() || Minecraft.getInstance().screen != null) { + if (action == GLFW_RELEASE && key >= 0 && key < this.keyOwnerWindows.length) { + io.setKeysDown(key, false); + this.keyOwnerWindows[key] = 0; + } + if (this.prevUserCallbackKey != null && windowId == this.mainWindowPtr) { + if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE; + this.prevUserCallbackKey.invoke(windowId, minecraftKey, scancode, action, mods); + } + return; + } + + if (action == GLFW_PRESS && ImGuiHelper.getWantsSpecialInput()) { + if (key == GLFW_KEY_BACKSPACE && ImGuiHelper.backspaceInput(mods)) { + return; + } else if (key == GLFW_KEY_SPACE) { + return; + } + } + + if (action != GLFW_RELEASE && GLFW.glfwGetKey(windowId, GLFW_KEY_F3) != GLFW_RELEASE) { + this.prevUserCallbackKey.invoke(windowId, minecraftKey, scancode, action, mods); + if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE; + return; + } + + boolean passToMinecraft = (ReplayUI.isMainFrameHovered() && ImGui.isMouseDown(ImGuiMouseButton.Left) || !io.getWantCaptureKeyboard()) && !io.getWantTextInput(); + + if (action == GLFW_RELEASE) { + if (keyInBoundsForGame && this.keyPressedGame[minecraftKey]) passToMinecraft = true; + } else if (passToMinecraft) { +// out: +// for (KeybindCategory category : Keybinds.categories) { +// if (!category.preventPassToGame()) continue; +// for (Keybind keybind : category.keybinds()) { +// if (keybind.wouldBePressed(key, shiftMod, ctrlMod, altMod, superMod)) { +// passToMinecraft = false; +// break out; +// } +// } +// } + } + + if (passToMinecraft && this.prevUserCallbackKey != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackKey.invoke(windowId, minecraftKey, scancode, action, mods); + if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE; + } + + if (key >= 0 && key < this.keyOwnerWindows.length) { + if (action == GLFW_PRESS || action == GLFW_REPEAT) { + io.setKeysDown(key, true); + this.keyOwnerWindows[key] = windowId; + } else if (action == GLFW_RELEASE) { + io.setKeysDown(key, false); + this.keyOwnerWindows[key] = 0; + } + } + } + + public void cursorPosCallback(final long windowId, final double xpos, final double ypos) { + if (!ReplayUI.isActive()) { + if (this.prevUserCallbackCursorPos != null && windowId == this.mainWindowPtr) this.prevUserCallbackCursorPos.invoke(windowId, xpos, ypos); + return; + } + + MouseHandledBy handledBy = this.getMouseHandledBy(); + + if (this.ignoreMouseMovements > 0) { + grabbedCurrMouseX = xpos; + grabbedCurrMouseY = ypos; + grabbedLastMouseX = xpos; + grabbedLastMouseY = ypos; + this.ignoreMouseMovements -= 1; + return; + } + + if (handledBy.allowGame() && this.prevUserCallbackCursorPos != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackCursorPos.invoke(windowId, ReplayUI.getNewMouseX(xpos), ReplayUI.getNewMouseY(ypos)); + } + if (handledBy == MouseHandledBy.EDITOR_GRABBED) { + grabbedCurrMouseX = xpos; + grabbedCurrMouseY = ypos; + } else { + this.interframeMousePositions.add(new Vec2((float)xpos, (float)ypos)); + } + } + + /** + * Method to set the {@link GLFWWindowFocusCallback}. + * + * @param windowId pointer to the window + * @param focused is window focused + */ + public void windowFocusCallback(final long windowId, final boolean focused) { + if (this.prevUserCallbackWindowFocus != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackWindowFocus.invoke(windowId, focused); + } + + ImGui.getIO().addFocusEvent(focused); + } + + /** + * Method to set the {@link GLFWCursorEnterCallback}. + * + * @param windowId pointer to the window + * @param entered is cursor entered + */ + public void cursorEnterCallback(final long windowId, final boolean entered) { + if (this.prevUserCallbackCursorEnter != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackCursorEnter.invoke(windowId, entered); + } + + if (entered) { + this.mouseWindowPtr = windowId; + } + if (!entered && this.mouseWindowPtr == windowId) { + this.mouseWindowPtr = 0; + } + } + + /** + * Method to set the {@link GLFWCharCallback}. + * + * @param windowId pointer to the window + * @param c pressed char + */ + public void charCallback(final long windowId, final int c, final int mods) { + if (!ReplayUI.isActive()) { + if (this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) this.prevUserCallbackChar.invoke(windowId, c, mods); + return; + } + + final ImGuiIO io = ImGui.getIO(); + + if (!io.getWantCaptureKeyboard() && this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackChar.invoke(windowId, c, mods); + } + + if (!ImGuiHelper.addInputCharacter((char) c)) { + io.addInputCharacter(c); + } + } + + /** + * Method to set the {@link GLFWMonitorCallback}. + * + * @param windowId pointer to the window + * @param event monitor event type (ignored) + */ + public void monitorCallback(final long windowId, final int event) { + if (this.prevUserCallbackMonitor != null && windowId == this.mainWindowPtr) { + this.prevUserCallbackMonitor.invoke(windowId, event); + } + this.wantUpdateMonitors = true; + } + + private final int[] keyMap = new int[ImGuiKey.COUNT]; + { + this.keyMap[ImGuiKey.Tab] = -1; // Note: Tab input forcibly unhooked + this.keyMap[ImGuiKey.LeftArrow] = GLFW_KEY_LEFT; + this.keyMap[ImGuiKey.RightArrow] = GLFW_KEY_RIGHT; + this.keyMap[ImGuiKey.UpArrow] = GLFW_KEY_UP; + this.keyMap[ImGuiKey.DownArrow] = GLFW_KEY_DOWN; + this.keyMap[ImGuiKey.PageUp] = GLFW_KEY_PAGE_UP; + this.keyMap[ImGuiKey.PageDown] = GLFW_KEY_PAGE_DOWN; + this.keyMap[ImGuiKey.Home] = GLFW_KEY_HOME; + this.keyMap[ImGuiKey.End] = GLFW_KEY_END; + this.keyMap[ImGuiKey.Insert] = GLFW_KEY_INSERT; + this.keyMap[ImGuiKey.Delete] = GLFW_KEY_DELETE; + this.keyMap[ImGuiKey.Backspace] = GLFW_KEY_BACKSPACE; + this.keyMap[ImGuiKey.Space] = GLFW_KEY_SPACE; + this.keyMap[ImGuiKey.Enter] = GLFW_KEY_ENTER; + this.keyMap[ImGuiKey.Escape] = GLFW_KEY_ESCAPE; + this.keyMap[ImGuiKey.KeyPadEnter] = GLFW_KEY_KP_ENTER; + this.keyMap[ImGuiKey.A] = GLFW_KEY_A; + this.keyMap[ImGuiKey.C] = GLFW_KEY_C; + this.keyMap[ImGuiKey.V] = GLFW_KEY_V; + this.keyMap[ImGuiKey.X] = GLFW_KEY_X; + this.keyMap[ImGuiKey.Y] = GLFW_KEY_Y; + this.keyMap[ImGuiKey.Z] = GLFW_KEY_Z; + } + + public void enableTabInput() { + this.keyMap[ImGuiKey.Tab] = GLFW_KEY_TAB; + ImGui.getIO().setKeyMap(this.keyMap); + } + + public void disableTabInput() { + this.keyMap[ImGuiKey.Tab] = -1; + ImGui.getIO().setKeyMap(this.keyMap); + } + + /** + * Method to do an initialization of the {@link imgui.glfw.ImGuiImplGlfw} state. It SHOULD be called before calling the {@link imgui.glfw.ImGuiImplGlfw#newFrame()} method. + *

+ * Method takes two arguments, which should be a valid GLFW window pointer and a boolean indicating whether or not to install callbacks. + * + * @param windowId pointer to the window + * @param installCallbacks should window callbacks be installed + * @return true if everything initialized + */ + public boolean init(final long windowId, final boolean installCallbacks) { + this.mainWindowPtr = windowId; + + this.detectGlfwVersionAndEnabledFeatures(); + + final ImGuiIO io = ImGui.getIO(); + + io.addBackendFlags(ImGuiBackendFlags.HasMouseCursors | ImGuiBackendFlags.HasSetMousePos | ImGuiBackendFlags.PlatformHasViewports); + io.setBackendPlatformName("imgui_java_impl_glfw"); + + // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array. + io.setKeyMap(this.keyMap); + + io.setGetClipboardTextFn(new ImStrSupplier() { + @Override + public String get() { + final String clipboardString = glfwGetClipboardString(windowId); + return clipboardString != null ? clipboardString : ""; + } + }); + + io.setSetClipboardTextFn(new ImStrConsumer() { + @Override + public void accept(final String str) { + glfwSetClipboardString(windowId, str); + } + }); + + // Mouse cursors mapping. Disable errors whilst setting due to X11. + final GLFWErrorCallback prevErrorCallback = glfwSetErrorCallback(null); + this.mouseCursors[ImGuiMouseCursor.Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); + this.mouseCursors[ImGuiMouseCursor.TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); + this.mouseCursors[ImGuiMouseCursor.ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR); + this.mouseCursors[ImGuiMouseCursor.ResizeNS] = glfwCreateStandardCursor(GLFW_RESIZE_NS_CURSOR); + this.mouseCursors[ImGuiMouseCursor.ResizeEW] = glfwCreateStandardCursor(GLFW_RESIZE_EW_CURSOR); + this.mouseCursors[ImGuiMouseCursor.ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); + this.mouseCursors[ImGuiMouseCursor.ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); + this.mouseCursors[ImGuiMouseCursor.Hand] = glfwCreateStandardCursor(GLFW_POINTING_HAND_CURSOR); + this.mouseCursors[ImGuiMouseCursor.NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); + glfwSetErrorCallback(prevErrorCallback); + + if (installCallbacks) { + this.callbacksInstalled = true; + this.prevUserCallbackWindowFocus = glfwSetWindowFocusCallback(windowId, this::windowFocusCallback); + this.prevUserCallbackCursorEnter = glfwSetCursorEnterCallback(windowId, this::cursorEnterCallback); + this.prevUserCallbackMouseButton = glfwSetMouseButtonCallback(windowId, this::mouseButtonCallback); + this.prevUserCallbackScroll = glfwSetScrollCallback(windowId, this::scrollCallback); + this.prevUserCallbackCursorPos = glfwSetCursorPosCallback(windowId, this::cursorPosCallback); + this.prevUserCallbackKey = glfwSetKeyCallback(windowId, this::keyCallback); + this.prevUserCallbackChar = glfwSetCharModsCallback(windowId, this::charCallback); + this.prevUserCallbackMonitor = glfwSetMonitorCallback(this::monitorCallback); + } + + // Calculate content scale + glfwGetWindowSize(this.mainWindowPtr, this.winWidth, this.winHeight); + glfwGetFramebufferSize(this.mainWindowPtr, this.fbWidth, this.fbHeight); + + io.setDisplaySize((float) this.winWidth[0], (float) this.winHeight[0]); + if (this.winWidth[0] > 0 && this.winHeight[0] > 0) { + final float scaleX = (float) this.fbWidth[0] / this.winWidth[0]; + final float scaleY = (float) this.fbHeight[0] / this.winHeight[0]; + io.setDisplayFramebufferScale(scaleX, scaleY); + + GLFW.glfwGetWindowContentScale(Minecraft.getInstance().getWindow().getWindow(), + this.windowScaleX, this.windowScaleY); + this.contentScale = Math.max(this.windowScaleX[0] / scaleX, windowScaleY[0] / scaleY); + } + + // Update monitors the first time (note: monitor callback are broken in GLFW 3.2 and earlier, see github.com/glfw/glfw/issues/784) + this.updateMonitors(); + glfwSetMonitorCallback(this::monitorCallback); + + // Our mouse update function expect PlatformHandle to be filled for the main viewport + final ImGuiViewport mainViewport = ImGui.getMainViewport(); + mainViewport.setPlatformHandle(this.mainWindowPtr); + + if (IS_WINDOWS) { + mainViewport.setPlatformHandleRaw(GLFWNativeWin32.glfwGetWin32Window(windowId)); + } + + if (io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { + this.initPlatformInterface(); + } + + return true; + } + + public List getCapturedInterframeMousePositions() { + return this.capturedInterframeMousePositions; + } + + /** + * Updates {@link ImGuiIO} and {@link org.lwjgl.glfw.GLFW} state. + */ + public void newFrame() { + final ImGuiIO io = ImGui.getIO(); + + if (this.interframeMousePositions.isEmpty()) { + this.capturedInterframeMousePositions.clear(); + } else { + this.capturedInterframeMousePositions = this.interframeMousePositions; + this.interframeMousePositions = new ArrayList<>(); + + if (io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { + // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) + long windowPtr = this.mouseWindowPtr; + if (windowPtr == 0) { + windowPtr = this.mainWindowPtr; + } + glfwGetWindowPos(windowPtr, this.windowX, this.windowY); + + List offset = new ArrayList<>(); + for (Vec2 pos : this.capturedInterframeMousePositions) { + offset.add(new Vec2(pos.x + this.windowX[0], pos.y + this.windowY[0])); + } + this.capturedInterframeMousePositions = offset; + } + } + + glfwGetWindowSize(this.mainWindowPtr, this.winWidth, this.winHeight); + glfwGetFramebufferSize(this.mainWindowPtr, this.fbWidth, this.fbHeight); + + io.setDisplaySize((float) this.winWidth[0], (float) this.winHeight[0]); + if (this.winWidth[0] > 0 && this.winHeight[0] > 0) { + final float scaleX = (float) this.fbWidth[0] / this.winWidth[0]; + final float scaleY = (float) this.fbHeight[0] / this.winHeight[0]; + io.setDisplayFramebufferScale(scaleX, scaleY); + + GLFW.glfwGetWindowContentScale(Minecraft.getInstance().getWindow().getWindow(), + this.windowScaleX, this.windowScaleY); + this.contentScale = Math.max(this.windowScaleX[0] / scaleX, windowScaleY[0] / scaleY); + } + if (this.wantUpdateMonitors) { + this.updateMonitors(); + } + + final double currentTime = glfwGetTime(); + io.setDeltaTime(this.time > 0.0 ? (float) (currentTime - this.time) : 1.0f / 60.0f); + this.time = currentTime; + + boolean shiftDown = false; + boolean ctrlDown = false; + boolean altDown = false; + boolean superDown = false; + + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final ImGuiViewport viewport = platformIO.getViewports(n); + final long windowPtr = viewport.getPlatformHandle(); + + if (glfwGetWindowAttrib(windowPtr, GLFW_FOCUSED) != 0) { + shiftDown |= GLFW.glfwGetKey(windowPtr, GLFW_KEY_LEFT_SHIFT) != 0 || GLFW.glfwGetKey(windowPtr, GLFW_KEY_RIGHT_SHIFT) != 0; + ctrlDown |= GLFW.glfwGetKey(windowPtr, GLFW_KEY_LEFT_CONTROL) != 0 || GLFW.glfwGetKey(windowPtr, GLFW_KEY_RIGHT_CONTROL) != 0; + altDown |= GLFW.glfwGetKey(windowPtr, GLFW_KEY_LEFT_ALT) != 0 || GLFW.glfwGetKey(windowPtr, GLFW_KEY_RIGHT_ALT) != 0; + superDown |= GLFW.glfwGetKey(windowPtr, GLFW_KEY_LEFT_SUPER) != 0 || GLFW.glfwGetKey(windowPtr, GLFW_KEY_RIGHT_SUPER) != 0; + } + } + + io.setKeyShift(shiftDown); + io.setKeyCtrl(ctrlDown); + io.setKeyAlt(altDown); + io.setKeySuper(superDown); + + this.updateMousePosAndButtons(); + this.updateMouseCursor(); + this.updateGamepads(); + + } + + public void updateReleaseAllKeys(boolean release) { + if (release) { + if (!this.releasedAllKeysBecauseOfDisable) { + this.releasedAllKeysBecauseOfDisable = true; + + final ImGuiIO io = ImGui.getIO(); + + for (int key = 0; key < this.keyOwnerWindows.length; key++) { + io.setKeysDown(key, false); + this.keyOwnerWindows[key] = 0; + } + + io.setKeyCtrl(false); + io.setKeyShift(false); + io.setKeyAlt(false); + io.setKeySuper(false); + + if (ImGui.getMouseCursor() != ImGuiMouseCursor.Arrow) { + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final long windowPtr = platformIO.getViewports(n).getPlatformHandle(); + + // Change cursor back to arrow + glfwSetCursor(windowPtr, this.mouseCursors[ImGuiMouseCursor.Arrow]); + } + } + } + } else { + this.releasedAllKeysBecauseOfDisable = false; + } + } + + private void detectGlfwVersionAndEnabledFeatures() { + final int[] major = new int[1]; + final int[] minor = new int[1]; + final int[] rev = new int[1]; + glfwGetVersion(major, minor, rev); + + final int version = major[0] * 1000 + minor[0] * 100 + rev[0] * 10; + + this.glfwHawWindowTopmost = version >= 3200; + this.glfwHasWindowAlpha = version >= 3300; + this.glfwHasPerMonitorDpi = version >= 3300; + this.glfwHasFocusWindow = version >= 3200; + this.glfwHasFocusOnShow = version >= 3300; + this.glfwHasMonitorWorkArea = version >= 3300; + } + + private void updateMousePosAndButtons() { + final ImGuiIO io = ImGui.getIO(); + + var mouseHandledBy = this.getMouseHandledBy(); + if (!mouseHandledBy.allowImgui()) { + for (int i = 0; i < ImGuiMouseButton.COUNT; i++) { + io.setMouseDown(i, false); + this.mouseJustPressed[i] = false; + } + return; + } + + for (int i = 0; i < ImGuiMouseButton.COUNT; i++) { + // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. + io.setMouseDown(i, this.mouseJustPressed[i] || glfwGetMouseButton(this.mainWindowPtr, i) != 0); + this.mouseJustPressed[i] = false; + } + + io.getMousePos(this.mousePosBackup); + io.setMousePos(-Float.MAX_VALUE, -Float.MAX_VALUE); + io.setMouseHoveredViewport(0); + + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final ImGuiViewport viewport = platformIO.getViewports(n); + final long windowPtr = viewport.getPlatformHandle(); + + final boolean focused = glfwGetWindowAttrib(windowPtr, GLFW_FOCUSED) != 0; + + // Update mouse buttons + if (focused) { + for (int i = 0; i < ImGuiMouseButton.COUNT; i++) { + if (!io.getMouseDown(i)) { + io.setMouseDown(i, glfwGetMouseButton(windowPtr, i) != 0); + } + } + } + + // Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + // (When multi-viewports are enabled, all Dear ImGui positions are same as OS positions) + if (io.getWantSetMousePos() && focused) { + glfwSetCursorPos(windowPtr, this.mousePosBackup.x - viewport.getPosX(), this.mousePosBackup.y - viewport.getPosY()); + } + + // Set Dear ImGui mouse position from OS position + if (this.mouseWindowPtr == windowPtr || focused) { + glfwGetCursorPos(windowPtr, this.mouseX, this.mouseY); + + if (io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { + // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) + glfwGetWindowPos(windowPtr, this.windowX, this.windowY); + io.setMousePos((float) this.mouseX[0] + this.windowX[0], (float) this.mouseY[0] + this.windowY[0]); + } else { + // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) + io.setMousePos((float) this.mouseX[0], (float) this.mouseY[0]); + } + } + } + } + + private void updateMouseCursor() { + final ImGuiIO io = ImGui.getIO(); + + final boolean noCursorChange = io.hasConfigFlags(ImGuiConfigFlags.NoMouseCursorChange); + final boolean cursorDisabled = glfwGetInputMode(this.mainWindowPtr, GLFW_CURSOR) == GLFW_CURSOR_DISABLED; + + if (noCursorChange || cursorDisabled) { + return; + } + + final int imguiCursor = ImGui.getMouseCursor(); + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final long windowPtr = platformIO.getViewports(n).getPlatformHandle(); + + if (imguiCursor == ImGuiMouseCursor.None || io.getMouseDrawCursor()) { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + glfwSetInputMode(windowPtr, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + } else { + // Show OS mouse cursor + // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. + glfwSetCursor(windowPtr, this.mouseCursors[imguiCursor] != 0 ? this.mouseCursors[imguiCursor] : this.mouseCursors[ImGuiMouseCursor.Arrow]); + glfwSetInputMode(windowPtr, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + } + } + } + + private void updateGamepads() { + final ImGuiIO io = ImGui.getIO(); + + if (!io.hasConfigFlags(ImGuiConfigFlags.NavEnableGamepad)) { + return; + } + + io.setNavInputs(this.emptyNavInputs); + + final ByteBuffer buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1); + final int buttonsCount = buttons.limit(); + + final FloatBuffer axis = glfwGetJoystickAxes(GLFW_JOYSTICK_1); + final int axisCount = axis.limit(); + + this.mapButton(ImGuiNavInput.Activate, 0, buttons, buttonsCount, io); // Cross / A + this.mapButton(ImGuiNavInput.Cancel, 1, buttons, buttonsCount, io); // Circle / B + this.mapButton(ImGuiNavInput.Menu, 2, buttons, buttonsCount, io); // Square / X + this.mapButton(ImGuiNavInput.Input, 3, buttons, buttonsCount, io); // Triangle / Y + this.mapButton(ImGuiNavInput.DpadLeft, 13, buttons, buttonsCount, io); // D-Pad Left + this.mapButton(ImGuiNavInput.DpadRight, 11, buttons, buttonsCount, io); // D-Pad Right + this.mapButton(ImGuiNavInput.DpadUp, 10, buttons, buttonsCount, io); // D-Pad Up + this.mapButton(ImGuiNavInput.DpadDown, 12, buttons, buttonsCount, io); // D-Pad Down + this.mapButton(ImGuiNavInput.FocusPrev, 4, buttons, buttonsCount, io); // L1 / LB + this.mapButton(ImGuiNavInput.FocusNext, 5, buttons, buttonsCount, io); // R1 / RB + this.mapButton(ImGuiNavInput.TweakSlow, 4, buttons, buttonsCount, io); // L1 / LB + this.mapButton(ImGuiNavInput.TweakFast, 5, buttons, buttonsCount, io); // R1 / RB + this.mapAnalog(ImGuiNavInput.LStickLeft, 0, -0.3f, -0.9f, axis, axisCount, io); + this.mapAnalog(ImGuiNavInput.LStickRight, 0, +0.3f, +0.9f, axis, axisCount, io); + this.mapAnalog(ImGuiNavInput.LStickUp, 1, +0.3f, +0.9f, axis, axisCount, io); + this.mapAnalog(ImGuiNavInput.LStickDown, 1, -0.3f, -0.9f, axis, axisCount, io); + + if (axisCount > 0 && buttonsCount > 0) { + io.addBackendFlags(ImGuiBackendFlags.HasGamepad); + } else { + io.removeBackendFlags(ImGuiBackendFlags.HasGamepad); + } + } + + private void mapButton(final int navNo, final int buttonNo, final ByteBuffer buttons, final int buttonsCount, final ImGuiIO io) { + if (buttonsCount > buttonNo && buttons.get(buttonNo) == GLFW_PRESS) { + io.setNavInputs(navNo, 1.0f); + } + } + + private void mapAnalog( + final int navNo, + final int axisNo, + final float v0, + final float v1, + final FloatBuffer axis, + final int axisCount, + final ImGuiIO io + ) { + float v = axisCount > axisNo ? axis.get(axisNo) : v0; + v = (v - v0) / (v1 - v0); + if (v > 1.0f) { + v = 1.0f; + } + if (io.getNavInputs(navNo) < v) { + io.setNavInputs(navNo, v); + } + } + + private void updateMonitors() { + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + final PointerBuffer monitors = glfwGetMonitors(); + + platformIO.resizeMonitors(0); + + for (int n = 0; n < monitors.limit(); n++) { + final long monitor = monitors.get(n); + + glfwGetMonitorPos(monitor, this.monitorX, this.monitorY); + final GLFWVidMode vidMode = glfwGetVideoMode(monitor); + final float mainPosX = this.monitorX[0]; + final float mainPosY = this.monitorY[0]; + final float mainSizeX = vidMode.width(); + final float mainSizeY = vidMode.height(); + + if (this.glfwHasMonitorWorkArea) { + glfwGetMonitorWorkarea(monitor, this.monitorWorkAreaX, this.monitorWorkAreaY, this.monitorWorkAreaWidth, this.monitorWorkAreaHeight); + } + + float workPosX = 0; + float workPosY = 0; + float workSizeX = 0; + float workSizeY = 0; + + // Workaround a small GLFW issue reporting zero on monitor changes: https://github.com/glfw/glfw/pull/1761 + if (this.glfwHasMonitorWorkArea && this.monitorWorkAreaWidth[0] > 0 && this.monitorWorkAreaHeight[0] > 0) { + workPosX = this.monitorWorkAreaX[0]; + workPosY = this.monitorWorkAreaY[0]; + workSizeX = this.monitorWorkAreaWidth[0]; + workSizeY = this.monitorWorkAreaHeight[0]; + } + + // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, + // which generally needs to be set in the manifest or at runtime. + if (this.glfwHasPerMonitorDpi) { + glfwGetMonitorContentScale(monitor, this.monitorContentScaleX, this.monitorContentScaleY); + } + final float dpiScale = this.monitorContentScaleX[0]; + + platformIO.pushMonitors(mainPosX, mainPosY, mainSizeX, mainSizeY, workPosX, workPosY, workSizeX, workSizeY, dpiScale); + } + + this.wantUpdateMonitors = false; + } + + //-------------------------------------------------------------------------------------------------------- + // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT + // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously. + // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. + //-------------------------------------------------------------------------------------------------------- + + private boolean viewportWindowsHidden = false; + public void setViewportWindowsHidden(boolean viewportWindowsHidden) { + if (this.viewportWindowsHidden == viewportWindowsHidden) return; + + if (!this.viewportWindowsHidden) { + this.viewportWindowsHidden = true; + + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final long windowPtr = platformIO.getViewports(n).getPlatformHandle(); + if (windowPtr != this.mainWindowPtr) glfwHideWindow(windowPtr); + } + } else { + this.viewportWindowsHidden = false; + + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final long windowPtr = platformIO.getViewports(n).getPlatformHandle(); + if (windowPtr != this.mainWindowPtr) glfwShowWindow(windowPtr); + } + } + } + + private void windowCloseCallback(final long windowId) { + final ImGuiViewport vp = ImGui.findViewportByPlatformHandle(windowId); + vp.setPlatformRequestClose(true); + } + + // GLFW may dispatch window pos/size events after calling glfwSetWindowPos()/glfwSetWindowSize(). + // However: depending on the platform the callback may be invoked at different time: + // - on Windows it appears to be called within the glfwSetWindowPos()/glfwSetWindowSize() call + // - on Linux it is queued and invoked during glfwPollEvents() + // Because the event doesn't always fire on glfwSetWindowXXX() we use a frame counter tag to only + // ignore recent glfwSetWindowXXX() calls. + private void windowPosCallback(final long windowId, final int xPos, final int yPos) { + final ImGuiViewport vp = ImGui.findViewportByPlatformHandle(windowId); + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + final boolean ignoreEvent = (ImGui.getFrameCount() <= data.ignoreWindowPosEventFrame + 1); + + if (ignoreEvent) { + return; + } + + vp.setPlatformRequestMove(true); + } + + private void windowSizeCallback(final long windowId, final int width, final int height) { + final ImGuiViewport vp = ImGui.findViewportByPlatformHandle(windowId); + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + final boolean ignoreEvent = (ImGui.getFrameCount() <= data.ignoreWindowSizeEventFrame + 1); + + if (ignoreEvent) { + return; + } + + vp.setPlatformRequestResize(true); + } + + private final class CreateWindowFunction extends ImPlatformFuncViewport { + @Override + public void accept(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = new ImGuiViewportDataGlfw(); + + vp.setPlatformUserData(data); + + // GLFW 3.2 unfortunately always set focus on glfwCreateWindow() if GLFW_VISIBLE is set, regardless of GLFW_FOCUSED + // With GLFW 3.3, the hint GLFW_FOCUS_ON_SHOW fixes this problem + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); + glfwWindowHint(GLFW_FOCUSED, GLFW_FALSE); + if (CustomImGuiImplGlfw.this.glfwHasFocusOnShow) { + glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_FALSE); + } + glfwWindowHint(GLFW_DECORATED, vp.hasFlags(ImGuiViewportFlags.NoDecoration) ? GLFW_FALSE : GLFW_TRUE); + if (CustomImGuiImplGlfw.this.glfwHawWindowTopmost) { + glfwWindowHint(GLFW_FLOATING, vp.hasFlags(ImGuiViewportFlags.TopMost) ? GLFW_TRUE : GLFW_FALSE); + } + + data.window = glfwCreateWindow((int) vp.getSizeX(), (int) vp.getSizeY(), "No Title Yet", NULL, CustomImGuiImplGlfw.this.mainWindowPtr); + data.windowOwned = true; + + vp.setPlatformHandle(data.window); + + if (IS_WINDOWS) { + vp.setPlatformHandleRaw(GLFWNativeWin32.glfwGetWin32Window(data.window)); + } + + glfwSetWindowPos(data.window, (int) vp.getPosX(), (int) vp.getPosY()); + + // Install GLFW callbacks for secondary viewports + glfwSetMouseButtonCallback(data.window, CustomImGuiImplGlfw.this::mouseButtonCallback); + glfwSetScrollCallback(data.window, CustomImGuiImplGlfw.this::scrollCallback); + glfwSetKeyCallback(data.window, CustomImGuiImplGlfw.this::keyCallback); + glfwSetCharModsCallback(data.window, CustomImGuiImplGlfw.this::charCallback); + glfwSetWindowCloseCallback(data.window, CustomImGuiImplGlfw.this::windowCloseCallback); + glfwSetWindowPosCallback(data.window, CustomImGuiImplGlfw.this::windowPosCallback); + glfwSetWindowSizeCallback(data.window, CustomImGuiImplGlfw.this::windowSizeCallback); + + glfwMakeContextCurrent(data.window); + glfwSwapInterval(0); + } + } + + private final class DestroyWindowFunction extends ImPlatformFuncViewport { + @Override + public void accept(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + + if (data != null && data.windowOwned) { + // Release any keys that were pressed in the window being destroyed and are still held down, + // because we will not receive any release events after window is destroyed. + for (int i = 0; i < CustomImGuiImplGlfw.this.keyOwnerWindows.length; i++) { + if (CustomImGuiImplGlfw.this.keyOwnerWindows[i] == data.window) { + CustomImGuiImplGlfw.this.keyCallback(data.window, i, 0, GLFW_RELEASE, 0); // Later params are only used for main viewport, on which this function is never called. + } + } + + glfwDestroyWindow(data.window); + } + + vp.setPlatformUserData(null); + vp.setPlatformHandle(0); + } + } + + private final class ShowWindowFunction extends ImPlatformFuncViewport { + @Override + public void accept(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + + if (IS_WINDOWS && vp.hasFlags(ImGuiViewportFlags.NoTaskBarIcon)) { + ImGuiImplGlfwNative.win32hideFromTaskBar(vp.getPlatformHandleRaw()); + } + + if (!CustomImGuiImplGlfw.this.viewportWindowsHidden) glfwShowWindow(data.window); + } + } + + private static final class GetWindowPosFunction extends ImPlatformFuncViewportSuppImVec2 { + private final int[] posX = new int[1]; + private final int[] posY = new int[1]; + + @Override + public void get(final ImGuiViewport vp, final ImVec2 dstImVec2) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwGetWindowPos(data.window, this.posX, this.posY); + dstImVec2.x = this.posX[0]; + dstImVec2.y = this.posY[0]; + } + } + + private static final class SetWindowPosFunction extends ImPlatformFuncViewportImVec2 { + @Override + public void accept(final ImGuiViewport vp, final ImVec2 imVec2) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + data.ignoreWindowPosEventFrame = ImGui.getFrameCount(); + glfwSetWindowPos(data.window, (int) imVec2.x, (int) imVec2.y); + } + } + + private static final class GetWindowSizeFunction extends ImPlatformFuncViewportSuppImVec2 { + private final int[] width = new int[1]; + private final int[] height = new int[1]; + + @Override + public void get(final ImGuiViewport vp, final ImVec2 dstImVec2) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwGetWindowSize(data.window, this.width, this.height); + dstImVec2.x = this.width[0]; + dstImVec2.y = this.height[0]; + } + } + + private final class SetWindowSizeFunction extends ImPlatformFuncViewportImVec2 { + private final int[] x = new int[1]; + private final int[] y = new int[1]; + private final int[] width = new int[1]; + private final int[] height = new int[1]; + + @Override + public void accept(final ImGuiViewport vp, final ImVec2 imVec2) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are + // positioned from the upper-left corner. GLFW makes an effort to convert macOS style coordinates, however it + // doesn't handle it when changing size. We are manually moving the window in order for changes of size to be based + // on the upper-left corner. + if (IS_APPLE && !CustomImGuiImplGlfw.this.glfwHasOsxWindowPosFix) { + glfwGetWindowPos(data.window, this.x, this.y); + glfwGetWindowSize(data.window, this.width, this.height); + glfwSetWindowPos(data.window, this.x[0], this.y[0] - this.height[0] + (int) imVec2.y); + } + data.ignoreWindowSizeEventFrame = ImGui.getFrameCount(); + glfwSetWindowSize(data.window, (int) imVec2.x, (int) imVec2.y); + } + } + + private static final class SetWindowTitleFunction extends ImPlatformFuncViewportString { + @Override + public void accept(final ImGuiViewport vp, final String str) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwSetWindowTitle(data.window, str); + } + } + + private final class SetWindowFocusFunction extends ImPlatformFuncViewport { + @Override + public void accept(final ImGuiViewport vp) { + if (CustomImGuiImplGlfw.this.glfwHasFocusWindow) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwFocusWindow(data.window); + } + } + } + + private static final class GetWindowFocusFunction extends ImPlatformFuncViewportSuppBoolean { + @Override + public boolean get(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + return glfwGetWindowAttrib(data.window, GLFW_FOCUSED) != 0; + } + } + + private static final class GetWindowMinimizedFunction extends ImPlatformFuncViewportSuppBoolean { + @Override + public boolean get(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + return glfwGetWindowAttrib(data.window, GLFW_ICONIFIED) != 0; + } + } + + private final class SetWindowAlphaFunction extends ImPlatformFuncViewportFloat { + @Override + public void accept(final ImGuiViewport vp, final float f) { + if (CustomImGuiImplGlfw.this.glfwHasWindowAlpha) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwSetWindowOpacity(data.window, f); + } + } + } + + private static final class RenderWindowFunction extends ImPlatformFuncViewport { + @Override + public void accept(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwMakeContextCurrent(data.window); + } + } + + private static final class SwapBuffersFunction extends ImPlatformFuncViewport { + @Override + public void accept(final ImGuiViewport vp) { + final ImGuiViewportDataGlfw data = (ImGuiViewportDataGlfw) vp.getPlatformUserData(); + glfwMakeContextCurrent(data.window); + glfwSwapBuffers(data.window); + } + } + + private void initPlatformInterface() { + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + + // Register platform interface (will be coupled with a renderer interface) + platformIO.setPlatformCreateWindow(new CreateWindowFunction()); + platformIO.setPlatformDestroyWindow(new DestroyWindowFunction()); + platformIO.setPlatformShowWindow(new ShowWindowFunction()); + platformIO.setPlatformGetWindowPos(new GetWindowPosFunction()); + platformIO.setPlatformSetWindowPos(new SetWindowPosFunction()); + platformIO.setPlatformGetWindowSize(new GetWindowSizeFunction()); + platformIO.setPlatformSetWindowSize(new SetWindowSizeFunction()); + platformIO.setPlatformSetWindowTitle(new SetWindowTitleFunction()); + platformIO.setPlatformSetWindowFocus(new SetWindowFocusFunction()); + platformIO.setPlatformGetWindowFocus(new GetWindowFocusFunction()); + platformIO.setPlatformGetWindowMinimized(new GetWindowMinimizedFunction()); + platformIO.setPlatformSetWindowAlpha(new SetWindowAlphaFunction()); + platformIO.setPlatformRenderWindow(new RenderWindowFunction()); + platformIO.setPlatformSwapBuffers(new SwapBuffersFunction()); + + // Register main window handle (which is owned by the main application, not by us) + // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports. + final ImGuiViewport mainViewport = ImGui.getMainViewport(); + final ImGuiViewportDataGlfw data = new ImGuiViewportDataGlfw(); + data.window = this.mainWindowPtr; + data.windowOwned = false; + mainViewport.setPlatformUserData(data); + } + + private static final class ImGuiViewportDataGlfw { + long window; + boolean windowOwned = false; + int ignoreWindowPosEventFrame = -1; + int ignoreWindowSizeEventFrame = -1; + } +} + diff --git a/src/client/java/com/moulberry/flashback/ui/EditorMovementControls.java b/src/client/java/com/moulberry/flashback/ui/EditorMovementControls.java new file mode 100644 index 0000000..cd6d8c5 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/EditorMovementControls.java @@ -0,0 +1,258 @@ +package com.moulberry.flashback.ui; + +import imgui.ImGui; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; +import org.joml.Intersectionf; +import org.joml.Vector3f; +import org.lwjgl.glfw.GLFW; + +public abstract sealed class EditorMovementControls permits EditorMovementControls.None, EditorMovementControls.Rotate, EditorMovementControls.Pan, EditorMovementControls.Arcball { + + // Interface + public abstract boolean allowGameInputWhileCaptureKeyboard(); + public abstract boolean shouldStop(boolean isGrabbed); + public abstract void update(double mouseDeltaX, double mouseDeltaY); + + // Static constructors + public static EditorMovementControls none() { + return None.INSTANCE; + } + + public static EditorMovementControls rotate() { + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) return None.INSTANCE; + + return new Rotate(ReplayUI.getMouseForwardsVector(), new Vec2( + Minecraft.getInstance().player.getXRot(), + Minecraft.getInstance().player.getYRot() + )); + } + +// public static EditorMovementControls pan() { +// LocalPlayer player = Minecraft.getInstance().player; +// if (player == null) return None.INSTANCE; +// +// RayCaster.RaycastResult result = Tool.raycastBlock(); +// if (result == null) return None.INSTANCE; +// +// Vec3 planePoint = result.getLocation(); +// return new Pan(player.position(), planePoint.toVector3f(), player.getLookAngle().toVector3f().negate()); +// } + +// public static EditorMovementControls arcball() { +// LocalPlayer player = Minecraft.getInstance().player; +// if (player == null) return None.INSTANCE; +// +// var look = ReplayUI.getMouseLookVector(); +// if (look == null) return None.INSTANCE; +// +// RayCaster.RaycastResult result = RayCaster.raycast(Minecraft.getInstance().level, +// player.getEyePosition().toVector3f(), look.toVector3f(), false, false); +// +// Vec3 point; +// if (result != null) { +// point = result.getLocation(); +// } else { +// return None.INSTANCE; +// } +// +// float distance = (float) point.distanceTo(player.getEyePosition()); +// return new Arcball(point, distance, true); +// } + + // Implementations + protected static final class None extends EditorMovementControls { + private static final None INSTANCE = new None(); + + @Override + public boolean allowGameInputWhileCaptureKeyboard() { + return false; + } + + @Override + public boolean shouldStop(boolean isGrabbed) { + return false; + } + + @Override + public void update(double mouseDeltaX, double mouseDeltaY) { + } + } + + protected static final class Rotate extends EditorMovementControls { + private final Vec3 originalForwards; + private final Vec2 originalAngles; + + public Rotate(Vec3 originalForwards, Vec2 originalAngles) { + this.originalForwards = originalForwards; + this.originalAngles = originalAngles; + } + + @Override + public boolean allowGameInputWhileCaptureKeyboard() { + return true; + } + + @Override + public boolean shouldStop(boolean isGrabbed) { + return !ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_LEFT); + // todo: keybinds +// return !Keybinds.ROTATE_CAMERA.isDownIgnoreMods(); + } + + @Override + public void update(double mouseDeltaX, double mouseDeltaY) { + Vec3 forwards = ReplayUI.getMouseForwardsVector(); + LocalPlayer player = Minecraft.getInstance().player; + if (forwards == null || player == null) return; + + float pitch = this.originalAngles.x; + float yaw = this.originalAngles.y; + Vec3 lastVector = this.originalForwards; + for (int i=1; i<=10; i++) { + Vec3 thisVector = this.originalForwards.lerp(forwards, i/10f); + + // Calculate pitch + double differenceY = lastVector.y - thisVector.y; + double pitchDelta = Math.toDegrees(Math.asin(differenceY / 2f)) * 2; + pitch = Mth.wrapDegrees(pitch - (float) pitchDelta); + pitch = Mth.clamp(pitch, -90, 90); + + // Calculate change in yaw + double yaw1 = Math.toDegrees(Math.atan2(lastVector.x, lastVector.z)); + double yaw2 = Math.toDegrees(Math.atan2(thisVector.x, thisVector.z)); + double yawDelta = Mth.wrapDegrees(yaw1 - yaw2); + + // Calculate scaling factor (radius of circle on unit sphere at current pitch) + Vector3f forwards3f = lastVector.lerp(thisVector, 0.5f).toVector3f(); + forwards3f.rotateX((float) Math.toRadians(pitch)); + forwards3f.normalize(); + float radius = (float) Math.sqrt(1 - forwards3f.y() * forwards3f.y()) * 1.08f; + if (radius < 0.2f) radius = 0.2f; + + yaw = Mth.wrapDegrees(yaw - (float) yawDelta / radius); + + lastVector = thisVector; + } + + // Set values + player.setXRot(pitch); + player.setYRot(yaw); + } + } + + protected static final class Pan extends EditorMovementControls { + private final Vec3 originalPos; + private final Vector3f planePoint; + private final Vector3f planeNormal; + + public Pan(Vec3 originalPos, Vector3f planePoint, Vector3f planeNormal) { + this.originalPos = originalPos; + this.planePoint = planePoint; + this.planeNormal = planeNormal; + } + + @Override + public boolean allowGameInputWhileCaptureKeyboard() { + return false; + } + + @Override + public boolean shouldStop(boolean isGrabbed) { + return !ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_RIGHT); +// return !Keybinds.PAN_CAMERA.isDownIgnoreMods(); + } + + @Override + public void update(double mouseDeltaX, double mouseDeltaY) { + Vec3 forwards = ReplayUI.getMouseForwardsVector(); + LocalPlayer player = Minecraft.getInstance().player; + if (forwards == null || player == null) return; + + var origin = this.originalPos.add(0, player.getEyeHeight(), 0).toVector3f(); + var view = ReplayUI.getMouseLookVectorFromForwards(forwards).toVector3f(); + + var distance = Intersectionf.intersectRayPlane(origin, view, this.planePoint, this.planeNormal, 1E-5f); + if (distance < 0) return; + + Vector3f targetPoint = origin.add(new Vector3f(view).mul(distance)); + Vector3f targetDelta = new Vector3f(targetPoint).sub(this.planePoint); + + var finalPos = this.originalPos.subtract(targetDelta.x, targetDelta.y, targetDelta.z); + player.setPos(finalPos); + player.setOldPosAndRot(); + } + } + + protected static final class Arcball extends EditorMovementControls { + private final Vec3 point; + private float distance; + private boolean snapLook; + + public Arcball(Vec3 point, float distance, boolean snapLook) { + this.point = point; + this.distance = Math.max(1, distance); + this.snapLook = snapLook; + } + + @Override + public boolean allowGameInputWhileCaptureKeyboard() { + return false; + } + + @Override + public boolean shouldStop(boolean isGrabbed) { + return !isGrabbed; + } + + @Override + public void update(double mouseDeltaX, double mouseDeltaY) { + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) return; + + if (this.snapLook) { + this.snapLook = false; + + var look = ReplayUI.getMouseLookVector(); + double horizontal = Math.sqrt(look.x*look.x + look.z*look.z); + + float newXRot = Mth.wrapDegrees((float)(Math.toDegrees(-(Mth.atan2(look.y, horizontal))))); + float newYRot = Mth.wrapDegrees((float)(Math.toDegrees(Mth.atan2(look.z, look.x))) - 90.0f); + + player.setXRot(newXRot); + player.setYRot(newYRot); + + return; + } + + double baseSensitivity = Minecraft.getInstance().options.sensitivity().get() * (double)0.6f + (double)0.2f; + double sensitivity = baseSensitivity * baseSensitivity * baseSensitivity * 8.0; + int invert = Minecraft.getInstance().options.invertYMouse().get() ? -1 : 1; + + player.turn(mouseDeltaX * sensitivity, mouseDeltaY * sensitivity * invert); + + if (ImGui.getIO().getMouseWheel() != 0) { + float wheel = Math.signum(ImGui.getIO().getMouseWheel()); + + float move = this.distance * 0.05f; + if (move > 4) move = 4 + (float)Math.sqrt(move - 4); + move *= wheel; + if (ReplayUI.isMoveQuickDown()) move *= 2; + + this.distance = Math.max(1, this.distance - move); + } + + Vec3 position = this.point.subtract(player.getLookAngle().scale(this.distance)); + + Minecraft.getInstance().player.setPos(position.subtract(0, player.getEyeHeight(), 0)); + Minecraft.getInstance().player.setOldPosAndRot(); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/ui/GlyphRanges.java b/src/client/java/com/moulberry/flashback/ui/GlyphRanges.java new file mode 100644 index 0000000..1d6fc61 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/GlyphRanges.java @@ -0,0 +1,160 @@ +package com.moulberry.flashback.ui; + +public class GlyphRanges { + + private static final short[] SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00 = { + 0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2, + 1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4, + 2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1, + 1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2, + 3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6, + 1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1, + 1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3, + 2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4, + 27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12, + 3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1, + 1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23, + 176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6, + 5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6, + 1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1, + 6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5, + 2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15, + 2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6, + 2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4, + 3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5, + 3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2, + 3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16, + 1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31, + 140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7, + 5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2, + 2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13, + 4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3, + 2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4, + 4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1, + 3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3, + 3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11, + 2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9, + 5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2, + 3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3, + 1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12, + 4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8, + 4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5, + 26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1, + 3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5, + 2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6, + 10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6 + }; + private static final short[] SC_BASE_RANGES = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x2000, 0x206F, // General Punctuation + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + (short)0xFF00, (short)0xFFEF, // Half-width characters + (short)0xFFFD, (short)0xFFFD // Invalid + }; + private static short[] SC_FULL_RANGES = null; + + public static short[] getSimplifiedChineseRanges() { + if (SC_FULL_RANGES == null) { + SC_FULL_RANGES = new short[SC_BASE_RANGES.length + SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00.length*2 + 1]; + System.arraycopy(SC_BASE_RANGES, 0, SC_FULL_RANGES, 0, SC_BASE_RANGES.length); + unpackAccumulativeOffsetsIntoRanges(0x4E00,SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00, SC_BASE_RANGES.length, SC_FULL_RANGES); + } + return SC_FULL_RANGES; + } + + private static final short[] JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00 = new short[] { + 0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1, + 1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3, + 2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8, + 2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5, + 2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1, + 1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30, + 2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3, + 13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4, + 5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14, + 2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1, + 1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1, + 7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1, + 1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1, + 6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2, + 10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7, + 2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5, + 3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1, + 6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7, + 4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2, + 4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5, + 1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6, + 12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2, + 1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16, + 22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11, + 2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18, + 18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9, + 14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3, + 1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6, + 40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1, + 12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8, + 2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1, + 1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10, + 1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5, + 3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2, + 14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5, + 12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1, + 2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5, + 1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4, + 3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7, + 2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5, + 13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13, + 18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21, + 37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1, + 5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38, + 32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4, + 1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4, + 4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1, + 3,2,1,1,1,1,2,1,1 + }; + private static final short JP_BASE_RANGES[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + (short)0xFF00, (short)0xFFEF, // Half-width characters + (short)0xFFFD, (short)0xFFFD // Invalid + }; + private static short[] JP_FULL_RANGES = null; + + public static short[] getJapaneseRanges() { + if (JP_FULL_RANGES == null) { + JP_FULL_RANGES = new short[JP_BASE_RANGES.length + JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00.length*2 + 1]; + System.arraycopy(JP_BASE_RANGES, 0, JP_FULL_RANGES, 0, JP_BASE_RANGES.length); + unpackAccumulativeOffsetsIntoRanges(0x4E00, JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00, JP_BASE_RANGES.length, JP_FULL_RANGES); + } + return JP_FULL_RANGES; + } + + private static final short[] TC_FULL_RANGES = { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x2000, 0x206F, // General Punctuation + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + (short)0xFF00, (short)0xFFEF, // Half-width characters + (short)0xFFFD, (short)0xFFFD, // Invalid + 0x4e00, (short)0x9FAF, // CJK Ideograms + 0, + }; + + public static short[] getChineseFullRanges() { + return TC_FULL_RANGES; + } + + static void unpackAccumulativeOffsetsIntoRanges(int baseCodepoint, short[] accumulativeOffsets, int index, short[] output) { + for (int n = 0; n < accumulativeOffsets.length; n++, index += 2) { + output[index] = output[index+1] = (short)(baseCodepoint + accumulativeOffsets[n]); + baseCodepoint += accumulativeOffsets[n]; + } + output[output.length - 1] = 0; + } + + +} diff --git a/src/client/java/com/moulberry/flashback/ui/ImGuiHelper.java b/src/client/java/com/moulberry/flashback/ui/ImGuiHelper.java new file mode 100644 index 0000000..a9960e7 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/ImGuiHelper.java @@ -0,0 +1,538 @@ +package com.moulberry.flashback.ui; + +import imgui.ImDrawList; +import imgui.ImGui; +import imgui.ImGuiListClipper; +import imgui.ImVec2; +import imgui.callback.ImListClipperCallback; +import imgui.flag.ImGuiCol; +import imgui.flag.ImGuiComboFlags; +import imgui.flag.ImGuiDragDropFlags; +import imgui.flag.ImGuiHoveredFlags; +import imgui.flag.ImGuiInputTextFlags; +import imgui.flag.ImGuiMouseButton; +import imgui.flag.ImGuiMouseCursor; +import imgui.flag.ImGuiWindowFlags; +import imgui.type.ImBoolean; +import imgui.type.ImString; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.ConfirmLinkScreen; +import net.minecraft.core.HolderSet; +import net.minecraft.world.level.block.Block; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.glfw.GLFW; + +import java.net.URI; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.IntConsumer; +import java.util.function.Predicate; + +public class ImGuiHelper { + + public enum LabelPosition { + LABEL_ABOVE, + LABEL_RIGHT + } + + public record Label(@NotNull String key, @NotNull String title, @Nullable String description) { + } + + public static String getString(ImString string) { + StringBuilder builder = new StringBuilder(); + String str = string.get(); + for (int i=0; i elements, float width, int minLines, int maxLines, boolean framed, IntConsumer buttonConsumer) { + if (minLines > maxLines) throw new IllegalArgumentException(); + + if (width <= 0) { + width = Math.max(ImGui.getContentRegionAvailX() + width, 4.0f); + } + + float itemSpacingX = ImGui.getStyle().getItemSpacingX(); + float framePaddingX = ImGui.getStyle().getFramePaddingX(); + float availableSpace = width; + if (framed) availableSpace -= framePaddingX*2f; + + int lines = 0; + boolean scrollbar = false; + if (minLines == maxLines) { + lines = minLines; + scrollbar = true; // assume there is a scrollbar + } else { + float consumedWidth = 0; + for (String element : elements) { + float elementWidth = framePaddingX*2f + ImGuiHelper.calcTextWidth(element); + if (consumedWidth+elementWidth < availableSpace && consumedWidth > 0) { + consumedWidth += elementWidth + itemSpacingX; + } else { + consumedWidth = elementWidth + itemSpacingX; + lines += 1; + if (lines > maxLines) { + lines = maxLines; + scrollbar = true; + break; + } + } + } + if (lines < minLines) lines = minLines; + } + + float lineHeight = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2 + ImGui.getStyle().getItemSpacingY(); + boolean visible; + if (framed) { + visible = ImGui.beginChildFrame(ImGui.getID(name), width, lineHeight*lines + ImGui.getStyle().getFramePaddingY()*2 - ImGui.getStyle().getItemSpacingY()); + } else { + visible = ImGui.beginChild(name, width, lineHeight*lines - ImGui.getStyle().getItemSpacingY()); + } + + int ret = -1; + + if (visible) { + if (scrollbar) { + availableSpace -= ImGui.getStyle().getScrollbarSize(); + } + + float consumedWidth = 0; + for (int i=0; i 0) { + ImGui.sameLine(); + consumedWidth += elementWidth + itemSpacingX; + } else { + consumedWidth = elementWidth + itemSpacingX; + } + ImGui.pushID(i); + if (ImGui.button(element)) { + ret = i; + } + if (buttonConsumer != null) { + buttonConsumer.accept(i); + } + ImGui.popID(); + } + } + + if (framed) { + ImGui.endChildFrame(); + } else { + ImGui.endChild(); + } + + return ret; + } + + public static boolean combo(String label, int[] currentItem, String[] values) { + return combo(label, currentItem, values, ImGuiComboFlags.None); + } + + public static boolean combo(String label, int[] currentItem, String[] values, int imguiComboFlags) { + boolean changed = false; + + if (ImGui.beginCombo(label, currentItem[0] < 0 ? "" : values[currentItem[0]], imguiComboFlags)) { + for (int i=0; i 0) { + specialInput.setLength(specialInput.length() - 1); + } else { + backspaceCount += 1; + } + return true; + } + return false; + } + + public static boolean beginPopup(String id) { + return beginPopup(id, ImGuiWindowFlags.None); + } + + public static boolean beginPopup(String id, int imGuiWindowFlags) { + if (ImGui.beginPopup(id, imGuiWindowFlags | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings)) { + closeableModalOnTop = false; + return true; + } else { + return false; + } + } + + public static boolean beginPopupModal(String id) { + return beginPopupModal(id, ImGuiWindowFlags.None); + } + + public static boolean beginPopupModal(String id, int imGuiWindowFlags) { + if (ImGui.beginPopupModal(id, imGuiWindowFlags | ImGuiWindowFlags.NoSavedSettings)) { + closeableModalOnTop = false; + return true; + } else { + return false; + } + } + + public static boolean beginPopupModalCloseable(String id) { + return beginPopupModalCloseable(id, ImGuiWindowFlags.None); + } + + public static boolean beginPopupModalCloseable(String id, int imGuiWindowFlags) { + if (ImGui.beginPopupModal(id, new ImBoolean(true), imGuiWindowFlags | ImGuiWindowFlags.NoSavedSettings)) { + closeableModalOnTop = true; + return true; + } else { + return false; + } + } + + public static void endPopupModalCloseable() { + if (closeableModalOnTop && closeableModalOnTopLast && ReplayUI.consumeNavClose()) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + + public static float borderIndentation = 0; + + public static void setupBorder() { + ImGui.beginGroup(); + + float windowPadding = ImGui.getStyle().getWindowPaddingX(); + borderIndentation += windowPadding; + + ImGui.indent(windowPadding); + ImGui.setCursorPosY(ImGui.getCursorPosY() + ImGui.getStyle().getWindowPaddingY()); + } + + public static void finishBorder() { + float windowPadding = ImGui.getStyle().getWindowPaddingX(); + borderIndentation -= windowPadding; + + ImGui.unindent(windowPadding); + ImGui.endGroup(); + + ImGui.getWindowDrawList().addRect(ImGui.getItemRectMinX(), ImGui.getItemRectMinY(), + ImGui.getItemRectMinX() + ImGui.getContentRegionAvailX(), + ImGui.getItemRectMaxY() + ImGui.getStyle().getWindowPaddingY(), ImGui.getColorU32(ImGuiCol.Separator)); + + ImGui.setCursorPosY(ImGui.getCursorPosY() + ImGui.getStyle().getWindowPaddingY()); + } + + public static float calcTextWidth(String text) { + ImVec2 textSizeVec = new ImVec2(); + ImGui.calcTextSize(textSizeVec, text); + return textSizeVec.x; + } + + public static LabelPosition calcLabelPosition(Label... labels) { + float availableSpace = ImGui.getWindowWidth()*0.35f - ImGui.getCursorPosX() - ImGui.getStyle().getItemInnerSpacingX(); + + for (Label label : labels) { + float requiredSpace = calcTextWidth(label.title) + ImGui.getStyle().getWindowPaddingX(); + if (label.description != null) { + requiredSpace += ImGui.getStyle().getItemSpacingX() + calcTextWidth("(?)"); + } + + if (availableSpace < requiredSpace) { + return LabelPosition.LABEL_ABOVE; + } + } + return LabelPosition.LABEL_RIGHT; + } + + public static void helpMarker(String message) { + ImGui.textDisabled("(?)"); + tooltip(message); + } + + public static void tooltip(String message) { + tooltip(message, ImGuiHoveredFlags.None); + } + + public static void openCommercialLicenseOnClick() { + if (ImGui.isItemClicked()) { + String page = "https://axiom.moulberry.com/commercial"; + Minecraft.getInstance().setScreen(new ConfirmLinkScreen(open -> { + if (open) { + try { + Util.getPlatform().openUri(new URI(page)); + } catch (Exception ignored) {} + } + Minecraft.getInstance().setScreen(null); + }, page, false)); + } + } + + public static void tooltip(String message, int imGuiHoveredFlags) { + if (ImGui.isItemHovered(imGuiHoveredFlags)) { + drawTooltip(message); + } + } + + public static void drawTooltip(String message) { + ImGui.beginTooltip(); + ImGui.pushTextWrapPos(ImGui.getFontSize() * 35.0f); + ImGui.textUnformatted(message); + ImGui.popTextWrapPos(); + ImGui.endTooltip(); + } + + public static void disabledMenuItem(String label, String disabledMessage) { + ImGui.beginDisabled(); + ImGui.menuItem(label); + ImGui.endDisabled(); + tooltip(disabledMessage, ImGuiHoveredFlags.AllowWhenDisabled); + } + + public static boolean drawLabelledWidget(Label label, LabelPosition style, Predicate predicate) { + boolean ret = false; + switch (style) { + case LABEL_ABOVE -> { + ImGui.text(label.title); + if (label.description != null) { + ImGui.sameLine(); + helpMarker(label.description); + } + ret = predicate.test("###" + label.key); + } + case LABEL_RIGHT -> { + ret = predicate.test(label.title + "###" + label.key); + if (label.description != null) { + ImGui.sameLine(); + helpMarker(label.description); + } + } + } + return ret; + } + + public static void separatorWithText(String text) { + float textStartX = ImGui.getCursorScreenPosX() + ImGui.getStyle().getIndentSpacing(); + + float size = ImGui.getWindowSizeX() - borderIndentation; + + if (ImGui.isRectVisible(size, ImGui.getFontSize())) { + float textEndX = textStartX + ImGuiHelper.calcTextWidth(text); + float lineEndX = ImGui.getWindowPosX() + size; + float lineY = ImGui.getCursorScreenPosY() + ImGui.getFontSize()/2f; + + ImGui.getWindowDrawList().addLine(ImGui.getCursorScreenPosX() - 4, lineY, + Math.min(lineEndX, textStartX) - 4, lineY, + ImGui.getColorU32(ImGuiCol.Separator)); + + if (textEndX + 4 < lineEndX) { + ImGui.getWindowDrawList().addLine(textEndX + 4, lineY, + lineEndX - 4, lineY, + ImGui.getColorU32(ImGuiCol.Separator)); + } + } + + ImGui.setCursorScreenPos(textStartX, ImGui.getCursorScreenPosY()); + ImGui.textColored(ImGui.getColorU32(ImGuiCol.TextDisabled), text); + } + + public static boolean radio(String label, int[] currentItem, String[] values) { + int item = currentItem[0]; + int newItem = -1; + + for (int i = 0; i < values.length; i++) { + String value = values[i]; + + if (i > 0) ImGui.sameLine(); + if (item == i) ImGui.beginDisabled(); + if (ImGui.button(value)) newItem = i; + if (item == i) ImGui.endDisabled(); + } + + if (label != null) { + ImGui.sameLine(); + ImGui.text(label); + } + + if (newItem != -1) { + currentItem[0] = newItem; + return true; + } else { + return false; + } + } + + public static int buttons(String... labels) { + if (labels.length == 0) return -1; + + // Calculate widths + float[] widths = new float[labels.length]; + float totalRawWidth = 0; + for (int i = 0; i < labels.length; i++) { + String label = labels[i]; + float width = ImGuiHelper.calcTextWidth(label); + widths[i] = width; + totalRawWidth += width; + } + + // Calculate extraPadding + float availableWidth = ImGui.getContentRegionAvailX(); + float freeSpace = availableWidth - totalRawWidth - ImGui.getStyle().getItemSpacingX()*(labels.length - 1); + float extraPadding = Math.max(ImGui.getStyle().getFramePaddingX()*2, freeSpace / labels.length); + + // Draw buttons + float height = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2f; + int pressed = -1; + for (int i = 0; i < labels.length; i++) { + if (ImGui.button(labels[i], widths[i] + extraPadding, height)) { + pressed = i; + } + if (i != labels.length-1) ImGui.sameLine(); + } + + return pressed; + } + + private static int pushedColors = 0; + private static int pushedStyleVars = 0; + + public static void popAllStyleColors() { + ImGui.popStyleColor(pushedColors); + pushedColors = 0; + } + + public static void popAllStyleVars() { + ImGui.popStyleVar(pushedStyleVars); + pushedStyleVars = 0; + } + + public static void pushStyleColor(int imGuiCol, float r, float g, float b, float a) { + ImGui.pushStyleColor(imGuiCol, r, g, b, a); + pushedColors += 1; + } + + public static void pushStyleColor(int imGuiCol, int r, int g, int b, int a) { + ImGui.pushStyleColor(imGuiCol, r, g, b, a); + pushedColors += 1; + } + + public static void pushStyleColor(int imGuiCol, int col) { + ImGui.pushStyleColor(imGuiCol, col); + pushedColors += 1; + } + + public static void popStyleColor() { + if (pushedColors >= 1) { + ImGui.popStyleColor(); + pushedColors -= 1; + } + } + + public static void popStyleColor(int count) { + count = Math.min(count, pushedColors); + if (count == 0) return; + + ImGui.popStyleColor(count); + pushedColors -= count; + } + + public static void pushStyleVar(int imGuiStyleVar, float val) { + ImGui.pushStyleVar(imGuiStyleVar, val); + pushedStyleVars += 1; + } + + public static void pushStyleVar(int imGuiStyleVar, float valX, float valY) { + ImGui.pushStyleVar(imGuiStyleVar, valX, valY); + pushedStyleVars += 1; + } + + public static void popStyleVar() { + if (pushedStyleVars >= 1) { + ImGui.popStyleVar(); + pushedStyleVars -= 1; + } + } + + public static void popStyleVar(int count) { + count = Math.min(count, pushedStyleVars); + if (count == 0) return; + + ImGui.popStyleVar(count); + pushedStyleVars -= count; + } + +} diff --git a/src/client/java/com/moulberry/flashback/ui/Keybinds.java b/src/client/java/com/moulberry/flashback/ui/Keybinds.java new file mode 100644 index 0000000..c452dfa --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/Keybinds.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.ui; + +public class Keybinds { + + + +} diff --git a/src/client/java/com/moulberry/flashback/ui/ReplayUI.java b/src/client/java/com/moulberry/flashback/ui/ReplayUI.java new file mode 100644 index 0000000..334fd10 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/ReplayUI.java @@ -0,0 +1,674 @@ +package com.moulberry.flashback.ui; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.platform.TextureUtil; +import com.mojang.blaze3d.platform.Window; +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.exporting.ExportJob; +import com.moulberry.flashback.ui.windows.Timeline; +import imgui.*; +import imgui.flag.*; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.ProgressScreen; +import net.minecraft.client.gui.screens.ReceivingLevelScreen; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.GameType; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector4f; +import org.lwjgl.glfw.GLFW; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class ReplayUI { + + public static final CustomImGuiImplGlfw imguiGlfw = new CustomImGuiImplGlfw(); + private static final CustomImGuiImplGl3 imguiGl3 = new CustomImGuiImplGl3(); + private static boolean initialized = false; + private static boolean enabled = false; + + private static boolean isFrameHovered = false; + public static int frameX = 0; + public static int frameY = 0; + public static int frameWidth = 1; + public static int frameHeight = 1; + private static boolean activeLastFrame = false; + + public static Matrix4f lastProjectionMatrix = null; + public static Quaternionf lastViewQuaternion = null; + + private static ImFont font = null; + public static ImFont icons = null; + + private static String languageCode = null; + private static boolean wasNavClose = false; + private static boolean navClose = false; + + private static final Lock deferredCloseLock = new ReentrantLock(); + private static final IntList deferredCloseTextureIds = new IntArrayList(); + private static final List deferredClose = new ArrayList<>(); + + private static float globalScale = 1.0f; + public static float newGlobalScale = 1.0f; + private static float contentScale = 1.0f; + + public static void init() { + if (initialized) { + throw new IllegalStateException("EditorUI initialized twice"); + } + initialized = true; + + // todo: + // newGlobalScale = globalScale = Configuration.internal.globalScale; + + // Initialize config so that everything starts nicely docked + + // todo: +// Path path = Axiom.getInstance().getConfigDirectory().resolve("imgui.ini"); +// if (!Files.exists(path)) { +// try { +// Files.write(path, InternalConfiguration.DEFAULT_LAYOUT.getBytes()); +// } catch(IOException ignored) {} +// } + + ImGui.createContext(); + + // todo: +// Path relativePath = FabricLoader.getInstance().getGameDir().relativize(path); +// Axiom.dbg("Using DearImGui config: " + relativePath); +// ImGui.getIO().setIniFilename(relativePath.toString()); + + ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); + ImGui.getIO().addConfigFlags(ImGuiConfigFlags.DockingEnable); + // ImGui.getIO().addConfigFlags(ImGuiConfigFlags.ViewportsEnable); + ImGui.getIO().setConfigMacOSXBehaviors(Minecraft.ON_OSX); + + imguiGlfw.init(Minecraft.getInstance().getWindow().getWindow(), true); + imguiGl3.init("#version 150"); + +// contentScale = imguiGlfw.contentScale; + initFonts(languageCode); + } + + public static void initFonts(String languageCode) { + if (languageCode != null) { + ReplayUI.languageCode = languageCode; + } else { + languageCode = "en_us"; + } + + if (!initialized) { + return; + } + + ImGuiIO io = ImGui.getIO(); + ImFontAtlas fonts = io.getFonts(); + fonts.clear(); + + int size = (int)(16 * getUiScale()); + + ImFontGlyphRangesBuilder rangesBuilder = new ImFontGlyphRangesBuilder(); + rangesBuilder.addRanges(fonts.getGlyphRangesDefault()); + + if (languageCode.startsWith("uk") || languageCode.startsWith("ru") || languageCode.startsWith("bg")) { + rangesBuilder.addRanges(fonts.getGlyphRangesCyrillic()); + } else if (languageCode.startsWith("tr")) { + rangesBuilder.addText("ÇçĞğİıÖöŞşÜü"); + } else if (languageCode.startsWith("pl")) { + rangesBuilder.addRanges(new short[]{0x0100, 0x017F, 0}); + } else if (languageCode.startsWith("cs")) { + rangesBuilder.addText("ÁáČčĎďÉéĚěÍíŇňÓóŘřŠšŤťÚúŮůÝýŽž"); + } + + rangesBuilder.addChar('\u2318'); // Mac CMD + rangesBuilder.addChar('\u2303'); // CTRL + rangesBuilder.addChar('\u2387'); // Alt + rangesBuilder.addChar('\u21E7'); // Shift (up arrow) + rangesBuilder.addChar('\u2756'); // Super + rangesBuilder.addChar('\u26A0'); // Warning symbol + rangesBuilder.addChar('\u2190'); // Left Arrow + rangesBuilder.addChar('\u2191'); // Up Arrow + rangesBuilder.addChar('\u2192'); // Right Arrow + rangesBuilder.addChar('\u2193'); // Down Arrow + + // Make sure every printable key on the keyboard is present + for (int i = GLFW.GLFW_KEY_SPACE; i <= GLFW.GLFW_KEY_LAST; i++) { + int scancode = GLFW.glfwGetKeyScancode(i); + if (scancode != -1) { + String key = GLFW.glfwGetKeyName(i, -1); + if (key != null) { + rangesBuilder.addText(key); + rangesBuilder.addText(key.toLowerCase()); + rangesBuilder.addText(key.toUpperCase()); + rangesBuilder.addText(key.toLowerCase(Locale.ROOT)); + rangesBuilder.addText(key.toUpperCase(Locale.ROOT)); + } + } + } + + short[] glyphRanges = rangesBuilder.buildRanges(); + + // Font config for additional fonts + final ImFontConfig fontConfig = new ImFontConfig(); + fontConfig.setOversampleH(2); + fontConfig.setOversampleV(2); + + fontConfig.setName("Inter (Medium), 16px"); + font = fonts.addFontFromMemoryTTF(loadFont("inter-medium.ttf"), size, fontConfig, glyphRanges); + + // Merge in Japanese/Korean/Chinese/etc. characters if needed + fontConfig.setMergeMode(true); + if (languageCode.startsWith("he")) { + short[] hebrewRanges = new short[]{(short)'\u0590', (short)'\u05FF', (short)'\uFB1D', (short)'\uFB4F', 0}; + io.getFonts().addFontFromMemoryTTF(loadFont("heebo-medium.ttf"), size, fontConfig, hebrewRanges); + } else if (languageCode.startsWith("ja")) { + io.getFonts().addFontFromMemoryTTF(loadFont("notosansjp-medium.ttf"), size, + fontConfig, GlyphRanges.getJapaneseRanges()); + } else if (languageCode.startsWith("zh")) { + io.getFonts().addFontFromMemoryTTF(loadFont("notosanssc-medium.otf"), size, + fontConfig, GlyphRanges.getChineseFullRanges()); + io.getFonts().addFontFromMemoryTTF(loadFont("notosanstc-medium.otf"), size, + fontConfig, GlyphRanges.getChineseFullRanges()); + } + fontConfig.setMergeMode(false); + + fonts.build(); + imguiGl3.updateFontsTexture(); + + fontConfig.destroy(); + fonts.clearTexData(); + } + + private static byte[] loadFont(String name) { + try { + var resource = Minecraft.getInstance().getResourceManager().getResource(new ResourceLocation("flashback", name)); + if (resource.isEmpty()) throw new MissingResourceException("Missing font: " + name, "Font", ""); + try (InputStream is = resource.get().open()) { + return is.readAllBytes(); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static Vec3 getMouseForwardsVector() { + return getMouseForwardsVector(ImGui.getMousePosX(), ImGui.getMousePosY()); + } + + public static Vec3 getMouseForwardsVector(float mouseX, float mouseY) { + if (!isActive() || (!isFrameHovered && !isMovingCamera()) || lastProjectionMatrix == null || lastViewQuaternion == null) return null; + return getForwardsVector(mouseX, mouseY); + } + + public static Vec2 getMouseViewportFraction() { + float x = (ImGui.getMousePosX() - ImGui.getMainViewport().getPosX() - frameX) / frameWidth; + float y = (ImGui.getMousePosY() - ImGui.getMainViewport().getPosY() - frameY) / frameHeight; + return new Vec2(x, y); + } + + public static Vec2 getMouseViewportFraction(float mouseX, float mouseY) { + float x = (mouseX - ImGui.getMainViewport().getPosX() - frameX) / frameWidth; + float y = (mouseY - ImGui.getMainViewport().getPosY() - frameY) / frameHeight; + return new Vec2(x, y); + } + + public static Vec3 getForwardsVector(float mouseX, float mouseY) { + float x = (mouseX - ImGui.getMainViewport().getPosX() - frameX) / frameWidth * 2 - 1; + float y = (mouseY - ImGui.getMainViewport().getPosY() - frameY) / frameHeight * 2 - 1; + return getForwardsVectorRaw(x, y); + } + + public static Vec3 getForwardsVectorRaw(float x, float y) { + if (!isMovingCamera() && (x < -1 || x > 1 || y < -1 || y > 1)) return null; + + var matrix = new Matrix4f(lastProjectionMatrix); + matrix.invert(); + + // Apply inverse projection matrix to get forwards vector + var forwards = new Vector4f(x, y, 0f, 1f); + forwards.mul(matrix); + + // Negate and normalize to match MC coordinate space + //#if MC>=12100 + return new Vec3(forwards.x(), -forwards.y(), forwards.z()).normalize(); + //#else + //$$ return new Vec3(-forwards.x(), -forwards.y(), -forwards.z()).normalize(); + //#endif + } + + public static Vec3 getMouseLookVectorFromForwards(Vec3 forwards) { + if (forwards == null) return null; + + // Apply the view quaternion to forwards vector to get view vector + var view = forwards.toVector3f(); + view.rotate(lastViewQuaternion); + + return new Vec3(view.x(), view.y(), view.z()).normalize(); + } + + public static Vec3 getMouseLookVector(float mouseX, float mouseY) { + return getMouseLookVectorFromForwards(getMouseForwardsVector(mouseX, mouseY)); + } + + public static Vec3 getMouseLookVector() { + return getMouseLookVectorFromForwards(getMouseForwardsVector()); + } + + public static boolean isMovingCamera() { + return imguiGlfw.isGrabbed() && imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME; + } + + public static void setupMainViewport() { + var window = Minecraft.getInstance().getWindow(); + + int frameBottom = (int) ImGui.getMainViewport().getSizeY() - (frameY + frameHeight); + GlStateManager._viewport(frameX * window.getWidth() / window.getScreenWidth(), + frameBottom * window.getHeight() / window.getScreenHeight(), + Math.max(1, frameWidth * window.getWidth() / window.getScreenWidth()), + Math.max(1, frameHeight * window.getHeight() / window.getScreenHeight())); + } + + public static float getUiScale() { + return globalScale * contentScale; + } + + public static double getNewMouseX(double x) { + return x - frameX; + } + + public static double getNewMouseY(double y) { + return y - frameY; + } + + public static int getNewGameWidth(float scale) { + return Math.max(1, Math.round(frameWidth * scale)); + } + + public static int getNewGameHeight(float scale) { + return Math.max(1, Math.round(frameHeight * scale)); + } + + private static boolean isActiveInternal() { + if (!FlashbackClient.isInReplay() || !enabled) { + return false; + } + + if (FlashbackClient.EXPORT_JOB != null) { + return false; + } + + MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode; + if (gameMode == null) return false; + if (gameMode.getPlayerMode() != GameType.SPECTATOR) return false; + if (Minecraft.getInstance().level == null) return false; + if (Minecraft.getInstance().player == null) return false; + if (Minecraft.getInstance().getOverlay() != null) return false; + return true; + } + + public static void enable() { + enabled = true; + } + + public static void disable() { + enabled = false; + } + + public static void toggleEnabled() { + enabled = !enabled; + } + + public static void deferredCloseTextureId(int textureId) { + deferredCloseLock.lock(); + try { + deferredCloseTextureIds.add(textureId); + } finally { + deferredCloseLock.unlock(); + } + } + + public static void deferredClose(AutoCloseable autoCloseable) { + deferredCloseLock.lock(); + try { + deferredClose.add(autoCloseable); + } finally { + deferredCloseLock.unlock(); + } + } + + public static boolean isEnabled() { + return enabled; + } + + public static boolean isActive() { + return activeLastFrame; + } + + private static void transitionActiveState(boolean active) { + if (activeLastFrame == active) return; + activeLastFrame = active; + + // Recalculate the size of the gameplay window + Window window = Minecraft.getInstance().getWindow(); + if (window.getWidth() > 0 && window.getWidth() <= 32768 && window.getHeight() > 0 && window.getHeight() <= 32768) { + Minecraft.getInstance().resizeDisplay(); + } + imguiGlfw.ungrab(); + + if (!activeLastFrame) { + // Make sure the vanilla grab state is correct + if (Minecraft.getInstance().gameMode != null) { + if (Minecraft.getInstance().screen == null) { + Minecraft.getInstance().mouseHandler.releaseMouse(); + Minecraft.getInstance().mouseHandler.grabMouse(); + } else { + Minecraft.getInstance().mouseHandler.grabMouse(); + Minecraft.getInstance().mouseHandler.releaseMouse(); + } + Minecraft.getInstance().mouseHandler.setIgnoreFirstMove(); + } + } else { + // Forcefully ungrab the cursor + long handle = ImGui.getMainViewport().getPlatformHandle(); + if (GLFW.glfwGetInputMode(handle, GLFW.GLFW_CURSOR) != GLFW.GLFW_CURSOR_NORMAL) { + GLFW.glfwSetInputMode(handle, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL); + GLFW.glfwSetCursorPos(handle, ImGui.getMainViewport().getSizeX()/2f, ImGui.getMainViewport().getSizeY()/2f); + } + } + + imguiGlfw.setViewportWindowsHidden(!activeLastFrame); + } + + public static void drawOverlay() { + int oldFrameX = frameX; + int oldFrameY = frameY; + int oldFrameWidth = frameWidth; + int oldFrameHeight = frameHeight; + + if (!initialized) { + throw new IllegalStateException("Tried to use EditorUI while it was not initialized"); + } + + deferredCloseLock.lock(); + try { + for (int id : deferredCloseTextureIds) { + TextureUtil.releaseTextureId(id); + } + deferredCloseTextureIds.clear(); + + for (AutoCloseable closeable : deferredClose) { + try { + closeable.close(); + } catch (Exception e) {} + } + deferredClose.clear(); + } finally { + deferredCloseLock.unlock(); + } + + if (Minecraft.getInstance().screen instanceof ProgressScreen || Minecraft.getInstance().screen instanceof ReceivingLevelScreen) { + return; + } + + enabled = true; + + if (!isActiveInternal()) { + transitionActiveState(false); + if (!FlashbackClient.isInReplay()) { + enabled = false; + } + imguiGlfw.updateReleaseAllKeys(true); + return; + } else { + imguiGlfw.updateReleaseAllKeys(false); + } + + if (!ImGui.isAnyMouseDown()) { + newGlobalScale = ((int)(newGlobalScale * 16))/16f; + if (newGlobalScale < 0.25) newGlobalScale = 0.25f; + if (newGlobalScale > 4) newGlobalScale = 4f; + + float newContentScale = ((int)(imguiGlfw.contentScale * 16))/16f; + if (newContentScale < 0.125) newContentScale = 0.125f; + if (newContentScale > 8) newContentScale = 8f; + + if (globalScale != newGlobalScale || contentScale != newContentScale) { + int oldFontSize = (int)(16 * getUiScale()); + globalScale = newGlobalScale; + contentScale = newContentScale; + if (oldFontSize != (int)(16 * getUiScale())) { + // todo: + // Axiom.dbg("Resizing EditorUI fonts from: " + oldFontSize + " to: " + (int)(16 * getUiScale())); + initFonts(languageCode); + } + } + } + + imguiGlfw.newFrame(); + ImGui.newFrame(); + + navClose = ImGui.getIO().getNavInputs(ImGuiNavInput.Cancel) != 0; + if (wasNavClose != navClose) { + wasNavClose = navClose; + } else if (wasNavClose) { + navClose = false; + } + + if (ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { + ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); + } else { + ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); + } + + char controlIcon = Minecraft.ON_OSX ? '\u2318' : '\u2303'; + + // todo: + // MainMenuBar.render(); + if (ImGui.beginMainMenuBar()) { + if (ImGui.menuItem("Hello")) { + FlashbackClient.EXPORT_JOB = new ExportJob(20, 100); + } + + ImGui.endMainMenuBar(); + } + + // Setup docking + ImGui.setNextWindowBgAlpha(0); + int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode); + imgui.internal.ImGui.dockBuilderGetCentralNode(mainDock).addLocalFlags(imgui.internal.flag.ImGuiDockNodeFlags.NoTabBar); + + isFrameHovered = false; + ImGui.setNextWindowDockID(mainDock); + ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); + + boolean fireCancelNavInput = false; + + if (ImGui.begin("Main", ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoNavInputs | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoCollapse | + ImGuiWindowFlags.NoSavedSettings)) { + ImGuiHelper.popStyleVar(); + + float minX = ImGui.getWindowContentRegionMinX(); + float maxX = ImGui.getWindowContentRegionMaxX(); + float minY = ImGui.getWindowContentRegionMinY(); + float maxY = ImGui.getWindowContentRegionMaxY(); + + if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { + frameX = (int) (ImGui.getWindowPosX() - ImGui.getWindowViewport().getPosX() + minX); + frameY = (int) (ImGui.getWindowPosY() - ImGui.getWindowViewport().getPosY() + minY); + } else { + frameX = (int) (ImGui.getWindowPosX() + minX); + frameY = (int) (ImGui.getWindowPosY() + minY); + } + frameWidth = (int) Math.max(1, maxX - minX); + frameHeight = (int) Math.max(1, maxY - minY); + + if (true) { + float aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY(); + + float currentAspectRatio = frameWidth / (float) frameHeight; + + if (currentAspectRatio < aspectRatio) { + int newHeight = (int)(frameWidth / aspectRatio); + frameY += (frameHeight - newHeight)/2; + frameHeight = newHeight; + } else if (currentAspectRatio > aspectRatio) { + int newWidth = (int)(frameHeight * aspectRatio); + frameX += (frameWidth - newWidth)/2; + frameWidth = newWidth; + } + } + + if (frameX != oldFrameX || frameY != oldFrameY || frameWidth != oldFrameWidth || frameHeight != oldFrameHeight) { + Minecraft.getInstance().resizeDisplay(); + } + + if (ImGui.isWindowHovered() && ImGui.getMousePosY() > ImGui.getWindowPosY()) { + isFrameHovered = true; + + if (Minecraft.getInstance().screen != null) { + ImGui.captureMouseFromApp(false); + } else { + if (ImGui.getIO().getWantCaptureMouse() && !isMovingCamera()) { +// if (!adjustSpeed) { +// handleScroll(); +// } + fireCancelNavInput |= handleBasicInputs(); + } + } + } + } else { + ImGuiHelper.popStyleVar(); + } + ImGui.end(); + + // VisualsWindow.render(); + Timeline.render(); + + if (ImGui.begin("There")) { + ImGui.text("Hello!"); + } + ImGui.end(); + + ImGui.render(); + ImGuiHelper.endFrame(); + + if (fireCancelNavInput) { + ImGui.getIO().setNavInputs(ImGuiNavInput.Input, 1.0f); + ImGui.getIO().setNavInputs(ImGuiNavInput.Cancel, 1.0f); + } + + long ctx = GLFW.glfwGetCurrentContext(); + ImGui.updatePlatformWindows(); + ImGui.renderPlatformWindowsDefault(); + GLFW.glfwMakeContextCurrent(ctx); + + var drawData = ImGui.getDrawData(); + if (drawData != null) { + imguiGl3.renderDrawData(drawData); + } + + transitionActiveState(true); + } + + public static boolean isMainFrameHovered() { + return isFrameHovered; + } + + private static boolean handleBasicInputs() { +// if (ImGui.isMouseClicked(ImGuiMouseButton.Left) && UserAction.LEFT_MOUSE.call(null) == UserAction.ActionResult.USED_STOP) { +// return true; +// } + + if (ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_LEFT)) { + int key = -GLFW.GLFW_MOUSE_BUTTON_LEFT-1; + if (key != 0) { + imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); + } + return true; + } + +// if (Keybinds.ADJUST_RADIUS.isPressed(false)) { +// if (ToolManager.isToolActive() && ToolManager.getCurrentTool().initiateAdjustment()) { +// int key = Keybinds.ADJUST_RADIUS.getKey(); +// if (key != 0) { +// imguiGlfw.setGrabbed(false, key, -1, -1); +// } +// +// adjustingTool = true; +// adjustingToolOffsetX = 0; +// adjustingToolOffsetY = 0; +// +// return true; +// } +// } else if (Keybinds.ROTATE_CAMERA.isPressed(false)) { +// movementControls = EditorMovementControls.rotate(); +// return true; +// } else if (Keybinds.PICK_BLOCK.isPressed(false)) { +// RayCaster.RaycastResult result = Tool.raycastBlock(); +// if (result != null) { +// BlockState blockState = Minecraft.getInstance().level.getBlockState(result.blockPos()); +// CustomBlockState customBlockState = ServerCustomBlocks.getCustomStateFor(blockState); +// activeBlockHistory.setActive(Objects.requireNonNullElse(customBlockState, (CustomBlockState) blockState)); +// return true; +// } +// } else if (Keybinds.USE_TOOL.isPressed(false)) { +// if (UserAction.RIGHT_MOUSE.call(null) != UserAction.ActionResult.NOT_HANDLED || ToolManager.isToolActive()) { +// return true; +// } +// } else if (Keybinds.ARCBALL_CAMERA.isPressed(false)) { +// Tool currentTool = ToolManager.isToolActive() ? ToolManager.getCurrentTool() : null; +// if (currentTool instanceof RulerTool || currentTool instanceof ModifyTool || Configuration.keybind.useCenterOfScreenForArcball) { +// movementControls = EditorMovementControls.arcballFromRaycast(); +// if (movementControls != EditorMovementControls.none()) { +// int key = Keybinds.ARCBALL_CAMERA.getKey(); +// if (key != 0) { +// imguiGlfw.setGrabbed(false, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); +// } +// return true; +// } +// } else { +// pendingDepthActions.add(PendingDepthAction.ARCBALL); +// return true; +// } +// } else if (Keybinds.PAN_CAMERA.isPressed(false)) { +// movementControls = EditorMovementControls.pan(); +// return true; +// } + +// if (Keybinds.CROSSHAIR_CAMERA.isPressed(false)) { +// int key = Keybinds.CROSSHAIR_CAMERA.getKey(); +// if (key != 0) { +// imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); +// } +// return true; +// } + return false; + } + + public static boolean consumeNavClose() { + boolean navClose = ReplayUI.navClose; + ReplayUI.navClose = false; + return navClose; + } + + public static boolean isMoveQuickDown() { + return ImGui.isKeyDown(Minecraft.getInstance().options.keySprint.key.getValue()); + } + + public static boolean isCtrlOrCmdDown() { + return Minecraft.ON_OSX ? ImGui.getIO().getKeySuper() : ImGui.getIO().getKeyCtrl(); + } + +} diff --git a/src/client/java/com/moulberry/flashback/ui/windows/Timeline.java b/src/client/java/com/moulberry/flashback/ui/windows/Timeline.java new file mode 100644 index 0000000..e005b48 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/windows/Timeline.java @@ -0,0 +1,774 @@ +package com.moulberry.flashback.ui.windows; + +import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.Keyframes; +import com.moulberry.flashback.keyframe.impl.CameraKeyframe; +import com.moulberry.flashback.keyframe.impl.FOVKeyframe; +import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; +import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.ui.ImGuiHelper; +import imgui.ImDrawList; +import imgui.ImGui; +import imgui.flag.ImGuiMouseButton; +import imgui.flag.ImGuiMouseCursor; +import imgui.flag.ImGuiPopupFlags; +import imgui.flag.ImGuiStyleVar; +import net.minecraft.client.Minecraft; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.TreeMap; + +public class Timeline { + + private static float zoomMin = 0.5f; + private static float zoomMax = 1.0f; + private static float zoomMinBeforeDrag = zoomMin; + private static float zoomMaxBeforeDrag = zoomMax; + private static boolean grabbedZoomBar = false; + private static boolean grabbedZoomBarResizeLeft = false; + private static boolean grabbedZoomBarResizeRight = false; + private static boolean grabbedPlayback = false; + private static boolean grabbedKeyframe = false; + + private static float[] speedKeyframeInput = new float[]{1.0f}; + private static int[] timeOfDayKeyframeInput = new int[]{6000}; + private static float[] fogDistanceKeyframeInput = new float[]{256.0f}; + + private record SelectedKeyframe(KeyframeType type, int keyframeTick, float mouseClickOffset) {} + private static SelectedKeyframe selectedKeyframe = null; + + private static final float[] replayTickSpeeds = new float[]{ + 1.0f, + 2.0f, + 4.0f, + 10.0f, + 20.0f, + 40.0f, + 100.0f, + 200.0f, + 400.0f + }; + + private static final int KEYFRAME_SIZE = 10; + + public static void render() { + ReplayServer replayServer = FlashbackClient.getReplayServer(); + if (replayServer == null) { + return; + } + + ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); + boolean timelineVisible = ImGui.begin("Timeline"); + ImGuiHelper.popStyleVar(); + + if (timelineVisible) { + ImDrawList drawList = ImGui.getWindowDrawList(); + + float maxX = ImGui.getWindowContentRegionMaxX(); + float maxY = ImGui.getWindowContentRegionMaxY(); + float minX = ImGui.getWindowContentRegionMinX(); + float minY = ImGui.getWindowContentRegionMinY(); + + float x = ImGui.getWindowPosX() + minX; + float y = ImGui.getWindowPosY() + minY; + float width = maxX - minX; + float height = maxY - minY; + + if (width < 1 || height < 1) { + ImGui.end(); + return; + } + + if (selectedKeyframe != null) { + TreeMap> keyframeTimes = Keyframes.keyframes.get(selectedKeyframe.type); + if (keyframeTimes == null) { + selectedKeyframe = null; + } else if (keyframeTimes.get(selectedKeyframe.keyframeTick) == null) { + selectedKeyframe = null; + } + } + + float mouseX = ImGui.getMousePosX(); + float mouseY = ImGui.getMousePosY(); + + int currentReplayTick = replayServer.getReplayTick(); + int totalTicks = Math.max(replayServer.getTotalReplayTicks(), currentReplayTick); + + int middleX = 240; + + float availableWidth = width - middleX; + float shownTicks = Math.round((zoomMax - zoomMin) * totalTicks); + int targetMajorSize = 60; + + float targetTicksPerMajor = 1f / (availableWidth / shownTicks / targetMajorSize); + int minorsPerMajor; + int ticksPerMinor; + boolean showSubSeconds; + + if (targetTicksPerMajor < 5) { + minorsPerMajor = 5; + ticksPerMinor = 1; + showSubSeconds = true; + } else if (targetTicksPerMajor < 8) { + minorsPerMajor = 5; + ticksPerMinor = 2; + showSubSeconds = true; + } else { + minorsPerMajor = 4; + ticksPerMinor = (int) Math.ceil(targetTicksPerMajor / 20 ) * 20 / minorsPerMajor; + showSubSeconds = false; + } + + int majorSnap = ticksPerMinor * minorsPerMajor; + int minTicks = Math.round(zoomMin * totalTicks / majorSnap) * majorSnap; + float minorSeparatorWidth = (availableWidth / shownTicks) * ticksPerMinor; + + float error = zoomMin*totalTicks - minTicks; + int errorOffset = (int)(-error/ticksPerMinor*minorSeparatorWidth); + + float availableTicks = availableWidth / minorSeparatorWidth * ticksPerMinor; + + int cursorTicks = currentReplayTick; + if (grabbedPlayback) { + cursorTicks = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); + } else if (replayServer.jumpToTick >= 0) { + cursorTicks = replayServer.jumpToTick; + } + + int cursorX = middleX + (int)((cursorTicks - minTicks)/availableTicks*(width-middleX)) + errorOffset; + int minorSeparatorHeight = 10; + int majorSeparatorHeight = minorSeparatorHeight * 2; + int timestampHeight = 20; + int middleY = timestampHeight+majorSeparatorHeight; + + renderKeyframeElements(replayServer, x, y + middleY, cursorTicks, middleX); + + float zoomBarWidth = width - (middleX+1); + float zoomBarMin = x+middleX+1 + zoomMin*zoomBarWidth; + float zoomBarMax = x+middleX+1 + zoomMax*zoomBarWidth; + + int zoomBarHeight = 6; + boolean zoomBarExpanded = false; + if (mouseY >= y+height-zoomBarHeight*2 && mouseY <= y+height || grabbedZoomBar) { + zoomBarHeight *= 2; + zoomBarExpanded = true; + } + boolean zoomBarHovered = mouseY >= y+height-zoomBarHeight && mouseY <= y+height && + mouseX >= x+zoomBarMin && mouseX <= x+zoomBarMax; + + drawList.pushClipRect(x+middleX, y, x+width, y+height); + + renderKeyframes(x, y + middleY, mouseX, minTicks, availableTicks, middleX, width, errorOffset); + drawSeparators(minorsPerMajor, x, middleX, minorSeparatorWidth, errorOffset, width, drawList, y, timestampHeight, middleY, minTicks, ticksPerMinor, showSubSeconds, majorSeparatorHeight, minorSeparatorHeight); + drawPlaybackHead(cursorX, x, middleX, width, cursorTicks, currentReplayTick, drawList, y, middleY, timestampHeight, height, zoomBarHeight); + + drawList.popClipRect(); + + // Timeline end line + if (zoomMax >= 1.0) { + drawList.addLine(x+width-2, y+timestampHeight, x+width-2, y+height-zoomBarHeight, -1); + } + // Middle divider (x) + drawList.addLine(x+middleX, y+timestampHeight, x+middleX, y+height, -1); + + // Middle divider (y) + drawList.addLine(0, y+middleY, width, y+middleY, -1); + + // Zoom Bar + if (zoomBarExpanded) { + drawList.addRectFilled(x+middleX+1, y+height-zoomBarHeight, x+width, y+height, 0xFF404040, zoomBarHeight); + } + if (zoomBarHovered || grabbedZoomBar) { + drawList.addRectFilled(x+zoomBarMin+zoomBarHeight/2f, y+height-zoomBarHeight, x+zoomBarMax-zoomBarHeight/2f, y+height, -1, zoomBarHeight); + + // Left/right resize + drawList.addCircleFilled(x+zoomBarMin+zoomBarHeight/2f, y+height-zoomBarHeight/2f, zoomBarHeight/2f, 0xffaaaa00); + drawList.addCircleFilled(x+zoomBarMax-zoomBarHeight/2f, y+height-zoomBarHeight/2f, zoomBarHeight/2f, 0xffaaaa00); + } else { + drawList.addRectFilled(x+zoomBarMin, y+height-zoomBarHeight, x+zoomBarMax, y+height, -1, zoomBarHeight); + } + + // Pause/play button + int controlSize = 24; + int controlsY = (int) y + middleY/2 - controlSize /2; + + // Skip backwards + int skipBackwardsX = (int) x + middleX/6 - controlSize/2; + drawList.addTriangleFilled(skipBackwardsX + controlSize/3, controlsY + controlSize/2, + skipBackwardsX + controlSize, controlsY, + skipBackwardsX + controlSize, controlsY + controlSize, -1); + drawList.addRectFilled(skipBackwardsX, controlsY, + skipBackwardsX + controlSize/3, controlsY+controlSize, -1); + + // Slow down + int slowDownX = (int) x + middleX*2/6 - controlSize/2; + drawList.addTriangleFilled(slowDownX, controlsY + controlSize/2, + slowDownX + controlSize/2, controlsY, + slowDownX + controlSize/2, controlsY+controlSize, -1); + drawList.addTriangleFilled(slowDownX + controlSize/2, controlsY + controlSize/2, + slowDownX + controlSize, controlsY, + slowDownX + controlSize, controlsY + controlSize, -1); + + int pauseX = (int) x + middleX/2 - controlSize /2; + if (replayServer.replayPaused) { + // Play button + drawList.addTriangleFilled(pauseX + controlSize/12, controlsY, + pauseX + controlSize, controlsY + controlSize/2, + pauseX + controlSize/12, controlsY + controlSize, + -1); + } else { + // Pause button + drawList.addRectFilled(pauseX, controlsY, + pauseX + controlSize/3, controlsY + controlSize, -1); + drawList.addRectFilled(pauseX + controlSize*2/3, controlsY, + pauseX + controlSize, controlsY + controlSize, -1); + } + + // Fast-forward + int fastForwardsX = (int) x + middleX*4/6 - controlSize/2; + drawList.addTriangleFilled(fastForwardsX, controlsY, + fastForwardsX + controlSize/2, controlsY + controlSize/2, + fastForwardsX, controlsY+controlSize, -1); + drawList.addTriangleFilled(fastForwardsX + controlSize/2, controlsY, + fastForwardsX + controlSize, controlsY + controlSize/2, + fastForwardsX + controlSize/2, controlsY + controlSize, -1); + + // Skip forward + int skipForwardsX = (int) x + middleX*5/6 - controlSize/2; + drawList.addTriangleFilled(skipForwardsX, controlsY, + skipForwardsX + controlSize*2/3, controlsY + controlSize/2, + skipForwardsX, controlsY + controlSize, -1); + drawList.addRectFilled(skipForwardsX + controlSize*2/3, controlsY, + skipForwardsX + controlSize, controlsY+controlSize, -1); + + + boolean hoveredControls = mouseY > controlsY && mouseY < controlsY + controlSize; + boolean hoveredSkipBackwards = hoveredControls && mouseX >= skipBackwardsX && mouseX <= skipBackwardsX+controlSize; + boolean hoveredSlowDown = hoveredControls && mouseX >= slowDownX && mouseX <= slowDownX+controlSize; + boolean hoveredPause = hoveredControls && mouseX >= pauseX && mouseX <= pauseX+controlSize; + boolean hoveredFastForwards = hoveredControls && mouseX >= fastForwardsX && mouseX <= fastForwardsX+controlSize; + boolean hoveredSkipForwards = hoveredControls && mouseX >= skipForwardsX && mouseX <= skipForwardsX+controlSize; + + if (hoveredSkipBackwards) { + ImGuiHelper.drawTooltip("Skip backwards"); + } else if (hoveredSlowDown) { + ImGuiHelper.drawTooltip("Slow down\n(Current speed: " + (replayServer.desiredTickRate/20f) + "x)"); + } else if (hoveredPause) { + if (replayServer.replayPaused) { + ImGuiHelper.drawTooltip("Start replay"); + } else { + ImGuiHelper.drawTooltip("Pause replay"); + } + } else if (hoveredFastForwards) { + ImGuiHelper.drawTooltip("Fast-forwards\n(Current speed: " + (replayServer.desiredTickRate/20f) + "x)"); + } else if (hoveredSkipForwards) { + ImGuiHelper.drawTooltip("Skip forwards"); + } + + renderKeyframeOptionsPopup(); + + boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); + boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); + if ((leftClicked || rightClicked) && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { + releaseGrabbed(mouseX, middleX, errorOffset, width, availableTicks, minTicks, replayServer); + selectedKeyframe = null; + + if (hoveredControls) { + // Skip backwards + if (hoveredSkipBackwards) { + replayServer.goToReplayTick(0); + } + + // Slow down + if (hoveredSlowDown) { + float highest = replayTickSpeeds[0]; + float currentTickRate = replayServer.desiredTickRate; + + for (float replayTickSpeed : replayTickSpeeds) { + if (replayTickSpeed >= currentTickRate) { + break; + } + highest = replayTickSpeed; + } + + replayServer.desiredTickRate = highest; + } + + // Pause button + if (hoveredPause) { + replayServer.replayPaused = !replayServer.replayPaused; + } + + // Fast-forward + if (hoveredFastForwards) { + float lowest = replayTickSpeeds[replayTickSpeeds.length - 1]; + float currentTickRate = replayServer.desiredTickRate; + + for (int i = replayTickSpeeds.length - 1; i >= 0; i--) { + float replayTickSpeed = replayTickSpeeds[i]; + if (replayTickSpeed <= currentTickRate) { + break; + } + lowest = replayTickSpeed; + } + + replayServer.desiredTickRate = lowest; + } + + // Skip forward + if (hoveredSkipForwards) { + replayServer.goToReplayTick(totalTicks); + } + } + + if (mouseY > y && mouseY < y+middleY) { + // Timeline + if (mouseX > x+middleX && mouseX < x+width) { + replayServer.replayPaused = true; + grabbedPlayback = leftClicked; + } + } + + // Tracks + if (mouseY > y+middleY && mouseY < y+height && mouseX > x+middleX && mouseX < x+width) { + float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); + + int trackIndex = (int) Math.max(0, Math.floor((mouseY - (y+middleY+2))/lineHeight)); + for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { + if (trackIndex == 0) { + TreeMap> treeMap = entry.getValue(); + int tick = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); + + Map.Entry> floor = treeMap.floorEntry(tick); + Map.Entry> ceil = treeMap.ceilingEntry(tick); + + float floorDistance = Float.MAX_VALUE; + + if (floor != null) { + float keyframeX = x + middleX + (floor.getKey() - minTicks)/availableTicks*(width-middleX) + errorOffset; + floorDistance = Math.abs(mouseX - keyframeX); + if (floorDistance < KEYFRAME_SIZE) { + selectedKeyframe = new SelectedKeyframe(entry.getKey(), floor.getKey(), mouseX - keyframeX); + grabbedKeyframe = leftClicked; + } + } + + if (ceil != null) { + float keyframeX = x + middleX + (ceil.getKey() - minTicks)/availableTicks*(width-middleX) + errorOffset; + float ceilDistance = Math.abs(mouseX - keyframeX); + if (ceilDistance < floorDistance && ceilDistance < KEYFRAME_SIZE) { + selectedKeyframe = new SelectedKeyframe(entry.getKey(), ceil.getKey(), mouseX - keyframeX); + grabbedKeyframe = leftClicked; + } + } + + break; + } else { + trackIndex -= 1; + } + } + + if (rightClicked && selectedKeyframe != null) { + ImGui.openPopup("##KeyframePopup"); + } + } + + if (zoomBarHovered) { + if (mouseX <= x+zoomBarMin+zoomBarHeight) { + grabbedZoomBarResizeLeft = leftClicked; + } else if (mouseX >= x+zoomBarMax-zoomBarHeight) { + grabbedZoomBarResizeRight = leftClicked; + } + grabbedZoomBar = leftClicked; + zoomMinBeforeDrag = zoomMin; + zoomMaxBeforeDrag = zoomMax; + } else if (zoomBarExpanded && mouseX >= x+middleX && mouseX <= x+width) { + float zoomSize = zoomMax - zoomMin; + float targetZoom = (mouseX - (x+middleX))/(x+width - (x+middleX)); + zoomMin = targetZoom - zoomSize/2f; + zoomMax = targetZoom + zoomSize/2f; + if (zoomMax > 1.0f) { + zoomMax = 1.0f; + zoomMin = zoomMax - zoomSize; + } else if (zoomMin < 0.0f) { + zoomMin = 0.0f; + zoomMax = zoomMin + zoomSize; + } + + grabbedZoomBar = leftClicked; + zoomMinBeforeDrag = zoomMin; + zoomMaxBeforeDrag = zoomMax; + } + } else if (ImGui.isMouseDragging(ImGuiMouseButton.Left)) { + if (zoomBarWidth > 1f && grabbedZoomBar) { + float dx = ImGui.getMouseDragDeltaX(); + float factor = dx / zoomBarWidth; + + if (grabbedZoomBarResizeLeft) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + zoomMin = Math.max(0, Math.min(zoomMax-0.01f, zoomMinBeforeDrag + factor)); + } else if (grabbedZoomBarResizeRight) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + zoomMax = Math.max(zoomMin+0.01f, Math.min(1, zoomMaxBeforeDrag + factor)); + } else { + ImGui.setMouseCursor(ImGuiMouseCursor.Hand); + + float zoomSize = zoomMaxBeforeDrag - zoomMinBeforeDrag; + if (factor < 0) { + zoomMin = Math.max(0, zoomMinBeforeDrag + factor); + zoomMax = zoomMin + zoomSize; + } else if (factor > 0) { + zoomMax = Math.min(1, zoomMaxBeforeDrag + factor); + zoomMin = zoomMax - zoomSize; + } + } + } + if (grabbedPlayback) { + int desiredTick = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); + + if (desiredTick > currentReplayTick) { + replayServer.goToReplayTick(desiredTick); + } + + replayServer.replayPaused = true; + } + } else if (!ImGui.isAnyMouseDown()) { + releaseGrabbed(mouseX, middleX, errorOffset, width, availableTicks, minTicks, replayServer); + } + } + ImGui.end(); + } + + private static void renderKeyframeOptionsPopup() { + if (ImGui.beginPopup("##KeyframePopup")) { + if (selectedKeyframe == null) { + ImGui.closeCurrentPopup(); + ImGui.endPopup(); + return; + } + + var keyframeTimes = Keyframes.keyframes.get(selectedKeyframe.type); + if (keyframeTimes == null) { + ImGui.closeCurrentPopup(); + ImGui.endPopup(); + return; + } + + Keyframe keyframe = keyframeTimes.get(selectedKeyframe.keyframeTick); + if (keyframe == null) { + ImGui.closeCurrentPopup(); + ImGui.endPopup(); + return; + } + + int[] type = new int[]{keyframe.interpolationType().ordinal()}; + ImGui.setNextItemWidth(160); + if (ImGuiHelper.combo("Type", type, InterpolationType.NAMES)) { + keyframe.interpolationType(InterpolationType.INTERPOLATION_TYPES[type[0]]); + } + + if (ImGui.button("Remove") && selectedKeyframe != null) { + keyframeTimes.remove(selectedKeyframe.keyframeTick); + selectedKeyframe = null; + } + + ImGui.endPopup(); + } + } + + private static void releaseGrabbed(float mouseX, int middleX, int errorOffset, float width, float availableTicks, int minTicks, ReplayServer replayServer) { + grabbedZoomBar = false; + grabbedZoomBarResizeLeft = false; + grabbedZoomBarResizeRight = false; + + if (grabbedPlayback) { + int desiredTick = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); + replayServer.goToReplayTick(desiredTick); + replayServer.replayPaused = true; + grabbedPlayback = false; + } + if (grabbedKeyframe) { + if (selectedKeyframe != null) { + int desiredTick = calculatePlaybackTarget(mouseX - selectedKeyframe.mouseClickOffset, middleX, errorOffset, width, availableTicks, minTicks); + if (desiredTick != selectedKeyframe.keyframeTick) { + var keyframeTimes = Keyframes.keyframes.get(selectedKeyframe.type); + if (keyframeTimes == null) { + selectedKeyframe = null; + } else { + Keyframe keyframe = keyframeTimes.remove(selectedKeyframe.keyframeTick); + if (keyframe == null) { + selectedKeyframe = null; + } else { + Keyframes.keyframes.get(selectedKeyframe.type).put(desiredTick, keyframe); + selectedKeyframe = new SelectedKeyframe(selectedKeyframe.type, desiredTick, 0); + } + } + } + } + grabbedKeyframe = false; + } + } + + + private static void renderKeyframes(float x, float y, float mouseX, int minTicks, float availableTicks, int middleX, float width, int errorOffset) { + float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); + + ImDrawList drawList = ImGui.getWindowDrawList(); + + int index = 0; + for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { + TreeMap> keyframeTimes = entry.getValue(); + + for (int i = minTicks; i <= minTicks + availableTicks; i++) { + Keyframe keyframe = keyframeTimes.get(i); + if (keyframe != null) { + int keyframeX = middleX + (int)((i - minTicks)/availableTicks*(width-middleX)) + errorOffset; + + float midX = x + keyframeX; + float midY = y + 2 + (index+0.5f) * lineHeight; + + if (selectedKeyframe != null && selectedKeyframe.type == entry.getKey() && selectedKeyframe.keyframeTick == i) { + continue; + } + + drawKeyframe(drawList, keyframe.interpolationType(), midX, midY, -1); + } + } + + if (selectedKeyframe != null && selectedKeyframe.type == entry.getKey()) { + Keyframe keyframe = keyframeTimes.get(selectedKeyframe.keyframeTick); + if (keyframe != null) { + int showKeyframeAt = selectedKeyframe.keyframeTick; + if (grabbedKeyframe) { + showKeyframeAt = calculatePlaybackTarget(mouseX - selectedKeyframe.mouseClickOffset, middleX, errorOffset, width, availableTicks, minTicks); + } + int keyframeX = middleX + (int)((showKeyframeAt - minTicks)/availableTicks*(width-middleX)) + errorOffset; + + float midX = x + keyframeX; + float midY = y + 2 + (index+0.5f) * lineHeight; + drawKeyframe(drawList, keyframe.interpolationType(), midX, midY, 0xFF0000FF); + } + } + + index += 1; + } + } + + private static void drawKeyframe(ImDrawList drawList, InterpolationType interpolationType, float x, float y, int colour) { + int easeSize = KEYFRAME_SIZE / 5; + switch (interpolationType) { + case SMOOTH -> { + drawList.addCircleFilled(x, y, KEYFRAME_SIZE, colour); + } + case LINEAR -> { + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y, x, y - KEYFRAME_SIZE, x, y + KEYFRAME_SIZE, colour); + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y, x, y + KEYFRAME_SIZE, x, y - KEYFRAME_SIZE, colour); + } + case EASE_IN -> { + // Left inverted triangle + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y, colour); + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y + KEYFRAME_SIZE, x - easeSize, y, x - easeSize, y + KEYFRAME_SIZE, colour); + // Right triangle + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y - KEYFRAME_SIZE, colour); + // Center + drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); + } + case EASE_OUT -> { + // Left triangle + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y + KEYFRAME_SIZE, colour); + // Right inverted triangle + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + easeSize, y, x + easeSize, y - KEYFRAME_SIZE, colour); + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y, colour); + // Center + drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); + } + case EASE_IN_OUT -> { + // Left inverted triangle + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y, colour); + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y + KEYFRAME_SIZE, x - easeSize, y, x - easeSize, y + KEYFRAME_SIZE, colour); + // Right inverted triangle + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + easeSize, y, x + easeSize, y - KEYFRAME_SIZE, colour); + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y, colour); + // Center + drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); + } + case HOLD -> { + drawList.addRectFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, colour); + } + } + } + + private static void renderKeyframeElements(ReplayServer replayServer, float x, float y, int cursorTicks, int middleX) { + ImGui.setCursorScreenPos(x + 8, y + 6); + + KeyframeType keyframeTypeToClear = null; + + ImDrawList drawList = ImGui.getWindowDrawList(); + + float buttonSize = ImGui.getTextLineHeight(); + float spacingX = ImGui.getStyle().getItemSpacingX(); + + for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { + KeyframeType keyframeType = entry.getKey(); + TreeMap> keyframeTimes = entry.getValue(); + + ImGui.pushID(keyframeType.ordinal()); + + ImGui.setCursorPosX(8); + ImGui.text(keyframeType.name); + + ImGui.sameLine(); + + float addX = middleX - buttonSize - spacingX - buttonSize - spacingX; + float buttonY = ImGui.getCursorScreenPosY(); + ImGui.setCursorPosX(addX); + if (ImGui.button("##Add", buttonSize, buttonSize)) { + Keyframe keyframe = switch (keyframeType) { + case CAMERA -> new CameraKeyframe(Minecraft.getInstance().player); + case FOV -> new FOVKeyframe(Minecraft.getInstance().options.fov().get()); + case SPEED -> { + speedKeyframeInput[0] = replayServer.desiredTickRate / 20.0f; + ImGui.openPopup("##EnterSpeed"); + yield null; + } + case TIME_OF_DAY -> { + timeOfDayKeyframeInput[0] = (int)(Minecraft.getInstance().level.getDayTime() % 24000); + ImGui.openPopup("##EnterTime"); + yield null; + } + }; + if (keyframe != null) { + keyframeTimes.put(cursorTicks, keyframe); + } + } + drawList.addRectFilled(addX + 2, buttonY + buttonSize/2 - 1, addX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); + drawList.addRectFilled(addX + buttonSize/2 - 1, buttonY + 2, addX + buttonSize/2 + 1, buttonY + buttonSize - 2, -1); + ImGuiHelper.tooltip("Add keyframe"); + + if (ImGui.beginPopup("##EnterSpeed")) { + ImGui.sliderFloat("Speed", speedKeyframeInput, 0.1f, 10f); + if (ImGui.button("Add")) { + keyframeTimes.put(cursorTicks, new TickrateKeyframe(speedKeyframeInput[0] * 20.0f)); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + if (ImGui.beginPopup("##EnterTime")) { + ImGui.sliderInt("Time", timeOfDayKeyframeInput, 0, 24000); + if (ImGui.button("Add")) { + keyframeTimes.put(cursorTicks, new TimeOfDayKeyframe(timeOfDayKeyframeInput[0])); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + + ImGui.sameLine(); + + float clearX = middleX - buttonSize - spacingX; + if (ImGui.button("##Clear", buttonSize, buttonSize)) { + keyframeTypeToClear = keyframeType; + } + drawList.addRectFilled(clearX + 2, buttonY + buttonSize/2 - 1, clearX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); + ImGuiHelper.tooltip("Remove all keyframes"); + + ImGui.separator(); + + ImGui.popID(); + } + + if (keyframeTypeToClear != null) { + Keyframes.keyframes.remove(keyframeTypeToClear); + } + + ImGui.setCursorPosX(8); + if (Keyframes.keyframes.size() < KeyframeType.KEYFRAME_TYPES.length && ImGui.smallButton("Add Element")) { + ImGui.openPopup("##AddKeyframeElement"); + } + if (ImGui.beginPopup("##AddKeyframeElement")) { + for (KeyframeType keyframeType : KeyframeType.KEYFRAME_TYPES) { + if (!Keyframes.keyframes.containsKey(keyframeType)) { + if (ImGui.selectable(keyframeType.name)) { + Keyframes.keyframes.put(keyframeType, new TreeMap<>()); + ImGui.closeCurrentPopup(); + } + } + } + ImGui.endPopup(); + } + } + + private static void drawSeparators(int minorsPerMajor, float x, int middleX, float minorSeparatorWidth, int errorOffset, float width, ImDrawList drawList, float y, int timestampHeight, int middleY, int minTicks, int ticksPerMinor, boolean showSubSeconds, int majorSeparatorHeight, int minorSeparatorHeight) { + int minor = -minorsPerMajor; + while (true) { + float h = x + middleX + minorSeparatorWidth *minor; + int hi = (int) (h + errorOffset); + + if (hi >= x + width) { + break; + } + + if (minor % minorsPerMajor == 0) { + drawList.addLine(hi, y + timestampHeight, hi, y + middleY, -1); + + int ticks = minTicks + minor* ticksPerMinor; + String timestamp = ticksToTimestamp(ticks); + drawList.addText(hi, y, -1, timestamp); + if (showSubSeconds) { + float timestampWidth = ImGuiHelper.calcTextWidth(timestamp); + drawList.addText(hi+(int)Math.ceil(timestampWidth), y, 0xFF808080, "/"+(ticks % 20)); + } + } else { + drawList.addLine(hi, y + timestampHeight +(majorSeparatorHeight - minorSeparatorHeight), hi, y + middleY, -1); + } + + minor += 1; + } + } + + private static void drawPlaybackHead(int cursorX, float x, int middleX, float width, int cursorTicks, int currentReplayTick, ImDrawList drawList, float y, int middleY, int timestampHeight, float height, int zoomBarHeight) { + if (cursorX > x + middleX -10 && cursorX < x + width +10) { + int colour = -1; + if (cursorTicks < currentReplayTick) { + colour = 0x80FFFFFF; + } + + drawList.addTriangleFilled(x + cursorX, y + middleY, x + cursorX -10, y + timestampHeight +5, + x + cursorX +10, y + timestampHeight +5, colour); + drawList.addRectFilled(x + cursorX -1, y + middleY -2, x + cursorX +1, y + height - zoomBarHeight, colour); + } + } + + private static int calculatePlaybackTarget(float mouseX, int middleX, int errorOffset, float width, float availableTicks, int minTicks) { + float relativeX = mouseX - middleX - errorOffset; + float amount = Math.max(0, Math.min(1, relativeX/(width - middleX))); + int numTicks = Math.round(amount* availableTicks); + int desiredTick = minTicks + numTicks; + return desiredTick; + } + + private static String ticksToTimestamp(int ticks) { + int seconds = ticks/20; + int minutes = seconds/60; + int hours = minutes/60; + + if (hours == 0) { + return String.format("%02d:%02d", minutes, seconds % 60); + } else { + return String.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/ui/windows/VisualsWindow.java b/src/client/java/com/moulberry/flashback/ui/windows/VisualsWindow.java new file mode 100644 index 0000000..816dfc2 --- /dev/null +++ b/src/client/java/com/moulberry/flashback/ui/windows/VisualsWindow.java @@ -0,0 +1,45 @@ +package com.moulberry.flashback.ui.windows; + +import com.moulberry.flashback.ReplayVisuals; +import imgui.ImGui; + +public class VisualsWindow { + + public static void render() { + if (ImGui.begin("Visuals")) { + if (ImGui.checkbox("Show Boss Bar", ReplayVisuals.showBossBar)) { + ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar; + } + if (ImGui.checkbox("Show Title Text", ReplayVisuals.showTitleText)) { + ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText; + } + if (ImGui.checkbox("Show Scoreboard", ReplayVisuals.showScoreboard)) { + ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard; + } + if (ImGui.checkbox("Show Action Bar", ReplayVisuals.showActionBar)) { + ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar; + } + if (ImGui.checkbox("Show Nametags", ReplayVisuals.showNametags)) { + ReplayVisuals.showNametags = !ReplayVisuals.showNametags; + } + + // Fog distance + boolean overridingFog = ReplayVisuals.overrideFogDistance > 0.0; + if (ImGui.checkbox("Override Fog", overridingFog)) { + if (overridingFog) { + ReplayVisuals.overrideFogDistance = 0.0f; + } else { + ReplayVisuals.overrideFogDistance = 256.0f; + } + } + if (overridingFog) { + float[] fogDistance = new float[]{ReplayVisuals.overrideFogDistance}; + if (ImGui.sliderFloat("Override Fog Distance", fogDistance, 0.0f, 512.0f)) { + ReplayVisuals.overrideFogDistance = fogDistance[0]; + } + } + + } + ImGui.end(); + } +} diff --git a/src/client/resources/assets/flashback/heebo-medium.ttf b/src/client/resources/assets/flashback/heebo-medium.ttf new file mode 100644 index 0000000..3aa8dd0 Binary files /dev/null and b/src/client/resources/assets/flashback/heebo-medium.ttf differ diff --git a/src/client/resources/assets/flashback/inter-medium.ttf b/src/client/resources/assets/flashback/inter-medium.ttf new file mode 100644 index 0000000..b53fb1c Binary files /dev/null and b/src/client/resources/assets/flashback/inter-medium.ttf differ diff --git a/src/client/resources/assets/flashback/notosansjp-medium.ttf b/src/client/resources/assets/flashback/notosansjp-medium.ttf new file mode 100644 index 0000000..1d89aef Binary files /dev/null and b/src/client/resources/assets/flashback/notosansjp-medium.ttf differ diff --git a/src/client/resources/assets/flashback/notosanssc-medium.otf b/src/client/resources/assets/flashback/notosanssc-medium.otf new file mode 100644 index 0000000..0a5bd9e Binary files /dev/null and b/src/client/resources/assets/flashback/notosanssc-medium.otf differ diff --git a/src/client/resources/assets/flashback/notosanstc-medium.otf b/src/client/resources/assets/flashback/notosanstc-medium.otf new file mode 100644 index 0000000..a0811eb Binary files /dev/null and b/src/client/resources/assets/flashback/notosanstc-medium.otf differ diff --git a/src/client/resources/flashback.client.mixins.json b/src/client/resources/flashback.client.mixins.json new file mode 100644 index 0000000..e619265 --- /dev/null +++ b/src/client/resources/flashback.client.mixins.json @@ -0,0 +1,47 @@ +{ + "required": true, + "package": "com.moulberry.flashback.mixin.client", + "compatibilityLevel": "JAVA_21", + "client": [ + "MixinLevelRenderer", + "MixinMinecraft", + "MixinMouseHandler", + "MixinRenderTarget", + "MixinWindow", + "packet_fix.MixinBossHealthOverlay", + "playback.MixinArmorStandRenderer", + "playback.MixinClientCommonPacketListenerImpl", + "playback.MixinGameRenderer", + "playback.MixinItemInHandRenderer", + "record.MixinClientConfigurationPacketListenerImpl", + "ui.MixinTitleScreen", + "visuals.MixinClientLevelData", + "visuals.MixinFogRenderer" + ], + "injectors": { + "defaultRequire": 1 + }, + "mixins": [ + "MixinThreadedLevelLightEngine", + "playback.MixinEntity", + "playback.MixinLevelChunkSection", + "playback.MixinLivingEntity", + "playback.MixinPlayerChunkSender", + "playback.MixinTickRateManager", + "playback.hashing.MixinGlobalPalette", + "playback.hashing.MixinHashMapPalette", + "playback.hashing.MixinLinearPalette", + "playback.hashing.MixinSingleValuePalette", + "record.MixinConnection", + "replay_server.MixinChunkGenerators", + "replay_server.MixinChunkStatusTasks", + "replay_server.MixinPersistentEntitySectionManager", + "replay_server.MixinPlayerList", + "replay_server.MixinServerChunkCache", + "replay_server.MixinServerConfigurationPacketListenerImpl", + "replay_server.MixinServerEntity", + "replay_server.MixinServerGamePacketListenerImpl", + "replay_server.MixinServerLoginPacketListenerImpl", + "replay_server.MixinTickRateManager" + ] +} diff --git a/src/main/resources/assets/flashback/icon.png b/src/main/resources/assets/flashback/icon.png new file mode 100644 index 0000000..047b91f Binary files /dev/null and b/src/main/resources/assets/flashback/icon.png differ diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..63e10ea --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 1, + "id": "flashback", + "version": "${version}", + "name": "Flashback", + "description": "Record and replay the game", + "authors": [ + "Moulberry" + ], + "contact": { + "homepage": "https://flashback.moulberry.com/", + "sources": "https://github.com/Moulberry/Flashback" + }, + "license": "ARR", + "icon": "assets/flashback/icon.png", + "environment": "*", + "entrypoints": { + "client": [ + "com.moulberry.flashback.FlashbackClient" + ] + }, + "mixins": [ + "flashback.mixins.json", + { + "config": "flashback.client.mixins.json", + "environment": "client" + } + ], + "depends": { + "fabricloader": ">=0.15.10", + "minecraft": "~1.20.6", + "java": ">=21", + "fabric-api": "*" + } +} diff --git a/src/main/resources/flashback.accesswidener b/src/main/resources/flashback.accesswidener new file mode 100644 index 0000000..981b111 --- /dev/null +++ b/src/main/resources/flashback.accesswidener @@ -0,0 +1,84 @@ +accessWidener v1 named + +# Client data +accessible class net/minecraft/client/multiplayer/ClientChunkCache$Storage +accessible field net/minecraft/client/multiplayer/ClientChunkCache storage Lnet/minecraft/client/multiplayer/ClientChunkCache$Storage; +accessible field net/minecraft/client/multiplayer/ClientChunkCache$Storage chunks Ljava/util/concurrent/atomic/AtomicReferenceArray; + +accessible method net/minecraft/tags/TagNetworkSerialization serializeToNetwork (Lnet/minecraft/core/Registry;)Lnet/minecraft/tags/TagNetworkSerialization$NetworkPayload; + +accessible field net/minecraft/world/entity/LivingEntity lerpHeadSteps I +accessible field net/minecraft/world/entity/LivingEntity lerpYHeadRot D +accessible field net/minecraft/world/entity/LivingEntity lerpSteps I +accessible method net/minecraft/world/entity/Entity lerpPositionAndRotationStep (IDDDDD)V +accessible method net/minecraft/world/entity/LivingEntity lerpHeadRotationStep (ID)V +accessible method net/minecraft/world/entity/LivingEntity tickHeadTurn (FF)F + +accessible field net/minecraft/client/gui/components/BossHealthOverlay events Ljava/util/Map; + +accessible field net/minecraft/client/resources/server/DownloadedPackSource manager Lnet/minecraft/client/resources/server/ServerPackManager; +accessible field net/minecraft/client/resources/server/ServerPackManager packs Ljava/util/List; +accessible class net/minecraft/client/resources/server/ServerPackManager$ServerPackData +accessible field net/minecraft/client/resources/server/ServerPackManager$ServerPackData id Ljava/util/UUID; +accessible field net/minecraft/client/resources/server/ServerPackManager$ServerPackData url Ljava/net/URL; +accessible field net/minecraft/client/resources/server/ServerPackManager$ServerPackData hash Lcom/google/common/hash/HashCode; + +accessible field net/minecraft/client/gui/components/PlayerTabOverlay header Lnet/minecraft/network/chat/Component; +accessible field net/minecraft/client/gui/components/PlayerTabOverlay footer Lnet/minecraft/network/chat/Component; + +accessible field net/minecraft/client/multiplayer/MultiPlayerGameMode destroyBlockPos Lnet/minecraft/core/BlockPos; + +# Entity +accessible field net/minecraft/network/syncher/SynchedEntityData itemsById [Lnet/minecraft/network/syncher/SynchedEntityData$DataItem; + +accessible field net/minecraft/world/entity/Entity ENTITY_COUNTER Ljava/util/concurrent/atomic/AtomicInteger; + +# Minecraft server +accessible field net/minecraft/server/MinecraftServer levels Ljava/util/Map; +accessible field net/minecraft/server/MinecraftServer worldData Lnet/minecraft/world/level/storage/WorldData; +accessible field net/minecraft/server/MinecraftServer executor Ljava/util/concurrent/Executor; +accessible field net/minecraft/server/MinecraftServer storageSource Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess; +accessible field net/minecraft/server/MinecraftServer progressListenerFactory Lnet/minecraft/server/level/progress/ChunkProgressListenerFactory; +accessible field net/minecraft/server/MinecraftServer nextTickTimeNanos J + +accessible field net/minecraft/server/MinecraftServer registries Lnet/minecraft/core/LayeredRegistryAccess; +mutable field net/minecraft/server/MinecraftServer registries Lnet/minecraft/core/LayeredRegistryAccess; +accessible class net/minecraft/resources/RegistryDataLoader$Loader +accessible class net/minecraft/resources/RegistryDataLoader$LoadingFunction +accessible field net/minecraft/core/LayeredRegistryAccess keys Ljava/util/List; +mutable field net/minecraft/core/LayeredRegistryAccess keys Ljava/util/List; +accessible field net/minecraft/core/LayeredRegistryAccess values Ljava/util/List; +mutable field net/minecraft/core/LayeredRegistryAccess values Ljava/util/List; +accessible field net/minecraft/core/LayeredRegistryAccess composite Lnet/minecraft/core/RegistryAccess$Frozen; +mutable field net/minecraft/core/LayeredRegistryAccess composite Lnet/minecraft/core/RegistryAccess$Frozen; +accessible field net/minecraft/core/RegistryAccess$ImmutableRegistryAccess registries Ljava/util/Map; +mutable field net/minecraft/core/RegistryAccess$ImmutableRegistryAccess registries Ljava/util/Map; + +accessible field net/minecraft/server/network/ServerCommonPacketListenerImpl connection Lnet/minecraft/network/Connection; + +accessible field net/minecraft/world/level/chunk/PalettedContainer data Lnet/minecraft/world/level/chunk/PalettedContainer$Data; +accessible class net/minecraft/world/level/chunk/PalettedContainer$Data +accessible method net/minecraft/server/MinecraftServer haveTime ()Z +extendable method net/minecraft/server/MinecraftServer haveTime ()Z + +accessible class net/minecraft/server/level/ThreadedLevelLightEngine$TaskType + +# Packets +accessible field net/minecraft/network/protocol/game/ClientboundPlayerInfoUpdatePacket entries Ljava/util/List; +mutable field net/minecraft/network/protocol/game/ClientboundPlayerInfoUpdatePacket entries Ljava/util/List; + +accessible field net/minecraft/network/protocol/game/ClientboundRotateHeadPacket entityId I + +accessible field net/minecraft/network/protocol/game/ClientboundAddEntityPacket data I +mutable field net/minecraft/network/protocol/game/ClientboundAddEntityPacket data I +accessible field net/minecraft/network/protocol/game/ClientboundAddEntityPacket id I +mutable field net/minecraft/network/protocol/game/ClientboundAddEntityPacket id I + +# Replay UI +accessible field net/minecraft/client/KeyMapping key Lcom/mojang/blaze3d/platform/InputConstants$Key; + +accessible method net/minecraft/client/particle/ParticleEngine clearParticles ()V + +# Exporting +accessible field net/minecraft/client/Minecraft clientTickCount J +accessible field net/minecraft/client/Minecraft timer Lnet/minecraft/client/Timer; diff --git a/src/main/resources/flashback.mixins.json b/src/main/resources/flashback.mixins.json new file mode 100644 index 0000000..924dba8 --- /dev/null +++ b/src/main/resources/flashback.mixins.json @@ -0,0 +1,10 @@ +{ + "required": true, + "package": "com.moulberry.flashback.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": [ + ], + "injectors": { + "defaultRequire": 1 + } +}