commit c48a86336070ca1894415bb0553d9d06707af7dd Author: froslanz Date: Tue Oct 27 17:37:44 2026 -0400 upload diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..37c5cf1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2023 3arthqu4ke, alpha432, cattyn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5651716 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# NoLongerHuman +aka. auraware aka. flexware a.k.a. chinaware +## Why +to flex on imperials yo + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..b62aa7a --- /dev/null +++ b/build.gradle @@ -0,0 +1,123 @@ +import java.nio.file.Paths + +plugins { + id 'fabric-loom' version "$loom_version" + id 'com.github.gmazzo.buildconfig' version "$buildconfig_version" +} + +var USING_GIT = Paths.get(System.getProperty("user.dir")).resolve(".git").toFile().exists() +var GIT_HASH = execute("git rev-parse --short HEAD") + +version = project.mod_version +group = project.maven_group + +buildConfig { + buildConfigField(String, "NAME", project.mod_name) + buildConfigField(String, "GROUP", project.group) + buildConfigField(String, "VERSION", project.mod_version) + buildConfigField(String, "BUILD_TIME", "${new Date(System.currentTimeMillis()).format("MM/dd/yyyy HH:mm")}") + buildConfigField(Boolean, "USING_GIT", USING_GIT) + buildConfigField(String, "HASH", GIT_HASH) + buildConfigField(String, "BRANCH", "${execute("git branch --show-current")}") + + packageName "${project.group}.util" + useJavaOutput() + generateAtSync = true +} + +sourceSets.main.java.srcDirs += "build/gen/buildconfig/src/main" + +base { + archivesName = "${project.archives_base_name}-${GIT_HASH}" +} + +repositories { + mavenCentral() + + maven { + url "https://jitpack.io" + } + + maven { + name = "meteor-maven" + url = "https://maven.meteordev.org/releases" + } +} + +loom { + accessWidenerPath = file("src/main/resources/nolongerhuman.accesswidener") +} + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings loom.officialMojangMappings() + + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + // Discord RPC / IPC + include implementation("meteordevelopment:discord-ipc:1.1") + + include implementation("com.github.cattyngmd.catformat:catformat-core:${project.catformat_version}") + include modImplementation("com.github.cattyngmd.catformat:catformat-fabric:${project.catformat_version}") +} + +processResources { + inputs.property "version", project.version + inputs.property "minecraft_version", project.minecraft_version + inputs.property "loader_version", project.loader_version + + filteringCharset "UTF-8" + + filesMatching("fabric.mod.json") { + expand "version": project.version, + "minecraft_version": project.minecraft_version, + "loader_version": project.loader_version + } +} + +def targetJavaVersion = 21 + +tasks.withType(JavaCompile).configureEach { + it.options.encoding = "UTF-8" + + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + it.options.release = targetJavaVersion + } +} + +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } + + withSourcesJar() +} + +sourcesJar { + dependsOn(generateBuildConfig) +} + +jar { + from("LICENSE") { + rename { "${it}_${archives_base_name}" } + } +} + +tasks.withType(JavaCompile).configureEach { + dependsOn(generateBuildConfig) +} + +def execute(String cmd) { + var output = providers.exec { + commandLine cmd.split(" ") + ignoreExitValue = true + } + + return output.standardOutput.getAsText().getOrElse("nogit") + .replaceAll("\n", "") +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..681dac5 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +# Fabric Properties +# check these on https://modmuss50.me/fabric.html +minecraft_version=1.21.11 +yarn_mappings=1.21.11+build.4 +loader_version=0.18.4 +loom_version=1.14-SNAPSHOT +# Mod Properties +maven_group=me.humanbeing.chinaware +mod_version=0.0.3-beta +mod_name=NoLongerHuman +archives_base_name=nolongerhuman +# Dependencies +# check this on https://modmuss50.me/fabric.html +fabric_version=0.141.1+1.21.11 +catformat_version=2.1.0 +buildconfig_version=5.3.5 \ 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..c1962a7 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..bad7c24 --- /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-9.2.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..6146088 --- /dev/null +++ b/gradlew @@ -0,0 +1,245 @@ +#!/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##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && 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 + which java >/dev/null 2>&1 || 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 + +# 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=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=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, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +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" "$@" \ No newline at end of file diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..2578005 --- /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. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +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 \ No newline at end of file diff --git a/images/ui.png b/images/ui.png new file mode 100644 index 0000000..a26d337 Binary files /dev/null and b/images/ui.png differ diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..f91a4fe --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/ducks/render/IChatComponent.java b/src/main/java/me/humanbeing/nolongerhuman/ducks/render/IChatComponent.java new file mode 100644 index 0000000..79e0f46 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/ducks/render/IChatComponent.java @@ -0,0 +1,11 @@ +package me.humanbeing.nolongerhuman.ducks.render; + +import net.minecraft.client.GuiMessage; +import net.minecraft.network.chat.MessageSignature; + +public interface IChatComponent { + void nolongerhumanl$addMessage(GuiMessage message); + void nolongerhuman$removeMessage(MessageSignature signature); + + void nolongerhuman$addMessage(GuiMessage guiMessage); +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/Event.java b/src/main/java/me/humanbeing/nolongerhuman/event/Event.java new file mode 100644 index 0000000..74805de --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/Event.java @@ -0,0 +1,13 @@ +package me.humanbeing.nolongerhuman.event; + +public class Event { + private boolean cancelled; + + public boolean isCancelled() { + return cancelled; + } + + public void cancel() { + cancelled = true; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/Stage.java b/src/main/java/me/humanbeing/nolongerhuman/event/Stage.java new file mode 100644 index 0000000..c7e373d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/Stage.java @@ -0,0 +1,6 @@ +package me.humanbeing.nolongerhuman.event; + +public enum Stage { + PRE, + POST +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/ClientEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/ClientEvent.java new file mode 100644 index 0000000..a1259b4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/ClientEvent.java @@ -0,0 +1,38 @@ +package me.humanbeing.nolongerhuman.event.impl; + +import me.humanbeing.nolongerhuman.event.Event; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.settings.Setting; + +public class ClientEvent extends Event { + private final Type type; + private final Feature feature; + private Setting setting; + + public ClientEvent(Type type, Feature feature) { + this.type = type; + this.feature = feature; + } + + public ClientEvent(Setting setting) { + this(Type.SETTING_UPDATE, setting.getFeature()); + this.setting = setting; + } + + public Type getType() { + return type; + } + + public Feature getFeature() { + return this.feature; + } + + public Setting getSetting() { + return this.setting; + } + + public enum Type { + TOGGLE_MODULE, + SETTING_UPDATE + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/PacketEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/PacketEvent.java new file mode 100644 index 0000000..0c46fab --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/PacketEvent.java @@ -0,0 +1,32 @@ +package me.humanbeing.nolongerhuman.event.impl; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.network.protocol.Packet; + +public class PacketEvent extends Event { + private Packet packet; + + public PacketEvent(Packet packet) { + this.packet = packet; + } + + public Packet getPacket() { + return this.packet; + } + + public void setPacket(Packet packet) { + this.packet = packet; + } + + public static class Receive extends PacketEvent { + public Receive(Packet packet) { + super(packet); + } + } + + public static class Send extends PacketEvent { + public Send(Packet packet) { + super(packet); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/DeathEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/DeathEvent.java new file mode 100644 index 0000000..46d78db --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/DeathEvent.java @@ -0,0 +1,16 @@ +package me.humanbeing.nolongerhuman.event.impl.entity; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.world.entity.LivingEntity; + +public class DeathEvent extends Event { + private final LivingEntity entity; + + public DeathEvent(LivingEntity entity) { + this.entity = entity; + } + + public LivingEntity getEntity() { + return entity; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/MoveEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/MoveEvent.java new file mode 100644 index 0000000..eae7c8d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/MoveEvent.java @@ -0,0 +1,30 @@ +package me.humanbeing.nolongerhuman.event.impl.entity.player; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.phys.Vec3; + +public class MoveEvent extends Event { + private final MoverType type; + private double x, y, z; + + public MoveEvent(MoverType type, Vec3 movement) { + this.type = type; + this.x = movement.x; + this.y = movement.y; + this.z = movement.z; + } + + public MoverType getType() { return type; } + + public double getX() { return x; } + public double getY() { return y; } + public double getZ() { return z; } + + public void setX(double x) { this.x = x; } + public void setY(double y) { this.y = y; } + public void setZ(double z) { this.z = z; } + + public void set(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } + public Vec3 toVec3() { return new Vec3(x, y, z); } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/TickEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/TickEvent.java new file mode 100644 index 0000000..cb0e0ae --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/TickEvent.java @@ -0,0 +1,6 @@ +package me.humanbeing.nolongerhuman.event.impl.entity.player; + +import me.humanbeing.nolongerhuman.event.Event; + +public class TickEvent extends Event { +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/TravelEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/TravelEvent.java new file mode 100644 index 0000000..101d5ec --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/TravelEvent.java @@ -0,0 +1,24 @@ +package me.humanbeing.nolongerhuman.event.impl.entity.player; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.world.phys.Vec3; + +public class TravelEvent extends Event { + private double x, y, z; + + public TravelEvent(Vec3 input) { + this.x = input.x; + this.y = input.y; + this.z = input.z; + } + + public double getX() { return x; } + public double getY() { return y; } + public double getZ() { return z; } + + public void setX(double x) { this.x = x; } + public void setY(double y) { this.y = y; } + public void setZ(double z) { this.z = z; } + + public Vec3 toVec3() { return new Vec3(x, y, z); } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/UpdateWalkingPlayerEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/UpdateWalkingPlayerEvent.java new file mode 100644 index 0000000..98f18c3 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/entity/player/UpdateWalkingPlayerEvent.java @@ -0,0 +1,16 @@ +package me.humanbeing.nolongerhuman.event.impl.entity.player; + +import me.humanbeing.nolongerhuman.event.Event; +import me.humanbeing.nolongerhuman.event.Stage; + +public class UpdateWalkingPlayerEvent extends Event { + private final Stage stage; + + public UpdateWalkingPlayerEvent(Stage stage) { + this.stage = stage; + } + + public Stage getStage() { + return stage; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/KeyInputEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/KeyInputEvent.java new file mode 100644 index 0000000..2cb76f4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/KeyInputEvent.java @@ -0,0 +1,15 @@ +package me.humanbeing.nolongerhuman.event.impl.input; + +import me.humanbeing.nolongerhuman.event.Event; + +public class KeyInputEvent extends Event { + private final int key; + + public KeyInputEvent(int key) { + this.key = key; + } + + public int getKey() { + return key; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/MouseInputEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/MouseInputEvent.java new file mode 100644 index 0000000..8b719f5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/MouseInputEvent.java @@ -0,0 +1,22 @@ +package me.humanbeing.nolongerhuman.event.impl.input; + +import me.humanbeing.nolongerhuman.event.Event; + +public class MouseInputEvent extends Event { + private final int button; + private final int action; + + public MouseInputEvent(int button, int action) { + this.button = button; + this.action = action; + } + + public int getButton() { + return button; + } + + public int getAction() { + return action; + } +} + diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/UnfilteredKeyInputEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/UnfilteredKeyInputEvent.java new file mode 100644 index 0000000..0a699d1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/UnfilteredKeyInputEvent.java @@ -0,0 +1,33 @@ +package me.humanbeing.nolongerhuman.event.impl.input; + +import me.humanbeing.nolongerhuman.event.Event; + +public class UnfilteredKeyInputEvent extends Event { + private final int key; + private final int scancode; + private final int action; + private final int modifiers; + + public UnfilteredKeyInputEvent(int key, int scancode, int action, int modifiers) { + this.key = key; + this.scancode = scancode; + this.action = action; + this.modifiers = modifiers; + } + + public int getKey() { + return key; + } + + public int getScancode() { + return scancode; + } + + public int getAction() { + return action; + } + + public int getModifiers() { + return modifiers; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/UnfilteredMouseInputEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/UnfilteredMouseInputEvent.java new file mode 100644 index 0000000..dd387b4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/input/UnfilteredMouseInputEvent.java @@ -0,0 +1,27 @@ +package me.humanbeing.nolongerhuman.event.impl.input; + +import me.humanbeing.nolongerhuman.event.Event; + +public class UnfilteredMouseInputEvent extends Event { + private final int button; + private final int action; + private final int mods; + + public UnfilteredMouseInputEvent(int button, int action, int mods) { + this.button = button; + this.action = action; + this.mods = mods; + } + + public int getButton() { + return button; + } + + public int getAction() { + return action; + } + + public int getMods() { + return mods; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/ChatEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/ChatEvent.java new file mode 100644 index 0000000..08e613e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/ChatEvent.java @@ -0,0 +1,15 @@ +package me.humanbeing.nolongerhuman.event.impl.network; + +import me.humanbeing.nolongerhuman.event.Event; + +public class ChatEvent extends Event { + private final String content; + + public ChatEvent(String content) { + this.content = content; + } + + public String getMessage() { + return content; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/ChatSendEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/ChatSendEvent.java new file mode 100644 index 0000000..65eb303 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/ChatSendEvent.java @@ -0,0 +1,20 @@ +package me.humanbeing.nolongerhuman.event.impl.network; + +import me.humanbeing.nolongerhuman.event.Event; + +public class ChatSendEvent extends Event { + + private String message; + + public ChatSendEvent(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/PacketEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/PacketEvent.java new file mode 100644 index 0000000..95d1aef --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/network/PacketEvent.java @@ -0,0 +1,30 @@ +package me.humanbeing.nolongerhuman.event.impl.network; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.network.protocol.Packet; + +public abstract class PacketEvent extends Event { + + private final Packet packet; + + public PacketEvent(Packet packet) { + this.packet = packet; + } + + public Packet getPacket() { + return packet; + } + + public static class Receive extends PacketEvent { + public Receive(Packet packet) { + super(packet); + } + } + + public static class Send extends PacketEvent { + public Send(Packet packet) { + super(packet); + } + } + +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/player/AttackBlockEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/player/AttackBlockEvent.java new file mode 100644 index 0000000..dcb2144 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/player/AttackBlockEvent.java @@ -0,0 +1,23 @@ +package me.humanbeing.nolongerhuman.event.impl.player; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; + +public class AttackBlockEvent extends Event { + private final BlockPos pos; + private final Direction direction; + + public AttackBlockEvent(BlockPos pos, Direction direction) { + this.pos = pos; + this.direction = direction; + } + + public BlockPos getPos() { + return pos; + } + + public Direction getDirection() { + return direction; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/ParticleEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/ParticleEvent.java new file mode 100644 index 0000000..b1a6b17 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/ParticleEvent.java @@ -0,0 +1,28 @@ +package me.humanbeing.nolongerhuman.event.impl.render; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.client.particle.Particle; + +public abstract class ParticleEvent extends Event { + + public final Particle particle; + private boolean cancelled; + + public ParticleEvent(Particle particle) { + this.particle = particle; + } + + public void cancel() { + this.cancelled = true; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public static class Add extends ParticleEvent { + public Add(Particle particle) { + super(particle); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/Render2DEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/Render2DEvent.java new file mode 100644 index 0000000..268c3ce --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/Render2DEvent.java @@ -0,0 +1,22 @@ +package me.humanbeing.nolongerhuman.event.impl.render; + +import me.humanbeing.nolongerhuman.event.Event; +import net.minecraft.client.gui.GuiGraphics; + +public class Render2DEvent extends Event { + private final GuiGraphics context; + private final float delta; + + public Render2DEvent(GuiGraphics context, float delta) { + this.context = context; + this.delta = delta; + } + + public GuiGraphics getContext() { + return context; + } + + public float getDelta() { + return delta; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/Render3DEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/Render3DEvent.java new file mode 100644 index 0000000..11e9cac --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/Render3DEvent.java @@ -0,0 +1,22 @@ +package me.humanbeing.nolongerhuman.event.impl.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.event.Event; + +public class Render3DEvent extends Event { + private final PoseStack matrix; + private final float delta; + + public Render3DEvent(PoseStack matrix, float delta) { + this.matrix = matrix; + this.delta = delta; + } + + public PoseStack getMatrix() { + return matrix; + } + + public float getDelta() { + return delta; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/RenderBlockOutlineEvent.java b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/RenderBlockOutlineEvent.java new file mode 100644 index 0000000..b715ac0 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/impl/render/RenderBlockOutlineEvent.java @@ -0,0 +1,6 @@ +package me.humanbeing.nolongerhuman.event.impl.render; + +import me.humanbeing.nolongerhuman.event.Event; + +public class RenderBlockOutlineEvent extends Event { +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/system/EventBus.java b/src/main/java/me/humanbeing/nolongerhuman/event/system/EventBus.java new file mode 100644 index 0000000..e1d46f8 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/system/EventBus.java @@ -0,0 +1,112 @@ +package me.humanbeing.nolongerhuman.event.system; + +import me.humanbeing.nolongerhuman.event.Event; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +public class EventBus { + + public static final EventBus INSTANCE = new EventBus(); + + private final Map, CopyOnWriteArrayList> listeners = new ConcurrentHashMap<>(); + + public void register(Object host) { + if (host == null) { + return; + } + + unregister(host); + register(host, host.getClass()); + } + + public void unregister(Object host) { + if (host == null) { + return; + } + + for (CopyOnWriteArrayList list : listeners.values()) { + list.removeIf(listener -> listener.getHost().equals(host)); + } + } + + public boolean post(Event event) { + if (event == null) { + return false; + } + + List list = listeners.get(event.getClass()); + + if (list == null) { + return false; + } + + for (Listener listener : list) { + listener.invoke(event); + + if (event.isCancelled()) { + return true; + } + } + + return event.isCancelled(); + } + + private void register(Object host, Class klass) { + if (klass == null) { + return; + } + + for (Method method : klass.getDeclaredMethods()) { + Subscribe subscribe = method.getAnnotation(Subscribe.class); + + if (subscribe == null) { + continue; + } + + Class[] params = method.getParameterTypes(); + + if (params.length != 1) { + continue; + } + + Class eventType = params[0]; + + if (!Event.class.isAssignableFrom(eventType)) { + continue; + } + + method.setAccessible(true); + + Listener listener = Listener.of(host, subscribe.priority(), method); + + CopyOnWriteArrayList registry = listeners.computeIfAbsent( + eventType, + ignored -> new CopyOnWriteArrayList<>() + ); + + register(registry, listener); + } + + register(host, klass.getSuperclass()); + } + + private void register(List registry, Listener target) { + int index = 0; + + while (index < registry.size()) { + Listener listener = registry.get(index); + + if (target.priority() > listener.priority()) { + break; + } + + index++; + } + + registry.add(index, target); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/system/Listener.java b/src/main/java/me/humanbeing/nolongerhuman/event/system/Listener.java new file mode 100644 index 0000000..4d67163 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/system/Listener.java @@ -0,0 +1,38 @@ +package me.humanbeing.nolongerhuman.event.system; + +import java.lang.invoke.*; +import java.lang.reflect.Method; +import java.util.function.Consumer; + +public record Listener(Object host, int priority, Consumer consumer) { + public static Listener of(Object host, int priority, Method method) { + return new Listener(host, priority, buildLambdaMetafactory(host, method)); + } + + public void invoke(Object event) { + consumer.accept(event); + } + + public Object getHost() { + return host; + } + + @SuppressWarnings("unchecked") + private static Consumer buildLambdaMetafactory(Object host, Method method) { + try { + MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(host.getClass(), MethodHandles.lookup()); + CallSite site = LambdaMetafactory.metafactory( + lookup, + "accept", + MethodType.methodType(Consumer.class, host.getClass()), + MethodType.methodType(void.class, Object.class), + lookup.unreflect(method), + MethodType.methodType(void.class, method.getParameterTypes()[0]) + ); + MethodHandle target = site.getTarget(); + return (Consumer) (target.invoke(host)); + } catch (Throwable e) { + throw new RuntimeException("Failed to build lambda from %s method".formatted(method.getName()), e); + } + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/event/system/Subscribe.java b/src/main/java/me/humanbeing/nolongerhuman/event/system/Subscribe.java new file mode 100644 index 0000000..6cc508f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/event/system/Subscribe.java @@ -0,0 +1,13 @@ +package me.humanbeing.nolongerhuman.event.system; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Subscribe { + int priority() default 0; +} + diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/Feature.java b/src/main/java/me/humanbeing/nolongerhuman/features/Feature.java new file mode 100644 index 0000000..816e117 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/Feature.java @@ -0,0 +1,65 @@ +package me.humanbeing.nolongerhuman.features; + +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.features.settings.SettingFactory; +import me.humanbeing.nolongerhuman.util.traits.Util; + +import java.util.ArrayList; +import java.util.List; + +public class Feature + implements Util, SettingFactory { + public List> settings = new ArrayList<>(); + private String name; + + public Feature() { + } + + public Feature(String name) { + this.name = name; + } + + public static boolean nullCheck() { + return Feature.mc.player == null || Feature.mc.level == null; + } + + public String getName() { + return this.name; + } + + public List> getSettings() { + return this.settings; + } + + public boolean hasSettings() { + return !this.settings.isEmpty(); + } + + public boolean isEnabled() { + return false; + } + + public boolean isDisabled() { + return !this.isEnabled(); + } + + public > T register(T setting) { + setting.setFeature(this); + this.settings.add(setting); + return setting; + } + + public Setting getSettingByName(String name) { + for (Setting setting : this.settings) { + if (!setting.getName().equalsIgnoreCase(name)) continue; + return setting; + } + return null; + } + + public void reset() { + for (Setting setting : this.settings) { + setting.reset(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/Command.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/Command.java new file mode 100644 index 0000000..82da2f5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/Command.java @@ -0,0 +1,79 @@ +package me.humanbeing.nolongerhuman.features.commands; + +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.manager.CommandManager; +import me.humanbeing.nolongerhuman.util.TextUtil; +import me.humanbeing.nolongerhuman.util.player.ChatUtil; + +import static com.mojang.brigadier.Command.SINGLE_SUCCESS; +import static me.humanbeing.nolongerhuman.features.commands.MessageIdentifiers.*; + +public abstract class Command extends Feature { + public static final int NO_OP = -1; + public static final int SINGLE_FAILURE = 0; + + private final String[] aliases; + private String description = "No description was provided for this command."; + + public Command(String... aliases) { + super(aliases[0]); + this.aliases = aliases; + } + + public abstract void createArgumentBuilder(LiteralArgumentBuilder builder); + + protected int success(String message, Object... format) { + sendMessage(message, SUCCESS, format); + return NO_OP; + } + + protected int success() { + return SINGLE_SUCCESS; + } + + protected int fail(String message, Object... format) { + sendMessage("{red} " + message, FAIL, format); + return NO_OP; + } + + protected int fail() { + return SINGLE_FAILURE; + } + + public String[] getAliases() { + return aliases; + } + + protected void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public boolean isShown() { + return true; + } + + public static void sendMessage(String message, String identifier) { + if (message == null) return; + ChatUtil.sendMessage(TextUtil.text(message), identifier); + } + + public static void sendMessage(String message, String identifier, Object... format) { + if (message == null) return; + ChatUtil.sendMessage(TextUtil.text(message, format), identifier); + } + + public static LiteralArgumentBuilder literal(String literal) { + return LiteralArgumentBuilder.literal(literal); + } + + public static RequiredArgumentBuilder argument(String name, ArgumentType type) { + return RequiredArgumentBuilder.argument(name, type); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/CommandExceptions.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/CommandExceptions.java new file mode 100644 index 0000000..9afa379 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/CommandExceptions.java @@ -0,0 +1,10 @@ +package me.humanbeing.nolongerhuman.features.commands; + +import com.mojang.brigadier.LiteralMessage; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; + +public class CommandExceptions { + public static SimpleCommandExceptionType invalidArgument(String message, Object... format) { + return new SimpleCommandExceptionType(new LiteralMessage(String.format(message, format))); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/MessageIdentifiers.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/MessageIdentifiers.java new file mode 100644 index 0000000..92831f7 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/MessageIdentifiers.java @@ -0,0 +1,7 @@ +package me.humanbeing.nolongerhuman.features.commands; + +public class MessageIdentifiers { + public static final String GENERAL = "general"; + public static final String SUCCESS = "success"; + public static final String FAIL = "fail"; +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/ModuleCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/ModuleCommand.java new file mode 100644 index 0000000..5105ab6 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/ModuleCommand.java @@ -0,0 +1,117 @@ +package me.humanbeing.nolongerhuman.features.commands; + +import com.mojang.brigadier.arguments.BoolArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.features.commands.argument.ColorArgumentType; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import java.awt.*; + +import static com.mojang.brigadier.arguments.BoolArgumentType.getBool; +import static com.mojang.brigadier.arguments.StringArgumentType.getString; +import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; +import static me.humanbeing.nolongerhuman.features.commands.argument.ColorArgumentType.getColor; +import static me.humanbeing.nolongerhuman.features.commands.argument.EnumArgumentType._enum; +import static me.humanbeing.nolongerhuman.features.commands.argument.EnumArgumentType.getEnum; +import static me.humanbeing.nolongerhuman.features.commands.argument.NumberArgumentType.*; + +public class ModuleCommand extends Command { + private final Module module; + + public ModuleCommand(Module module) { + super(module.getName().toLowerCase()); + setDescription("Command line configuration implementation for \"" + module.getName() + "\""); + this.module = module; + } + + @SuppressWarnings("unchecked") + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + for (Setting setting : module.getSettings()) { + Class type = setting.getDefaultValue().getClass(); + + if (Boolean.class.isAssignableFrom(type)) { + registerBooleanArgument(builder, (Setting) setting); + } else if (Number.class.isAssignableFrom(type)) { + registerNumberArgument(builder, (Setting) setting); + } else if (Enum.class.isAssignableFrom(type)) { + registerEnumArgument(builder, (Setting>) setting); + } else if (String.class.isAssignableFrom(type)) { + registerStringArgument(builder, (Setting) setting); + } else if (Color.class.isAssignableFrom(type)) { + registerColorArgument(builder, (Setting) setting); + } + } + } + + private void registerColorArgument(LiteralArgumentBuilder builder, + Setting setting) { + builder.then(literal(setting.getName().toLowerCase()) + .then(argument("value", ColorArgumentType.color()) + .executes((ctx) -> { + setting.setValue(getColor(ctx, "value")); + Color value = setting.getValue(); + return success("Set %s.%s to RGB(%s, %s, %s)", + module.getName(), + setting.getName(), + value.getRed(), + value.getGreen(), + value.getBlue()); + }))); + } + + private void registerStringArgument(LiteralArgumentBuilder builder, + Setting setting) { + builder.then(literal(setting.getName().toLowerCase()) + .then(argument("value", greedyString()) + .executes((ctx) -> { + setting.setValue(getString(ctx, "value")); + return settingChangeReturn(setting); + }))); + } + + @SuppressWarnings("unchecked") + private void registerEnumArgument(LiteralArgumentBuilder builder, + Setting> setting) { + Class> type = (Class>) setting.getDefaultValue().getClass(); + builder.then(literal(setting.getName().toLowerCase()) + .then(argument("value", _enum(type)) + .executes((ctx) -> { + setting.setValue(getEnum(ctx, "value")); + return settingChangeReturn(setting); + }))); + } + + @SuppressWarnings("unchecked") + private void registerNumberArgument(LiteralArgumentBuilder builder, + Setting setting) { + Class type = (Class) setting.getDefaultValue().getClass(); + builder.then(literal(setting.getName().toLowerCase()) + .then(argument("value", number(type, minMax(setting.getMin(), setting.getMax()))) + .executes((ctx) -> { + setting.setValue(get(type, ctx, "value")); + return settingChangeReturn(setting); + }))); + } + + private void registerBooleanArgument(LiteralArgumentBuilder builder, + Setting setting) { + builder.then(literal(setting.getName().toLowerCase()) + .then(argument("value", BoolArgumentType.bool()) + .executes((ctx) -> { + setting.setValue(getBool(ctx, "value")); + return settingChangeReturn(setting); + }))); + } + + private int settingChangeReturn(final Setting setting) { + return success("Set %s.%s to %s", module.getName(), setting.getName(), setting.getValue()); + } + + @Override + public boolean isShown() { + return false; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ColorArgumentType.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ColorArgumentType.java new file mode 100644 index 0000000..861da26 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ColorArgumentType.java @@ -0,0 +1,93 @@ +package me.humanbeing.nolongerhuman.features.commands.argument; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.humanbeing.nolongerhuman.features.commands.CommandExceptions; + +import java.awt.*; +import java.util.Collection; +import java.util.List; + +public class ColorArgumentType implements ArgumentType { + private static final List EXAMPLES = List.of("hsb:55,100,100", "255,0,255", "0,255,255,80"); + private static final String[] RGBA_VALUES = {"Red", "Green", "Blue", "Alpha"}; + + @Override + public Color parse(StringReader reader) throws CommandSyntaxException { + String value = reader.getRemaining(); + reader.setCursor(reader.getTotalLength()); + + if (value.startsWith("#")) { + return new Color(Integer.parseInt(value.substring(1), 16)); + } + + if (value.startsWith("hsb:")) { + int[] elements = parseColorElements(reader, value.substring(4)); + + int hue = elements[0]; + if (hue < 0 || hue > 360) { + throw CommandExceptions.invalidArgument("Hue value must be between 0-360") + .createWithContext(reader); + } + + int saturation = elements[1]; + if (saturation < 0 || saturation > 100) { + throw CommandExceptions.invalidArgument("Saturation value must be between 0-100") + .createWithContext(reader); + } + + int brightness = elements[2]; + if (brightness < 0 || brightness > 100) { + throw CommandExceptions.invalidArgument("Brightness value must be between 0-100") + .createWithContext(reader); + } + + return Color.getHSBColor((float) hue / 360.0f, + (float) saturation / 100.0f, + (float) brightness / 100.0f); + } + + int[] elements = parseColorElements(reader, value); + for (int i = 0; i < elements.length; ++i) { + int element = elements[i]; + if (element < 0 || element > 255) { + throw CommandExceptions.invalidArgument("%s value must be between 0-255", RGBA_VALUES[i]) + .createWithContext(reader); + } + } + + return new Color(elements[0], + elements[1], + elements[2], + elements.length == 4 ? elements[3] : 255); + } + + private int[] parseColorElements(StringReader reader, String value) throws CommandSyntaxException { + String[] parts = value.split(","); + if (parts.length < 3) { + throw CommandExceptions.invalidArgument("Color element must have three values (with optional alpha value), either RGB(A) or hsb:HSB") + .createWithContext(reader); + } + + int[] elements = new int[parts.length]; + for (int i = 0; i < parts.length; ++i) { + elements[i] = Integer.parseInt(parts[i]); + } + return elements; + } + + @Override + public Collection getExamples() { + return EXAMPLES; + } + + public static Color getColor(CommandContext ctx, String name) { + return ctx.getArgument(name, Color.class); + } + + public static ColorArgumentType color() { + return new ColorArgumentType(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/CommandArgumentType.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/CommandArgumentType.java new file mode 100644 index 0000000..f51e5b2 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/CommandArgumentType.java @@ -0,0 +1,51 @@ +package me.humanbeing.nolongerhuman.features.commands.argument; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandExceptionType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.commands.CommandExceptions; + +import java.util.concurrent.CompletableFuture; + +public class CommandArgumentType implements ArgumentType, CommandExceptionType { + @Override + public Command parse(StringReader reader) throws CommandSyntaxException { + String value = reader.readString().toLowerCase(); + + for (String alias : nolongerhuman.commandManager.getCommandAliases()) { + if (value.equalsIgnoreCase(alias)) { + return nolongerhuman.commandManager.getCommand(alias); + } + } + + throw CommandExceptions.invalidArgument("Invalid command").createWithContext(reader); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String input = builder.getRemainingLowerCase(); + + for (String alias : nolongerhuman.commandManager.getCommandAliases()) { + String name = alias.toLowerCase(); + if (name.contains(input)) { + builder.suggest(name); + } + } + + return builder.buildFuture(); + } + + public static Command getCommand(CommandContext ctx, String name) { + return ctx.getArgument(name, Command.class); + } + + public static CommandArgumentType command() { + return new CommandArgumentType(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ConfigArgumentType.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ConfigArgumentType.java new file mode 100644 index 0000000..a622101 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ConfigArgumentType.java @@ -0,0 +1,58 @@ +package me.humanbeing.nolongerhuman.features.commands.argument; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.CommandExceptions; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class ConfigArgumentType implements ArgumentType { + private static final List EXAMPLES = List.of("default", "crystal", "visuals"); + + @Override + public String parse(StringReader reader) throws CommandSyntaxException { + String value = reader.readString(); + String sanitized = nolongerhuman.configManager.sanitizeName(value); + + if (sanitized.isEmpty()) { + throw CommandExceptions.invalidArgument("Invalid config name").createWithContext(reader); + } + + return sanitized; + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String input = builder.getRemainingLowerCase(); + + for (String config : nolongerhuman.configManager.getNamedConfigs()) { + String name = config.toLowerCase(); + + if (name.contains(input)) { + builder.suggest(name); + } + } + + return builder.buildFuture(); + } + + @Override + public Collection getExamples() { + return EXAMPLES; + } + + public static ConfigArgumentType config() { + return new ConfigArgumentType(); + } + + public static String getConfig(CommandContext ctx, String name) { + return ctx.getArgument(name, String.class); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/EnumArgumentType.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/EnumArgumentType.java new file mode 100644 index 0000000..4dce498 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/EnumArgumentType.java @@ -0,0 +1,67 @@ +package me.humanbeing.nolongerhuman.features.commands.argument; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import me.humanbeing.nolongerhuman.features.commands.CommandExceptions; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public class EnumArgumentType> implements ArgumentType { + private final Map enumNameMap = new HashMap<>(); + private final T defaultValue; + + public EnumArgumentType(Class clazz, T defaultValue) { + this.defaultValue = defaultValue; + + for (T constant : clazz.getEnumConstants()) { + enumNameMap.put(constant.toString(), constant); + } + } + + @Override + public T parse(StringReader reader) throws CommandSyntaxException { + String value = reader.readString(); + for (String name : enumNameMap.keySet()) { + if (value.equalsIgnoreCase(name)) { + return enumNameMap.get(name); + } + } + + if (defaultValue != null) { + return defaultValue; + } + + throw CommandExceptions.invalidArgument("Invalid enum type").createWithContext(reader); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String input = builder.getRemainingLowerCase(); + for (String key : enumNameMap.keySet()) { + String name = key.toLowerCase(); + if (name.contains(input)) { + builder.suggest(name); + } + } + return builder.buildFuture(); + } + + @SuppressWarnings("unchecked") + public static > T getEnum(CommandContext ctx, String name) { + return (T) ctx.getArgument(name, Object.class); + } + + public static > EnumArgumentType _enum(Class clazz) { + return _enum(clazz, null); + } + + public static > EnumArgumentType _enum(Class clazz, T defaultValue) { + return new EnumArgumentType<>(clazz, defaultValue); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ModuleArgumentType.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ModuleArgumentType.java new file mode 100644 index 0000000..a2c51a5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/ModuleArgumentType.java @@ -0,0 +1,55 @@ +package me.humanbeing.nolongerhuman.features.commands.argument; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.suggestion.Suggestions; +import com.mojang.brigadier.suggestion.SuggestionsBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.CommandExceptions; +import me.humanbeing.nolongerhuman.features.modules.Module; + +import java.util.concurrent.CompletableFuture; + +public record ModuleArgumentType(boolean fullName) implements ArgumentType { + @Override + public Module parse(StringReader reader) throws CommandSyntaxException { + String value = reader.readString().toLowerCase(); + + for (Module module : nolongerhuman.moduleManager.getModules()) { + if (value.equalsIgnoreCase(module.getName()) || module.getName().startsWith(value)) { + return module; + } + } + + throw CommandExceptions.invalidArgument("Invalid module").createWithContext(reader); + } + + @Override + public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { + String input = builder.getRemainingLowerCase(); + + for (Module module : nolongerhuman.moduleManager.getModules()) { + String name = module.getName().toLowerCase(); + String displayName = module.getDisplayName().toLowerCase(); + if (name.contains(input) || displayName.contains(input)) { + builder.suggest(name); + } + } + + return builder.buildFuture(); + } + + public static ModuleArgumentType module() { + return module(false); + } + + public static ModuleArgumentType module(boolean fullName) { + return new ModuleArgumentType(fullName); + } + + public static Module getModule(CommandContext ctx, String name) { + return ctx.getArgument(name, Module.class); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/NumberArgumentType.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/NumberArgumentType.java new file mode 100644 index 0000000..dbd00cd --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/argument/NumberArgumentType.java @@ -0,0 +1,67 @@ +package me.humanbeing.nolongerhuman.features.commands.argument; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.arguments.ArgumentType; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.humanbeing.nolongerhuman.features.commands.CommandExceptions; + +public record NumberArgumentType(Class type, Constraint constraint) implements ArgumentType { + @SuppressWarnings("unchecked") + @Override + public T parse(StringReader reader) throws CommandSyntaxException { + String input = reader.readString(); + + T value = null; + if (type.isAssignableFrom(Integer.class)) { + value = (T) Integer.valueOf(input); + } else if (type.isAssignableFrom(Double.class)) { + value = (T) Double.valueOf(input); + } else if (type.isAssignableFrom(Float.class)) { + value = (T) Float.valueOf(input); + } else if (type.isAssignableFrom(Long.class)) { + value = (T) Long.valueOf(input); + } + + if (constraint != null) { + constraint.validate(reader, value); + } + + if (value == null) { + throw CommandExceptions.invalidArgument("Could not parse \"%s\"", input) + .createWithContext(reader); + } + + return value; + } + + public static Constraint minMax(T min, T max) { + return (reader, input) -> { + double value = input.doubleValue(); + if (min.doubleValue() > value) { + throw CommandExceptions.invalidArgument("Value is less than minimum(%s)", min.toString()) + .createWithContext(reader); + } + if (max.doubleValue() < value) { + throw CommandExceptions.invalidArgument("Value is more than maximum(%s)", max.toString()) + .createWithContext(reader); + } + }; + } + + public static T get(Class type, CommandContext ctx, String name) { + return ctx.getArgument(name, type); + } + + public static NumberArgumentType number(Class type) { + return number(type, null); + } + + public static NumberArgumentType number(Class type, Constraint constraint) { + return new NumberArgumentType<>(type, constraint); + } + + public interface Constraint { + void validate(StringReader reader, T input) throws CommandSyntaxException; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/BindCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/BindCommand.java new file mode 100644 index 0000000..c0f1519 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/BindCommand.java @@ -0,0 +1,53 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.event.impl.input.KeyInputEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Bind; +import me.humanbeing.nolongerhuman.manager.CommandManager; +import me.humanbeing.nolongerhuman.util.KeyboardUtil; + +import static me.humanbeing.nolongerhuman.features.commands.argument.ModuleArgumentType.getModule; +import static me.humanbeing.nolongerhuman.features.commands.argument.ModuleArgumentType.module; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_UNKNOWN; + +public class BindCommand extends Command { + private Module module; + + public BindCommand() { + super("bind", "setbind"); + setDescription("Sets a key bind for a module"); + EVENT_BUS.register(this); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(argument("module", module(true)) + .executes((ctx) -> { + module = getModule(ctx, "module"); + return success("Press any key..."); + })); + } + + @Subscribe + public void onKey(final KeyInputEvent event) { + if (nullCheck() || module == null || event.getKey() == GLFW_KEY_UNKNOWN) { + return; + } + + if (event.getKey() == GLFW_KEY_ESCAPE) { + module = null; + sendMessage("Operation canceled.", "fail"); + return; + } + + sendMessage("Bind for {green} %s {} set to {green} %s", + module.getName(), + KeyboardUtil.getKeyName(event.getKey())); + module.bind.setValue(new Bind(event.getKey())); + module = null; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/ConfigCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/ConfigCommand.java new file mode 100644 index 0000000..1475be4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/ConfigCommand.java @@ -0,0 +1,154 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import java.util.List; +import java.util.StringJoiner; + +import static com.mojang.brigadier.arguments.StringArgumentType.getString; +import static com.mojang.brigadier.arguments.StringArgumentType.word; +import static me.humanbeing.nolongerhuman.features.commands.MessageIdentifiers.GENERAL; + +public class ConfigCommand extends Command { + public ConfigCommand() { + super("config", "configs", "cfg"); + setDescription("Saves, updates, loads, deletes, and lists named configs"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(literal("save") + .then(argument("filename", word()) + .executes(ctx -> saveConfig(getString(ctx, "filename"))))) + + .then(literal("update") + .then(argument("filename", word()) + .executes(ctx -> saveConfig(getString(ctx, "filename"))))) + + .then(literal("load") + .then(argument("filename", word()) + .executes(ctx -> loadConfig(getString(ctx, "filename"))))) + + .then(literal("loadvisuals") + .then(argument("filename", word()) + .executes(ctx -> loadVisuals(getString(ctx, "filename"))))) + + .then(literal("visuals") + .then(argument("filename", word()) + .executes(ctx -> loadVisuals(getString(ctx, "filename"))))) + + .then(literal("delete") + .then(argument("filename", word()) + .executes(ctx -> deleteConfig(getString(ctx, "filename"))))) + + .then(literal("remove") + .then(argument("filename", word()) + .executes(ctx -> deleteConfig(getString(ctx, "filename"))))) + + .then(literal("list") + .executes(ctx -> listConfigs())) + + .executes(ctx -> { + Command.sendMessage("Config command usage:", GENERAL); + Command.sendMessage("{gray} .config save ", GENERAL); + Command.sendMessage("{gray} .config update ", GENERAL); + Command.sendMessage("{gray} .config load ", GENERAL); + Command.sendMessage("{gray} .config loadvisuals ", GENERAL); + Command.sendMessage("{gray} .config delete ", GENERAL); + Command.sendMessage("{gray} .config list", GENERAL); + return success(); + }); + } + + private int saveConfig(String inputName) { + String configName = nolongerhuman.configManager.sanitizeName(inputName); + + if (configName.isEmpty()) { + return fail("Invalid config name."); + } + + boolean saved = nolongerhuman.configManager.save(configName); + + if (!saved) { + return fail("Failed to save config {green}%s", configName); + } + + return success("Saved config {green}%s", configName); + } + + private int loadConfig(String inputName) { + String configName = nolongerhuman.configManager.sanitizeName(inputName); + + if (configName.isEmpty()) { + return fail("Invalid config name."); + } + + if (!nolongerhuman.configManager.exists(configName)) { + return fail("Config {green}%s {red}does not exist.", configName); + } + + boolean loaded = nolongerhuman.configManager.load(configName); + + if (!loaded) { + return fail("Failed to load config {green}%s", configName); + } + + return success("Loaded config {green}%s", configName); + } + + private int loadVisuals(String inputName) { + String configName = nolongerhuman.configManager.sanitizeName(inputName); + + if (configName.isEmpty()) { + return fail("Invalid config name."); + } + + if (!nolongerhuman.configManager.exists(configName)) { + return fail("Config {green}%s {red}does not exist.", configName); + } + + boolean loaded = nolongerhuman.configManager.loadVisuals(configName); + + if (!loaded) { + return fail("Failed to load visuals from config {green}%s", configName); + } + + return success("Loaded visuals from config {green}%s", configName); + } + + private int deleteConfig(String inputName) { + String configName = nolongerhuman.configManager.sanitizeName(inputName); + + if (configName.isEmpty()) { + return fail("Invalid config name."); + } + + if (!nolongerhuman.configManager.exists(configName)) { + return fail("Config {green}%s {red}does not exist.", configName); + } + + boolean deleted = nolongerhuman.configManager.delete(configName); + + if (!deleted) { + return fail("Failed to delete config {green}%s", configName); + } + + return success("Deleted config {green}%s", configName); + } + + private int listConfigs() { + List configs = nolongerhuman.configManager.getNamedConfigs(); + + if (configs.isEmpty()) { + return success("No named configs saved."); + } + + StringJoiner joiner = new StringJoiner(", "); + configs.forEach(joiner::add); + + return success("Configs (%s): {green}%s", configs.size(), joiner); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/DrawnCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/DrawnCommand.java new file mode 100644 index 0000000..bde203e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/DrawnCommand.java @@ -0,0 +1,51 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import static me.humanbeing.nolongerhuman.features.commands.argument.ModuleArgumentType.getModule; +import static me.humanbeing.nolongerhuman.features.commands.argument.ModuleArgumentType.module; + +public class DrawnCommand extends Command { + public DrawnCommand() { + super("drawn"); + setDescription("Sets modules to be drawn to the arraylist or not"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(literal("all") + .executes((ctx) -> { + int drawn = 0; + int hidden = 0; + + for (Module module : nolongerhuman.moduleManager.getModules()) { + module.setDrawn(!module.isDrawn()); + + if (module.isDrawn()) { + drawn++; + } else { + hidden++; + } + } + + return success("Toggled drawn state for all modules. {green}%s drawn{reset}, {red}%s hidden", drawn, hidden); + })) + .then(argument("module", module()) + .executes((ctx) -> { + Module module = getModule(ctx, "module"); + + module.setDrawn(!module.isDrawn()); + + boolean drawn = module.isDrawn(); + + return success("{gray} %s {reset} is now %s %s", + module.getDisplayName(), + drawn ? "{green}" : "{red}", + drawn ? "drawn" : "hidden"); + })); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/FriendCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/FriendCommand.java new file mode 100644 index 0000000..11bc628 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/FriendCommand.java @@ -0,0 +1,58 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import java.util.List; +import java.util.StringJoiner; + +import static com.mojang.brigadier.arguments.StringArgumentType.getString; +import static com.mojang.brigadier.arguments.StringArgumentType.word; + +public class FriendCommand extends Command { + public FriendCommand() { + super("friend", "friends", "f"); + setDescription("Manages your friends list"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(literal("list") + .executes((ctx) -> { + List friends = nolongerhuman.friendManager.getFriends(); + if (friends.isEmpty()) { + return success("You have no friends :("); + } + StringJoiner joiner = new StringJoiner(","); + friends.forEach(joiner::add); + return success("Friends (%s): %s", friends.size(), joiner); + })) + .then(literal("clear") + .executes((ctx) -> { + nolongerhuman.friendManager.getFriends().clear(); + return success("Cleared friends list"); + })) + .then(literal("add") + .then(argument("username", word()) + .executes((ctx) -> { + String username = getString(ctx, "username"); + if (nolongerhuman.friendManager.isFriend(username)) { + return success("{green} %s {reset} is already on your friends list.", username); + } + nolongerhuman.friendManager.addFriend(username); + return success("Added {green} %s {reset} to your friends list", username); + }))) + .then(literal("remove") + .then(argument("username", word()) + .executes((ctx) -> { + String username = getString(ctx, "username"); + if (!nolongerhuman.friendManager.isFriend(username)) { + return success("{green} %s {reset} is not on your friends list.", username); + } + nolongerhuman.friendManager.removeFriend(username); + return success("Removed {green} %s {reset} from your friends list", username); + }))); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/HelpCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/HelpCommand.java new file mode 100644 index 0000000..1337e47 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/HelpCommand.java @@ -0,0 +1,83 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.google.common.collect.Iterables; +import com.mojang.brigadier.ParseResults; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.tree.CommandNode; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; + +import static me.humanbeing.nolongerhuman.features.commands.argument.CommandArgumentType.command; +import static me.humanbeing.nolongerhuman.features.commands.argument.CommandArgumentType.getCommand; +import static me.humanbeing.nolongerhuman.features.commands.argument.NumberArgumentType.get; +import static me.humanbeing.nolongerhuman.features.commands.argument.NumberArgumentType.number; + +public class HelpCommand extends Command { + private static final int ITEMS_PER_PAGE = 5; + + public HelpCommand() { + super("help", "commands", "h", "cmds"); + setDescription("Displays all executable commands and additional information"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(argument("page", number(Integer.class)) + .executes((ctx) -> helpCommands(ctx, get(Integer.class, ctx, "page"))) + .then(argument("command_name", command()) + .executes(this::helpSpecific)) + .executes((ctx) -> helpCommands(ctx, 1))); + } + + private int helpSpecific(CommandContext ctx) { + Command command = getCommand(ctx, "command_name"); + sendMessage("Usages for %s:", command.getName()); + + ParseResults results = ctx.getSource().getDispatcher() + .parse(command.getName(), ctx.getSource()); + if (results.getContext().getNodes().isEmpty()) { + return success("No usages available"); + } + + Map, String> smartUsages = ctx.getSource().getDispatcher().getSmartUsage( + Iterables.getLast(results.getContext().getNodes()).getNode(), ctx.getSource()); + for (String usage : smartUsages.values()) { + sendMessage(".%s %s", results.getReader().getString(), usage); + } + + return success(); + } + + private int helpCommands(CommandContext ctx, int page) { + List commands = ctx.getSource().getCommands() + .stream().filter(Command::isShown).toList(); + + int pageIndex = page; + int pages = (int) Math.ceil((double) commands.size() / ITEMS_PER_PAGE); + if (pageIndex > pages) { + pageIndex = 1; + } + + List paginated = commands.subList((pageIndex - 1) * ITEMS_PER_PAGE, + Math.min(commands.size(), pageIndex * ITEMS_PER_PAGE)); + + sendMessage("Commands (%s):", "general", commands.size()); + + for (Command command : paginated) { + StringJoiner joiner = new StringJoiner(", "); + for (String alias : command.getAliases()) { + joiner.add(alias); + } + + sendMessage("{dark_gray} %s: {reset}\n %s", "general", + joiner, command.getDescription()); + } + + return success("Page %s/%s", pageIndex, pages); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/LoadVisualsCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/LoadVisualsCommand.java new file mode 100644 index 0000000..80f03f0 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/LoadVisualsCommand.java @@ -0,0 +1,41 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import static me.humanbeing.nolongerhuman.features.commands.argument.ConfigArgumentType.config; +import static me.humanbeing.nolongerhuman.features.commands.argument.ConfigArgumentType.getConfig; + +public class LoadVisualsCommand extends Command { + + public LoadVisualsCommand() { + super("loadvisuals", "visuals", "loadvis"); + setDescription("Loads only visual/client settings and all module colours from a named config"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(argument("config", config()) + .executes(ctx -> { + String config = nolongerhuman.configManager.sanitizeName(getConfig(ctx, "config")); + + if (config.isEmpty()) { + return fail("Invalid config name."); + } + + if (!nolongerhuman.configManager.exists(config)) { + return fail("Config {red}%s{reset} does not exist", config); + } + + boolean loaded = nolongerhuman.configManager.loadVisuals(config); + + if (!loaded) { + return fail("Failed to load visuals from config {red}%s", config); + } + + return success("Loaded visuals from config {green}%s", config); + })); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/PrefixCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/PrefixCommand.java new file mode 100644 index 0000000..7c80402 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/PrefixCommand.java @@ -0,0 +1,28 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import static com.mojang.brigadier.arguments.StringArgumentType.getString; +import static com.mojang.brigadier.arguments.StringArgumentType.word; + +public class PrefixCommand extends Command { + public PrefixCommand() { + super("prefix", "setprefix"); + setDescription("Sets the command prefix"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(argument("prefix", word()) + .executes((ctx) -> { + String prefix = getString(ctx, "prefix"); + if (prefix == null || prefix.isEmpty()) { + return fail("Prefix must contain more than one character"); + } + ctx.getSource().setCommandPrefix(prefix); + return success("Prefix changed to {green} %s", prefix); + })); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/ToggleCommand.java b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/ToggleCommand.java new file mode 100644 index 0000000..994fa04 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/commands/impl/ToggleCommand.java @@ -0,0 +1,30 @@ +package me.humanbeing.nolongerhuman.features.commands.impl; + +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.manager.CommandManager; + +import static me.humanbeing.nolongerhuman.features.commands.argument.ModuleArgumentType.getModule; +import static me.humanbeing.nolongerhuman.features.commands.argument.ModuleArgumentType.module; + +public class ToggleCommand extends Command { + public ToggleCommand() { + super("toggle", "t"); + setDescription("Toggles a module"); + } + + @Override + public void createArgumentBuilder(LiteralArgumentBuilder builder) { + builder.then(argument("module", module(true)) + .executes((ctx) -> { + Module module = getModule(ctx, "module"); + module.toggle(); + boolean toggled = module.isEnabled(); + return success("{gray} %s {reset} is now %s %s", + module.getDisplayName(), + toggled ? "{green}" : "{red}", + toggled ? "enabled" : "disabled"); + })); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/ChinaGUI.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/ChinaGUI.java new file mode 100644 index 0000000..66a4e5c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/ChinaGUI.java @@ -0,0 +1,486 @@ +package me.humanbeing.nolongerhuman.features.gui; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.gui.items.Item; +import me.humanbeing.nolongerhuman.features.gui.items.buttons.ModuleButton; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.NotNull; +import org.lwjgl.glfw.GLFW; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; + +public class ChinaGUI extends Screen { + private static final Minecraft mc = Minecraft.getInstance(); + + private static ChinaGUI INSTANCE; + private static Color colorClipboard = null; + + static { + INSTANCE = new ChinaGUI(); + } + + private final ArrayList widgets = new ArrayList<>(); + + private boolean searchListening; + private String searchText = ""; + + public ChinaGUI() { + super(Component.literal("China")); + setInstance(); + load(); + } + + public static ChinaGUI getInstance() { + if (INSTANCE == null) { + INSTANCE = new ChinaGUI(); + } + + return INSTANCE; + } + + public static ChinaGUI getClickGui() { + return ChinaGUI.getInstance(); + } + + private void setInstance() { + INSTANCE = this; + } + + private void load() { + this.widgets.clear(); + + int x = 8; + int y = 26; + int spacing = 120; + + for (Module.Category category : nolongerhuman.moduleManager.getCategories()) { + if (category == Module.Category.HUD) { + continue; + } + + Widget panel = new Widget(category.getName(), x, y, true); + + nolongerhuman.moduleManager.stream() + .filter(module -> module.getCategory() == category && !module.hidden) + .map(ModuleButton::new) + .forEach(panel::addButton); + + this.widgets.add(panel); + + x += spacing; + } + + Widget configsPanel = new Widget("Configs", x, y, true); + this.widgets.add(configsPanel); + + this.widgets.forEach(widget -> + widget.getItems().sort(Comparator.comparing(Feature::getName)) + ); + } + + @Override + public void render(@NotNull GuiGraphics context, int mouseX, int mouseY, float delta) { + Item.context = context; + + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + if (clickGui.blurBackground.getValue()) { + context.fill( + 0, + 0, + context.guiWidth(), + context.guiHeight(), + clickGui.backgroundColor.getValue().getRGB() + ); + + RenderUtil.verticalGradient( + context, + 0, + 0, + context.guiWidth(), + context.guiHeight(), + new Color(0, 0, 0, 25), + clickGui.vignetteColor.getValue() + ); + } + + updateWidgetSearchQueries(); + drawTopBar(context); + + this.widgets.forEach(widget -> widget.drawScreen(context, mouseX, mouseY, delta)); + + if (clickGui.descriptions.getValue()) { + drawDescriptionBar(context, mouseX, mouseY); + } + + if (clickGui.searchBar.getValue()) { + drawSearchBar(context); + } + } + + private void updateWidgetSearchQueries() { + for (Widget widget : this.widgets) { + widget.setSearchQuery(this.searchText); + } + } + + private void drawTopBar(GuiGraphics context) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + RenderUtil.rect( + context, + 0, + 0, + context.guiWidth(), + 18, + new Color(0, 0, 0, 115).getRGB() + ); + + RenderUtil.horizontalGradient( + context, + 0, + 17, + context.guiWidth(), + 18, + clickGui.topColor.getValue(), + clickGui.secondaryColor.getValue() + ); + + String title = "nolongerhuman"; + String hint = "Right click modules/configs to expand • Drag panels • " + + nolongerhuman.commandManager.getCommandPrefix() + + "help"; + + context.drawString( + mc.font, + title, + 8, + 5, + clickGui.categoryTextColor.getValue().getRGB() + ); + + context.drawString( + mc.font, + hint, + context.guiWidth() - mc.font.width(hint) - 8, + 5, + clickGui.disabledTextColor.getValue().getRGB() + ); + } + + private void drawDescriptionBar(GuiGraphics context, int mouseX, int mouseY) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + String text = getHoveredDescription(mouseX, mouseY); + + if (text == null || text.isBlank()) { + text = "Hover over a module to see its description"; + } + + int width = Math.max(170, Math.min(context.guiWidth() - 24, mc.font.width(text) + 18)); + int x = context.guiWidth() / 2 - width / 2; + int y = 4; + + RenderUtil.rect( + context, + x, + y, + x + width, + y + 12, + new Color(0, 0, 0, 95).getRGB() + ); + + RenderUtil.rect( + context, + x, + y, + x + width, + y + 1, + clickGui.topColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + x, + y + 11, + x + width, + y + 12, + clickGui.panelBorderColor.getValue().getRGB() + ); + + context.drawString( + mc.font, + trimToWidth(text, width - 10), + x + 5, + y + 3, + clickGui.textColor.getValue().getRGB() + ); + } + + private String getHoveredDescription(int mouseX, int mouseY) { + for (Widget widget : widgets) { + String hovered = widget.getHoveredDescription(mouseX, mouseY); + + if (hovered != null && !hovered.isBlank()) { + return hovered; + } + } + + return null; + } + + private void drawSearchBar(GuiGraphics context) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + int margin = 8; + int height = 16; + int width = Math.min(260, context.guiWidth() - margin * 2); + int x = context.guiWidth() / 2 - width / 2; + int y = context.guiHeight() - height - 8; + + RenderUtil.rect( + context, + x + 2, + y + 2, + x + width + 2, + y + height + 2, + clickGui.panelShadowColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + x, + y, + x + width, + y + height, + clickGui.searchBarColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + x, + y, + x + width, + y + 1, + searchListening + ? clickGui.topColor.getValue().getRGB() + : clickGui.searchBorderColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + x, + y + height - 1, + x + width, + y + height, + clickGui.searchBorderColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + x, + y, + x + 1, + y + height, + clickGui.searchBorderColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + x + width - 1, + y, + x + width, + y + height, + clickGui.searchBorderColor.getValue().getRGB() + ); + + String label; + + if (searchText.isEmpty()) { + label = searchListening ? "Search..." + getCursor() : "Search modules/configs..."; + } else { + label = searchText + (searchListening ? getCursor() : ""); + } + + int textColor = searchText.isEmpty() + ? clickGui.searchPlaceholderColor.getValue().getRGB() + : clickGui.searchTextColor.getValue().getRGB(); + + context.drawString( + mc.font, + trimToWidth(label, width - 16), + x + 8, + y + 4, + textColor + ); + } + + private boolean isHoveringSearchBar(double mouseX, double mouseY) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + if (!clickGui.searchBar.getValue()) { + return false; + } + + int margin = 8; + int height = 16; + int width = Math.min(260, mc.getWindow().getGuiScaledWidth() - margin * 2); + int x = mc.getWindow().getGuiScaledWidth() / 2 - width / 2; + int y = mc.getWindow().getGuiScaledHeight() - height - 8; + + return mouseX >= x + && mouseX <= x + width + && mouseY >= y + && mouseY <= y + height; + } + + private String getCursor() { + return System.currentTimeMillis() % 1000L > 500L ? "_" : ""; + } + + private String trimToWidth(String text, int maxWidth) { + if (text == null) { + return ""; + } + + if (mc.font.width(text) <= maxWidth) { + return text; + } + + String suffix = "..."; + int targetWidth = Math.max(0, maxWidth - mc.font.width(suffix)); + String trimmed = text; + + while (!trimmed.isEmpty() && mc.font.width(trimmed) > targetWidth) { + trimmed = trimmed.substring(0, trimmed.length() - 1); + } + + return trimmed + suffix; + } + + @Override + public void renderBackground(@NotNull GuiGraphics context, int mouseX, int mouseY, float delta) { + } + + @Override + public boolean mouseClicked(@NotNull MouseButtonEvent click, boolean doubled) { + if (isHoveringSearchBar(click.x(), click.y())) { + searchListening = true; + return true; + } + + searchListening = false; + + this.widgets.forEach(widget -> + widget.mouseClicked((int) click.x(), (int) click.y(), click.button()) + ); + + return super.mouseClicked(click, doubled); + } + + @Override + public boolean mouseReleased(@NotNull MouseButtonEvent click) { + this.widgets.forEach(widget -> + widget.mouseReleased((int) click.x(), (int) click.y(), click.button()) + ); + + return super.mouseReleased(click); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) { + if (verticalAmount < 0.0D) { + this.widgets.forEach(widget -> widget.setY(widget.getY() - 10)); + } else if (verticalAmount > 0.0D) { + this.widgets.forEach(widget -> widget.setY(widget.getY() + 10)); + } + + return super.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount); + } + + @Override + public boolean keyPressed(@NotNull KeyEvent input) { + if (searchListening) { + int key = input.input(); + + if (key == GLFW.GLFW_KEY_BACKSPACE) { + if (!searchText.isEmpty()) { + searchText = searchText.substring(0, searchText.length() - 1); + } + + return true; + } + + if (key == GLFW.GLFW_KEY_ESCAPE) { + if (!searchText.isEmpty()) { + searchText = ""; + return true; + } + + searchListening = false; + return true; + } + + if (key == GLFW.GLFW_KEY_ENTER) { + searchListening = false; + return true; + } + + return super.keyPressed(input); + } + + this.widgets.forEach(widget -> widget.onKeyPressed(input.input())); + + return super.keyPressed(input); + } + + @Override + public boolean charTyped(@NotNull CharacterEvent input) { + if (searchListening) { + String typed = input.codepointAsString(); + + if (typed != null && !typed.isBlank() && typed.length() == 1) { + searchText += typed; + } + + return true; + } + + this.widgets.forEach(widget -> widget.onKeyTyped(input.codepointAsString(), input.modifiers())); + + return super.charTyped(input); + } + + @Override + public boolean isPauseScreen() { + return false; + } + + public final ArrayList getComponents() { + return this.widgets; + } + + public int getTextOffset() { + return -6; + } + + public static Color getColorClipboard() { + return colorClipboard; + } + + public static void setColorClipboard(Color color) { + colorClipboard = color; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/HudEditorScreen.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/HudEditorScreen.java new file mode 100644 index 0000000..f06990a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/HudEditorScreen.java @@ -0,0 +1,106 @@ +package me.humanbeing.nolongerhuman.features.gui; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.gui.items.Item; +import me.humanbeing.nolongerhuman.features.gui.items.buttons.ModuleButton; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; + +import java.util.ArrayList; +import java.util.Comparator; + +public class HudEditorScreen extends Screen { + private static HudEditorScreen INSTANCE; + + private final ArrayList components = new ArrayList<>(); + + public HudModule currentDragging; + public boolean anyHover; + + private HudEditorScreen() { + super(Component.literal("nolongerhuman-hudeditor")); + load(); + } + + private void load() { + Widget hud = new Widget("Hud", 50, 50, true); + + nolongerhuman.moduleManager.stream() + .filter(m -> m.getCategory() == Module.Category.HUD && !m.hidden) + .map(ModuleButton::new) + .forEach(hud::addButton); + + this.components.add(hud); + this.components.forEach(component -> component.getItems().sort(Comparator.comparing(Feature::getName))); + } + + @Override + public void render(GuiGraphics context, int mouseX, int mouseY, float delta) { + Item.context = context; + anyHover = false; + this.components.forEach(component -> component.drawScreen(context, mouseX, mouseY, delta)); + } + + @Override + public boolean mouseClicked(MouseButtonEvent click, boolean doubled) { + this.components.forEach(component -> component.mouseClicked((int) click.x(), (int) click.y(), click.button())); + return super.mouseClicked(click, doubled); + } + + @Override + public boolean mouseReleased(MouseButtonEvent click) { + this.components.forEach(component -> component.mouseReleased((int) click.x(), (int) click.y(), click.button())); + return super.mouseReleased(click); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) { + if (verticalAmount < 0) { + this.components.forEach(component -> component.setY(component.getY() - 10)); + } else if (verticalAmount > 0) { + this.components.forEach(component -> component.setY(component.getY() + 10)); + } + + return super.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount); + } + + @Override + public boolean keyPressed(KeyEvent input) { + this.components.forEach(component -> component.onKeyPressed(input.input())); + return super.keyPressed(input); + } + + @Override + public boolean charTyped(CharacterEvent input) { + this.components.forEach(component -> component.onKeyTyped(input.codepointAsString(), input.modifiers())); + return super.charTyped(input); + } + + @Override + public boolean isPauseScreen() { + return false; + } + + @Override + public void renderBackground(GuiGraphics context, int mouseX, int mouseY, float delta) { + } + + public ArrayList getComponents() { + return components; + } + + public static HudEditorScreen getInstance() { + if (INSTANCE == null) { + INSTANCE = new HudEditorScreen(); + } + + return INSTANCE; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/Widget.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/Widget.java new file mode 100644 index 0000000..cdc1b68 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/Widget.java @@ -0,0 +1,903 @@ +package me.humanbeing.nolongerhuman.features.gui; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.gui.items.Item; +import me.humanbeing.nolongerhuman.features.gui.items.buttons.Button; +import me.humanbeing.nolongerhuman.features.gui.items.buttons.ConfigButton; +import me.humanbeing.nolongerhuman.features.gui.items.buttons.ModuleButton; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import me.humanbeing.nolongerhuman.util.render.ScissorUtil; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +public class Widget extends Feature { + protected GuiGraphics context; + + private static final int CAT_EAR_WIDTH = 30; + private static final int CAT_EAR_HEIGHT = 18; + private static final int CAT_EAR_FILL_INSET = 3; + private static final int CAT_EAR_INNER_INSET = 8; + + private final List items = new ArrayList<>(); + + public boolean drag; + + private int x; + private int y; + private int x2; + private int y2; + private int width; + private int height; + private boolean open; + private boolean hidden = false; + private String searchQuery = ""; + + public Widget(String name, int x, int y, boolean open) { + super(name); + + this.x = x; + this.y = y; + this.width = 114; + this.height = 16; + this.open = open; + + if (isConfigsPanel()) { + refreshConfigButtons(); + } + } + + private boolean isConfigsPanel() { + return this.getName().equalsIgnoreCase("Configs"); + } + + private void refreshConfigButtons() { + if (!isConfigsPanel()) { + return; + } + + this.items.clear(); + + for (String config : nolongerhuman.configManager.getNamedConfigs()) { + this.items.add(new ConfigButton(config, this::refreshConfigButtons)); + } + } + + private void drag(int mouseX, int mouseY) { + if (!this.drag) { + return; + } + + this.x = this.x2 + mouseX; + this.y = this.y2 + mouseY; + } + + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + this.context = context; + this.drag(mouseX, mouseY); + + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + int panelTop = this.y; + int headerBottom = this.y + this.height; + + int bodyBottom = this.open + ? this.y + this.height + (int) this.getTotalItemHeight() + 4 + : headerBottom; + + if (clickGui.shadows.getValue()) { + if (clickGui.catEars.getValue()) { + drawCatEars( + context, + this.x + 3, + panelTop + 3, + new Color(0, 0, 0, 90), + new Color(0, 0, 0, 65), + new Color(0, 0, 0, 35) + ); + + drawCatEars( + context, + this.x + 1, + panelTop + 1, + new Color(0, 0, 0, 65), + new Color(0, 0, 0, 45), + new Color(0, 0, 0, 25) + ); + } + + RenderUtil.rect( + context, + this.x + 3, + panelTop + 3, + this.x + this.width + 3, + bodyBottom + 3, + clickGui.panelShadowColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + this.x + 1, + panelTop + 1, + this.x + this.width + 1, + bodyBottom + 1, + new Color(0, 0, 0, 70).getRGB() + ); + } + + drawPanelBorderGlow(context, clickGui, panelTop, bodyBottom); + drawPanelBackground(context, clickGui, panelTop, bodyBottom); + + RenderUtil.horizontalGradient( + context, + this.x, + panelTop, + this.x + this.width, + headerBottom, + clickGui.topColor.getValue(), + clickGui.color.getValue() + ); + + drawPanelBorderLines(context, clickGui, panelTop, bodyBottom); + + if (this.open) { + RenderUtil.rect( + context, + this.x + 1, + headerBottom, + this.x + this.width - 1, + headerBottom + 1, + new Color(255, 255, 255, 28).getRGB() + ); + } + + if (clickGui.catEars.getValue()) { + drawCatEars( + context, + this.x, + panelTop, + clickGui.catEarBorderColor.getValue(), + clickGui.catEarColor.getValue(), + clickGui.catEarInnerColor.getValue() + ); + } + + drawTrimmedString( + this.getName(), + this.x + 6, + this.y + 4, + this.width - 12, + clickGui.categoryTextColor.getValue().getRGB() + ); + + if (!this.open) { + return; + } + + ScissorUtil.enable( + context, + this.x, + 0, + this.x + this.width, + mc.getWindow().getGuiScaledHeight() + ); + + float itemY = this.y + this.height + 3.0F; + + if (isConfigsPanel() && this.items.isEmpty()) { + drawTrimmedString( + "No named configs", + this.x + 6.0F, + itemY + 3.0F, + this.width - 12, + clickGui.disabledTextColor.getValue().getRGB() + ); + + ScissorUtil.disable(context); + return; + } + + for (Item item : this.getItems()) { + item.update(); + + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + item.setLocation(this.x + 3.0F, itemY); + item.setWidth(this.getWidth() - 6); + item.drawScreen(context, mouseX, mouseY, partialTicks); + + itemY += item.getHeight() + 1.0F; + } + + ScissorUtil.disable(context); + } + + private void drawPanelBorderGlow( + GuiGraphics context, + ClickGuiModule clickGui, + int panelTop, + int bodyBottom + ) { + if (!clickGui.panelBorderGlow.getValue()) { + return; + } + + int radius = clickGui.panelBorderGlowRadius.getValue(); + + if (radius <= 0) { + return; + } + + Color base = clickGui.panelBorderGlowColor.getValue(); + + for (int layer = radius; layer >= 1; layer--) { + double progress = (double) (radius - layer + 1) / (double) radius; + double alphaMultiplier = progress * progress; + + Color glow = withAlphaMultiplier(base, alphaMultiplier); + + RenderUtil.rect( + context, + this.x - layer, + panelTop - layer, + this.x + this.width + layer, + panelTop - layer + 1, + glow.getRGB() + ); + + RenderUtil.rect( + context, + this.x - layer, + bodyBottom + layer - 1, + this.x + this.width + layer, + bodyBottom + layer, + glow.getRGB() + ); + + RenderUtil.rect( + context, + this.x - layer, + panelTop - layer, + this.x - layer + 1, + bodyBottom + layer, + glow.getRGB() + ); + + RenderUtil.rect( + context, + this.x + this.width + layer - 1, + panelTop - layer, + this.x + this.width + layer, + bodyBottom + layer, + glow.getRGB() + ); + } + + Color coreGlow = withAlphaMultiplier(base, 0.65D); + + RenderUtil.rect( + context, + this.x - 1, + panelTop - 1, + this.x + this.width + 1, + panelTop, + coreGlow.getRGB() + ); + + RenderUtil.rect( + context, + this.x - 1, + bodyBottom, + this.x + this.width + 1, + bodyBottom + 1, + coreGlow.getRGB() + ); + + RenderUtil.rect( + context, + this.x - 1, + panelTop, + this.x, + bodyBottom, + coreGlow.getRGB() + ); + + RenderUtil.rect( + context, + this.x + this.width, + panelTop, + this.x + this.width + 1, + bodyBottom, + coreGlow.getRGB() + ); + } + + private void drawPanelBackground( + GuiGraphics context, + ClickGuiModule clickGui, + int panelTop, + int bodyBottom + ) { + if (!clickGui.panelBackgroundGradient.getValue()) { + RenderUtil.rect( + context, + this.x, + panelTop, + this.x + this.width, + bodyBottom, + clickGui.panelColor.getValue().getRGB() + ); + + if (this.open) { + RenderUtil.rect( + context, + this.x + 1, + panelTop + this.height, + this.x + this.width - 1, + bodyBottom - 1, + clickGui.panelBodyColor.getValue().getRGB() + ); + } + + return; + } + + drawGradient( + context, + this.x, + panelTop, + this.x + this.width, + bodyBottom, + clickGui.panelGradientStart.getValue(), + clickGui.panelGradientEnd.getValue(), + clickGui.panelGradientDirection.getValue() + ); + } + + private void drawPanelBorderLines( + GuiGraphics context, + ClickGuiModule clickGui, + int panelTop, + int bodyBottom + ) { + RenderUtil.rect( + context, + this.x, + panelTop, + this.x + this.width, + panelTop + 1, + clickGui.secondaryColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + this.x, + panelTop, + this.x + 1, + bodyBottom, + clickGui.panelBorderColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + this.x + this.width - 1, + panelTop, + this.x + this.width, + bodyBottom, + clickGui.panelBorderColor.getValue().getRGB() + ); + + RenderUtil.rect( + context, + this.x, + bodyBottom - 1, + this.x + this.width, + bodyBottom, + clickGui.panelBorderColor.getValue().getRGB() + ); + } + + private void drawGradient( + GuiGraphics context, + float left, + float top, + float right, + float bottom, + Color start, + Color end, + ClickGuiModule.GradientDirection direction + ) { + switch (direction) { + case LeftToRight -> RenderUtil.horizontalGradient(context, left, top, right, bottom, start, end); + case RightToLeft -> RenderUtil.horizontalGradient(context, left, top, right, bottom, end, start); + case TopToBottom -> RenderUtil.verticalGradient(context, left, top, right, bottom, start, end); + case BottomToTop -> RenderUtil.verticalGradient(context, left, top, right, bottom, end, start); + } + } + + private void drawCatEars( + GuiGraphics context, + int panelX, + int panelTop, + Color borderColor, + Color fillColor, + Color innerColor + ) { + drawLeftCatEar(context, panelX, panelTop, borderColor, fillColor, innerColor); + drawRightCatEar(context, panelX, panelTop, borderColor, fillColor, innerColor); + } + + private void drawLeftCatEar( + GuiGraphics context, + int panelX, + int panelTop, + Color borderColor, + Color fillColor, + Color innerColor + ) { + double outerBaseLeft = panelX; + double outerBaseRight = panelX + CAT_EAR_WIDTH; + double outerBaseY = panelTop + 1.0D; + double outerPeakX = panelX + 5.0D; + double outerPeakY = panelTop - CAT_EAR_HEIGHT; + + drawSmoothTriangle( + context, + outerPeakX, + outerPeakY, + outerBaseLeft, + outerBaseY, + outerBaseRight, + outerBaseY, + borderColor + ); + + double fillBaseLeft = outerBaseLeft + CAT_EAR_FILL_INSET; + double fillBaseRight = outerBaseRight - CAT_EAR_FILL_INSET; + double fillBaseY = outerBaseY; + double fillPeakX = outerPeakX + 1.5D; + double fillPeakY = outerPeakY + CAT_EAR_FILL_INSET; + + drawSmoothTriangle( + context, + fillPeakX, + fillPeakY, + fillBaseLeft, + fillBaseY, + fillBaseRight, + fillBaseY, + fillColor + ); + + double innerBaseLeft = outerBaseLeft + CAT_EAR_INNER_INSET; + double innerBaseRight = outerBaseRight - 8.0D; + double innerBaseY = outerBaseY - 1.0D; + double innerPeakX = outerPeakX + 4.0D; + double innerPeakY = outerPeakY + 8.0D; + + drawSmoothTriangle( + context, + innerPeakX, + innerPeakY, + innerBaseLeft, + innerBaseY, + innerBaseRight, + innerBaseY, + innerColor + ); + } + + private void drawRightCatEar( + GuiGraphics context, + int panelX, + int panelTop, + Color borderColor, + Color fillColor, + Color innerColor + ) { + double outerBaseLeft = panelX + this.width - CAT_EAR_WIDTH; + double outerBaseRight = panelX + this.width; + double outerBaseY = panelTop + 1.0D; + double outerPeakX = panelX + this.width - 5.0D; + double outerPeakY = panelTop - CAT_EAR_HEIGHT; + + drawSmoothTriangle( + context, + outerPeakX, + outerPeakY, + outerBaseLeft, + outerBaseY, + outerBaseRight, + outerBaseY, + borderColor + ); + + double fillBaseLeft = outerBaseLeft + CAT_EAR_FILL_INSET; + double fillBaseRight = outerBaseRight - CAT_EAR_FILL_INSET; + double fillBaseY = outerBaseY; + double fillPeakX = outerPeakX - 1.5D; + double fillPeakY = outerPeakY + CAT_EAR_FILL_INSET; + + drawSmoothTriangle( + context, + fillPeakX, + fillPeakY, + fillBaseLeft, + fillBaseY, + fillBaseRight, + fillBaseY, + fillColor + ); + + double innerBaseLeft = outerBaseLeft + 8.0D; + double innerBaseRight = outerBaseRight - CAT_EAR_INNER_INSET; + double innerBaseY = outerBaseY - 1.0D; + double innerPeakX = outerPeakX - 4.0D; + double innerPeakY = outerPeakY + 8.0D; + + drawSmoothTriangle( + context, + innerPeakX, + innerPeakY, + innerBaseLeft, + innerBaseY, + innerBaseRight, + innerBaseY, + innerColor + ); + } + + private void drawSmoothTriangle( + GuiGraphics context, + double x1, + double y1, + double x2, + double y2, + double x3, + double y3, + Color color + ) { + int minY = (int) Math.floor(Math.min(y1, Math.min(y2, y3))); + int maxY = (int) Math.ceil(Math.max(y1, Math.max(y2, y3))); + + for (int y = minY; y <= maxY; y++) { + double scanY = y + 0.5D; + double[] intersections = new double[3]; + int count = 0; + + count = addIntersection(intersections, count, scanY, x1, y1, x2, y2); + count = addIntersection(intersections, count, scanY, x2, y2, x3, y3); + count = addIntersection(intersections, count, scanY, x3, y3, x1, y1); + + if (count < 2) { + continue; + } + + double minX = intersections[0]; + double maxX = intersections[0]; + + for (int i = 1; i < count; i++) { + minX = Math.min(minX, intersections[i]); + maxX = Math.max(maxX, intersections[i]); + } + + RenderUtil.rect( + context, + (float) minX, + y, + (float) maxX, + y + 1.0F, + color.getRGB() + ); + } + } + + private int addIntersection( + double[] intersections, + int count, + double scanY, + double x1, + double y1, + double x2, + double y2 + ) { + if (y1 == y2) { + return count; + } + + double minY = Math.min(y1, y2); + double maxY = Math.max(y1, y2); + + if (scanY < minY || scanY >= maxY) { + return count; + } + + double progress = (scanY - y1) / (y2 - y1); + intersections[count] = x1 + progress * (x2 - x1); + + return count + 1; + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = Math.max(0.0D, Math.min(1.0D, multiplier)); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (mouseButton == 0 && this.isHovering(mouseX, mouseY)) { + this.x2 = this.x - mouseX; + this.y2 = this.y - mouseY; + + ChinaGUI.getClickGui().getComponents().forEach(component -> { + if (component.drag) { + component.drag = false; + } + }); + + this.drag = true; + return; + } + + if (mouseButton == 1 && this.isHovering(mouseX, mouseY)) { + this.open = !this.open; + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + return; + } + + if (!this.open) { + return; + } + + for (Item item : this.getItems()) { + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + item.mouseClicked(mouseX, mouseY, mouseButton); + } + } + + public void mouseReleased(int mouseX, int mouseY, int releaseButton) { + if (releaseButton == 0) { + this.drag = false; + } + + if (!this.open) { + return; + } + + for (Item item : this.getItems()) { + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + item.mouseReleased(mouseX, mouseY, releaseButton); + } + } + + public void onKeyTyped(String typedChar, int keyCode) { + if (!this.open) { + return; + } + + for (Item item : this.getItems()) { + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + item.onKeyTyped(typedChar, keyCode); + } + } + + public void onKeyPressed(int key) { + if (!open) { + return; + } + + for (Item item : this.getItems()) { + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + item.onKeyPressed(key); + } + } + + public void addButton(Button button) { + if (isConfigsPanel()) { + return; + } + + this.items.add(button); + } + + public String getHoveredDescription(int mouseX, int mouseY) { + if (!this.open) { + return null; + } + + for (Item item : this.items) { + item.update(); + + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + if (item instanceof ModuleButton moduleButton && moduleButton.isHovering(mouseX, mouseY)) { + return moduleButton.getModuleDescription(); + } + } + + return null; + } + + public String getHoveredItemName(int mouseX, int mouseY) { + if (!this.open) { + return null; + } + + for (Item item : this.items) { + item.update(); + + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + if (item.isHovering(mouseX, mouseY)) { + return item.getName(); + } + } + + if (this.isHovering(mouseX, mouseY)) { + return this.getName(); + } + + return null; + } + + public void setSearchQuery(String searchQuery) { + if (searchQuery == null) { + this.searchQuery = ""; + return; + } + + this.searchQuery = searchQuery.trim().toLowerCase(Locale.ROOT); + } + + private boolean isFilteredOut(Item item) { + if (this.searchQuery.isEmpty()) { + return false; + } + + if (item instanceof ModuleButton moduleButton) { + return !moduleButton.matchesSearch(this.searchQuery); + } + + return !item.getName().toLowerCase(Locale.ROOT).contains(this.searchQuery); + } + + public int getX() { + return this.x; + } + + public void setX(int x) { + this.x = x; + } + + public int getY() { + return this.y; + } + + public void setY(int y) { + this.y = y; + } + + public int getWidth() { + return this.width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return this.height; + } + + public void setHeight(int height) { + this.height = height; + } + + public boolean isHidden() { + return this.hidden; + } + + public void setHidden(boolean hidden) { + this.hidden = hidden; + } + + public boolean isOpen() { + return this.open; + } + + public final List getItems() { + return this.items; + } + + public boolean isHovering(int mouseX, int mouseY) { + return mouseX >= this.getX() + && mouseX <= this.getX() + this.getWidth() + && mouseY >= this.getY() + && mouseY <= this.getY() + this.getHeight(); + } + + private float getTotalItemHeight() { + if (isConfigsPanel() && this.items.isEmpty()) { + return 15.0F; + } + + float totalHeight = 0.0F; + + for (Item item : this.getItems()) { + item.update(); + + if (item.isHidden() || isFilteredOut(item)) { + continue; + } + + totalHeight += item.getHeight() + 1.0F; + } + + return totalHeight; + } + + protected void drawString(String text, double x, double y, Color color) { + drawString(text, x, y, color.getRGB()); + } + + protected void drawString(String text, double x, double y, int color) { + context.drawString(mc.font, text, (int) x, (int) y, color); + } + + protected void drawTrimmedString(String text, double x, double y, int maxWidth, int color) { + context.drawString(mc.font, trimToWidth(text, maxWidth), (int) x, (int) y, color); + } + + protected String trimToWidth(String text, int maxWidth) { + if (text == null) { + return ""; + } + + if (mc.font.width(text) <= maxWidth) { + return text; + } + + String suffix = "..."; + int targetWidth = Math.max(0, maxWidth - mc.font.width(suffix)); + String trimmed = text; + + while (!trimmed.isEmpty() && mc.font.width(trimmed) > targetWidth) { + trimmed = trimmed.substring(0, trimmed.length() - 1); + } + + return trimmed + suffix; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/Item.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/Item.java new file mode 100644 index 0000000..84645bf --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/Item.java @@ -0,0 +1,342 @@ +package me.humanbeing.nolongerhuman.features.gui.items; + +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.gui.GuiGraphics; + +import java.awt.Color; + +public class Item extends Feature { + public static GuiGraphics context; + + protected float x; + protected float y; + protected int width; + protected int height; + + private boolean hidden; + + public Item(String name) { + super(name); + } + + public void setLocation(float x, float y) { + this.x = x; + this.y = y; + } + + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + } + + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + } + + public void mouseReleased(int mouseX, int mouseY, int releaseButton) { + } + + public void update() { + } + + public void onKeyTyped(String typedChar, int keyCode) { + } + + public void onKeyPressed(int key) { + } + + public float getX() { + return this.x; + } + + public float getY() { + return this.y; + } + + public int getWidth() { + return this.width; + } + + public void setWidth(int width) { + this.width = width; + } + + public int getHeight() { + return this.height; + } + + public void setHeight(int height) { + this.height = height; + } + + public boolean isHidden() { + return this.hidden; + } + + public boolean setHidden(boolean hidden) { + this.hidden = hidden; + return this.hidden; + } + + protected void drawRowBackground(GuiGraphics context, ClickGuiModule clickGui, boolean hovering) { + if (hovering) { + if (clickGui.rowHoverGradient.getValue()) { + drawGradient( + context, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.rowHoverGradientStart.getValue(), + clickGui.rowHoverGradientEnd.getValue(), + clickGui.rowHoverGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, this.x, this.y, this.x + this.width, this.y + this.height, clickGui.rowHoverColor.getValue().getRGB()); + } + return; + } + + if (clickGui.rowGradient.getValue()) { + drawGradient( + context, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.rowGradientStart.getValue(), + clickGui.rowGradientEnd.getValue(), + clickGui.rowGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, this.x, this.y, this.x + this.width, this.y + this.height, clickGui.rowColor.getValue().getRGB()); + } + } + + protected void drawSettingBackground(GuiGraphics context, ClickGuiModule clickGui, boolean hovering) { + if (hovering) { + if (clickGui.settingHoverGradient.getValue()) { + drawGradient( + context, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.settingHoverGradientStart.getValue(), + clickGui.settingHoverGradientEnd.getValue(), + clickGui.settingHoverGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, this.x, this.y, this.x + this.width, this.y + this.height, clickGui.rowHoverColor.getValue().getRGB()); + } + return; + } + + if (clickGui.settingGradient.getValue()) { + drawGradient( + context, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.settingGradientStart.getValue(), + clickGui.settingGradientEnd.getValue(), + clickGui.settingGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, this.x, this.y, this.x + this.width, this.y + this.height, clickGui.rowSettingColor.getValue().getRGB()); + } + } + + protected void drawEnabledOverlay(GuiGraphics context, ClickGuiModule clickGui, float leftOffset) { + float left = this.x + leftOffset; + + if (!clickGui.enabledGradient.getValue()) { + RenderUtil.rect(context, left, this.y, this.x + this.width, this.y + this.height, clickGui.enabledOverlayColor.getValue().getRGB()); + return; + } + + drawGradient( + context, + left, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.enabledGradientStart.getValue(), + clickGui.enabledGradientEnd.getValue(), + clickGui.enabledGradientDirection.getValue() + ); + } + + protected void drawDisabledOverlay(GuiGraphics context, ClickGuiModule clickGui) { + if (!clickGui.disabledGradient.getValue()) { + return; + } + + drawGradient( + context, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.disabledGradientStart.getValue(), + clickGui.disabledGradientEnd.getValue(), + clickGui.disabledGradientDirection.getValue() + ); + } + + protected void drawAccentBar(GuiGraphics context, ClickGuiModule clickGui, float width) { + if (clickGui.accentGradient.getValue()) { + drawGradient( + context, + this.x, + this.y, + this.x + width, + this.y + this.height, + clickGui.accentGradientStart.getValue(), + clickGui.accentGradientEnd.getValue(), + clickGui.accentGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, this.x, this.y, this.x + width, this.y + this.height, clickGui.color.getValue().getRGB()); + } + } + + protected void drawSliderFill( + GuiGraphics context, + ClickGuiModule clickGui, + float left, + float top, + float right, + float bottom + ) { + if (clickGui.sliderGradient.getValue()) { + drawGradient( + context, + left, + top, + right, + bottom, + clickGui.sliderGradientStart.getValue(), + clickGui.sliderGradientEnd.getValue(), + clickGui.sliderGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, left, top, right, bottom, clickGui.color.getValue().getRGB()); + } + } + + protected void drawSmallButtonBackground( + GuiGraphics context, + ClickGuiModule clickGui, + float left, + float top, + float right, + float bottom, + boolean hovering + ) { + if (hovering) { + if (clickGui.smallButtonHoverGradient.getValue()) { + drawGradient( + context, + left, + top, + right, + bottom, + clickGui.smallButtonHoverGradientStart.getValue(), + clickGui.smallButtonHoverGradientEnd.getValue(), + clickGui.smallButtonHoverGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, left, top, right, bottom, clickGui.topColor.getValue().getRGB()); + } + return; + } + + if (clickGui.smallButtonGradient.getValue()) { + drawGradient( + context, + left, + top, + right, + bottom, + clickGui.smallButtonGradientStart.getValue(), + clickGui.smallButtonGradientEnd.getValue(), + clickGui.smallButtonGradientDirection.getValue() + ); + } else { + RenderUtil.rect(context, left, top, right, bottom, clickGui.rowColor.getValue().getRGB()); + } + } + + protected void drawListeningOverlay(GuiGraphics context, ClickGuiModule clickGui) { + if (!clickGui.listeningGradient.getValue()) { + RenderUtil.rect(context, this.x, this.y, this.x + this.width, this.y + this.height, clickGui.listeningTextColor.getValue().getRGB()); + return; + } + + drawGradient( + context, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + clickGui.listeningGradientStart.getValue(), + clickGui.listeningGradientEnd.getValue(), + clickGui.listeningGradientDirection.getValue() + ); + } + + protected void drawGradient( + GuiGraphics context, + float left, + float top, + float right, + float bottom, + Color start, + Color end, + ClickGuiModule.GradientDirection direction + ) { + switch (direction) { + case LeftToRight -> RenderUtil.horizontalGradient(context, left, top, right, bottom, start, end); + case RightToLeft -> RenderUtil.horizontalGradient(context, left, top, right, bottom, end, start); + case TopToBottom -> RenderUtil.verticalGradient(context, left, top, right, bottom, start, end); + case BottomToTop -> RenderUtil.verticalGradient(context, left, top, right, bottom, end, start); + } + } + + protected void drawString(String text, double x, double y, Color color) { + drawString(text, x, y, color.getRGB()); + } + + protected void drawString(String text, double x, double y, int color) { + context.drawString(mc.font, text, (int) x, (int) y, color); + } + + protected void drawTrimmedString(String text, double x, double y, int maxWidth, int color) { + context.drawString(mc.font, trimToWidth(text, maxWidth), (int) x, (int) y, color); + } + + protected String trimToWidth(String text, int maxWidth) { + if (text == null) { + return ""; + } + + if (mc.font.width(text) <= maxWidth) { + return text; + } + + String suffix = "..."; + int targetWidth = Math.max(0, maxWidth - mc.font.width(suffix)); + String trimmed = text; + + while (!trimmed.isEmpty() && mc.font.width(trimmed) > targetWidth) { + trimmed = trimmed.substring(0, trimmed.length() - 1); + } + + return trimmed + suffix; + } + + public boolean isHovering(int mouseX, int mouseY) { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/BindButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/BindButton.java new file mode 100644 index 0000000..44cc3a6 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/BindButton.java @@ -0,0 +1,126 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Bind; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; +import org.lwjgl.glfw.GLFW; + +public class BindButton extends Button { + private final Setting setting; + public boolean isListening; + + public BindButton(Setting setting) { + super(setting.getName()); + this.setting = setting; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + boolean hovering = this.isHovering(mouseX, mouseY); + + drawSettingBackground(context, clickGui, hovering); + + if (this.isListening) { + drawListeningOverlay(context, clickGui); + drawAccentBar(context, clickGui, 2.0F); + } else { + drawDisabledOverlay(context, clickGui); + drawAccentBar(context, clickGui, 2.0F); + } + + String text; + + if (this.isListening) { + text = "Press a key..."; + } else { + Bind bindValue = this.setting.getValue(); + String bind = bindValue.getKeyName().toUpperCase(); + bind = bind.replace("KEY.KEYBOARD", "").replace(".", " ").trim(); + + text = this.setting.getName() + + ": " + + ChatFormatting.GRAY + + bind + + ChatFormatting.DARK_GRAY + + " | " + + ChatFormatting.GRAY + + bindValue.getMode().name(); + } + + drawTrimmedString( + text, + this.x + 4.0F, + this.y + 2.0F, + this.width - 8, + this.isListening + ? clickGui.listeningTextColor.getValue().getRGB() + : clickGui.textColor.getValue().getRGB() + ); + } + + @Override + public void update() { + this.setHidden(!this.setting.isVisible()); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (this.isListening) { + if (mouseButton != 0 && mouseButton != 1) { + Bind old = this.setting.getValue(); + this.setting.setValue(new Bind(-mouseButton - 2, old.getMode())); + this.onMouseClick(); + } + + return; + } + + if (!this.isHovering(mouseX, mouseY)) { + return; + } + + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + + if (mouseButton == 1) { + this.setting.setValue(this.setting.getValue().cycleMode()); + return; + } + + super.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + public void onKeyPressed(int key) { + if (!this.isListening) { + return; + } + + Bind old = this.setting.getValue(); + Bind bind = new Bind(key, old.getMode()); + + if (key == GLFW.GLFW_KEY_DELETE + || key == GLFW.GLFW_KEY_BACKSPACE + || key == GLFW.GLFW_KEY_ESCAPE) { + bind = new Bind(-1, old.getMode()); + } + + this.setting.setValue(bind); + this.onMouseClick(); + } + + @Override + public void toggle() { + this.isListening = !this.isListening; + } + + @Override + public boolean getState() { + return !this.isListening; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/BooleanButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/BooleanButton.java new file mode 100644 index 0000000..9dc6a0a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/BooleanButton.java @@ -0,0 +1,88 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; + +import java.awt.Color; + +public class BooleanButton extends Button { + private final Setting setting; + + public BooleanButton(Setting setting) { + super(setting.getName()); + this.setting = setting; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + boolean hovering = this.isHovering(mouseX, mouseY); + boolean enabled = this.getState(); + + drawSettingBackground(context, clickGui, hovering); + + if (enabled) { + drawAccentBar(context, clickGui, 2.0F); + drawEnabledOverlay(context, clickGui, 2.0F); + } else { + drawDisabledOverlay(context, clickGui); + } + + int boxSize = 6; + float boxX = this.x + this.width - boxSize - 4.0F; + float boxY = this.y + 3.0F; + + RenderUtil.rect(context, boxX, boxY, boxX + boxSize, boxY + boxSize, new Color(0, 0, 0, 100).getRGB()); + RenderUtil.rect(context, boxX, boxY, boxX + boxSize, boxY + 1.0F, new Color(255, 255, 255, 45).getRGB()); + + if (enabled) { + drawGradient( + context, + boxX + 1.0F, + boxY + 1.0F, + boxX + boxSize - 1.0F, + boxY + boxSize - 1.0F, + clickGui.enabledGradientStart.getValue(), + clickGui.enabledGradientEnd.getValue(), + clickGui.enabledGradientDirection.getValue() + ); + } + + drawTrimmedString( + this.getName(), + this.x + 4.0F, + this.y + 2.0F, + this.width - 17, + enabled ? clickGui.textColor.getValue().getRGB() : clickGui.disabledTextColor.getValue().getRGB() + ); + } + + @Override + public void update() { + this.setHidden(!this.setting.isVisible()); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + + if (this.isHovering(mouseX, mouseY)) { + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + } + + @Override + public void toggle() { + this.setting.setValue(!this.setting.getValue()); + } + + @Override + public boolean getState() { + return this.setting.getValue(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/Button.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/Button.java new file mode 100644 index 0000000..c5e02b7 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/Button.java @@ -0,0 +1,121 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import me.humanbeing.nolongerhuman.features.gui.Widget; +import me.humanbeing.nolongerhuman.features.gui.items.Item; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; + +public class Button extends Item { + private boolean state; + + public Button(String name) { + super(name); + this.height = 14; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + boolean hovering = this.isHovering(mouseX, mouseY); + boolean enabled = this.getState(); + + drawRowBackground(context, clickGui, hovering); + + if (enabled) { + drawAccentBar(context, clickGui, 3.0F); + drawEnabledOverlay(context, clickGui, 3.0F); + } else { + drawDisabledOverlay(context, clickGui); + } + + if (hovering) { + net.minecraft.client.gui.GuiGraphics ignored = context; + } + + int textColor = enabled + ? clickGui.textColor.getValue().getRGB() + : clickGui.disabledTextColor.getValue().getRGB(); + + drawScaledTrimmedString( + this.getName(), + this.x + 6.0F, + this.y + getTextYOffset(), + this.width - 12, + textColor + ); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (mouseButton == 0 && this.isHovering(mouseX, mouseY)) { + this.onMouseClick(); + } + } + + public void onMouseClick() { + this.state = !this.state; + this.toggle(); + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + + public void toggle() { + } + + public boolean getState() { + return this.state; + } + + @Override + public int getHeight() { + return 14; + } + + protected float getTextScale() { + return 1.0F; + } + + protected float getTextYOffset() { + return 3.0F; + } + + protected void drawScaledTrimmedString(String text, float x, float y, int maxWidth, int color) { + float scale = getTextScale(); + + if (scale == 1.0F) { + drawTrimmedString(text, x, y, maxWidth, color); + return; + } + + String trimmed = trimToWidth(text, (int) (maxWidth / scale)); + + context.pose().pushMatrix(); + context.pose().scale(scale, scale); + + context.drawString( + mc.font, + trimmed, + (int) (x / scale), + (int) (y / scale), + color + ); + + context.pose().popMatrix(); + } + + public boolean isHovering(int mouseX, int mouseY) { + for (Widget widget : ChinaGUI.getClickGui().getComponents()) { + if (widget.drag) { + return false; + } + } + + return mouseX >= this.getX() + && mouseX <= this.getX() + this.getWidth() + && mouseY >= this.getY() + && mouseY < this.getY() + this.height; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ColorButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ColorButton.java new file mode 100644 index 0000000..2abf68a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ColorButton.java @@ -0,0 +1,432 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import me.humanbeing.nolongerhuman.features.gui.Widget; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.util.Mth; + +import java.awt.Color; + +public class ColorButton extends Button { + private static final int PICKER_SIZE = 84; + + private final Setting setting; + + private boolean open; + private boolean hoveringHue; + private boolean hoveringColor; + private boolean hoveringAlpha; + private boolean hoveringCopy; + private boolean hoveringPaste; + private boolean draggingHue; + private boolean draggingColor; + private boolean draggingAlpha; + + private float[] hsb; + + public ColorButton(Setting setting) { + super(setting.getName()); + this.setting = setting; + hsb = Color.RGBtoHSB(setting.getValue().getRed(), setting.getValue().getGreen(), setting.getValue().getBlue(), null); + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + Color currentColor = setting.getValue(); + Color realColor = Color.getHSBColor(hsb[0], 1.0F, 1.0F); + + boolean hovering = this.isHovering(mouseX, mouseY); + + drawSettingBackground(context, clickGui, hovering); + drawAccentBar(context, clickGui, 2.0F); + + int swatchSize = 8; + float swatchX = this.x + this.width - swatchSize - 5.0F; + float swatchY = this.y + 3.0F; + + RenderUtil.rect( + context, + swatchX - 1.0F, + swatchY - 1.0F, + swatchX + swatchSize + 1.0F, + swatchY + swatchSize + 1.0F, + Color.BLACK.getRGB() + ); + + RenderUtil.rect( + context, + swatchX, + swatchY, + swatchX + swatchSize, + swatchY + swatchSize, + currentColor.getRGB() + ); + + drawTrimmedString( + this.getName(), + this.x + 5.0F, + this.y + 3.0F, + this.width - 22, + clickGui.textColor.getValue().getRGB() + ); + + if (!open) { + return; + } + + float yOffset = this.height + 3.0F; + int pickerWidth = Math.min(PICKER_SIZE, this.width - 10); + float pickerX = this.x + 5.0F; + + int dragX = Mth.clamp(mouseX - (int) pickerX, 0, pickerWidth); + int dragY = Mth.clamp(mouseY - (int) (getY() + yOffset), 0, pickerWidth); + + float dragHue = Math.max(pickerWidth * hsb[0] - 0.5F, 1.0F); + float dragSaturation = Math.max(pickerWidth * hsb[1] - 1.0F, 2.0F); + float dragBrightness = Math.max(pickerWidth * (1.0F - hsb[2]) - 1.0F, 2.0F); + float dragAlpha = Math.max(pickerWidth * (currentColor.getAlpha() / 255.0F) - 0.5F, 1.0F); + + drawPickerBackground(context, clickGui); + + RenderUtil.horizontalGradient( + context, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + pickerWidth, + Color.WHITE, + realColor + ); + + RenderUtil.verticalGradient( + context, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + pickerWidth, + new Color(0, 0, 0, 0), + Color.BLACK + ); + + RenderUtil.rect( + context, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + pickerWidth, + new Color(0, 0, 0, 150).getRGB(), + 1.0F + ); + + hoveringColor = isHoveringArea( + mouseX, + mouseY, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + pickerWidth + ); + + if (dragSaturation < pickerWidth && dragBrightness < pickerWidth) { + RenderUtil.rect( + context, + pickerX + dragSaturation - 2.0F, + this.y + yOffset + dragBrightness - 2.0F, + pickerX + dragSaturation + 2.0F, + this.y + yOffset + dragBrightness + 2.0F, + Color.BLACK.getRGB() + ); + + RenderUtil.rect( + context, + pickerX + dragSaturation - 1.0F, + this.y + yOffset + dragBrightness - 1.0F, + pickerX + dragSaturation + 1.0F, + this.y + yOffset + dragBrightness + 1.0F, + Color.WHITE.getRGB() + ); + } + + if (draggingColor) { + hsb[1] = (float) dragX / pickerWidth; + hsb[2] = 1.0F - (float) dragY / pickerWidth; + setColor(hsb); + } + + yOffset += pickerWidth + 4.0F; + + RenderUtil.horizontalGradient( + context, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + 7.0F, + new Color(currentColor.getRed(), currentColor.getGreen(), currentColor.getBlue(), 0), + new Color(currentColor.getRed(), currentColor.getGreen(), currentColor.getBlue(), 255) + ); + + RenderUtil.rect( + context, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + 7.0F, + new Color(0, 0, 0, 150).getRGB(), + 1.0F + ); + + hoveringAlpha = isHoveringArea( + mouseX, + mouseY, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + 7.0F + ); + + RenderUtil.rect( + context, + pickerX + dragAlpha - 1.0F, + this.y + yOffset - 1.0F, + pickerX + dragAlpha + 1.0F, + this.y + yOffset + 8.0F, + Color.WHITE.getRGB() + ); + + if (draggingAlpha) { + setColor(hsb, (int) (255 * (float) dragX / pickerWidth)); + } + + yOffset += 11.0F; + + for (float i = 0.0F; i < pickerWidth; i += 0.5F) { + RenderUtil.rect( + context, + pickerX + i, + this.y + yOffset, + pickerX + i + 0.5F, + this.y + yOffset + 7.0F, + Color.getHSBColor(i / pickerWidth, 1.0F, 1.0F).getRGB() + ); + } + + RenderUtil.rect( + context, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + 7.0F, + new Color(0, 0, 0, 150).getRGB(), + 1.0F + ); + + hoveringHue = isHoveringArea( + mouseX, + mouseY, + pickerX, + this.y + yOffset, + pickerX + pickerWidth, + this.y + yOffset + 7.0F + ); + + if (dragHue < pickerWidth) { + RenderUtil.rect( + context, + pickerX + dragHue - 1.0F, + this.y + yOffset - 1.0F, + pickerX + dragHue + 1.0F, + this.y + yOffset + 8.0F, + Color.WHITE.getRGB() + ); + } + + if (draggingHue) { + hsb[0] = (float) dragX / pickerWidth; + setColor(hsb); + } + + yOffset += 11.0F; + + int buttonWidth = (pickerWidth - 1) / 2; + + hoveringCopy = isHoveringArea( + mouseX, + mouseY, + pickerX, + this.y + yOffset, + pickerX + buttonWidth, + this.y + yOffset + 13.0F + ); + + hoveringPaste = isHoveringArea( + mouseX, + mouseY, + pickerX + buttonWidth + 1.0F, + this.y + yOffset, + pickerX + buttonWidth * 2.0F + 1.0F, + this.y + yOffset + 13.0F + ); + + drawSmallButtonBackground( + context, + clickGui, + pickerX, + this.y + yOffset, + pickerX + buttonWidth, + this.y + yOffset + 13.0F, + hoveringCopy + ); + + drawSmallButtonBackground( + context, + clickGui, + pickerX + buttonWidth + 1.0F, + this.y + yOffset, + pickerX + buttonWidth * 2.0F + 1.0F, + this.y + yOffset + 13.0F, + hoveringPaste + ); + + drawString( + "Copy", + pickerX + buttonWidth / 2.0F - mc.font.width("Copy") / 2.0F, + this.y + yOffset + 3.0F, + Color.WHITE.getRGB() + ); + + drawString( + "Paste", + pickerX + buttonWidth + 1.0F + buttonWidth / 2.0F - mc.font.width("Paste") / 2.0F, + this.y + yOffset + 3.0F, + Color.WHITE.getRGB() + ); + } + + private void drawPickerBackground(GuiGraphics context, ClickGuiModule clickGui) { + if (clickGui.settingGradient.getValue()) { + drawGradient( + context, + this.x + 3.0F, + this.y + this.height + 1.0F, + this.x + this.width - 3.0F, + this.y + this.getHeight() - 2.0F, + clickGui.settingGradientStart.getValue(), + clickGui.settingGradientEnd.getValue(), + clickGui.settingGradientDirection.getValue() + ); + return; + } + + RenderUtil.rect( + context, + this.x + 3.0F, + this.y + this.height + 1.0F, + this.x + this.width - 3.0F, + this.y + this.getHeight() - 2.0F, + new Color(0, 0, 0, 70).getRGB() + ); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (this.isHovering(mouseX, mouseY) && mouseButton == 1) { + open = !open; + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + + if (mouseButton == 0) { + if (hoveringHue) { + draggingHue = true; + } + + if (hoveringColor) { + draggingColor = true; + } + + if (hoveringAlpha) { + draggingAlpha = true; + } + + if (hoveringCopy) { + ChinaGUI.setColorClipboard(setting.getValue()); + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + + if (hoveringPaste && ChinaGUI.getColorClipboard() != null) { + setting.setValue(ChinaGUI.getColorClipboard()); + hsb = Color.RGBtoHSB( + setting.getValue().getRed(), + setting.getValue().getGreen(), + setting.getValue().getBlue(), + null + ); + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + } + } + + @Override + public void mouseReleased(int mouseX, int mouseY, int releaseButton) { + if (releaseButton == 0) { + draggingHue = false; + draggingColor = false; + draggingAlpha = false; + } + } + + @Override + public void update() { + this.setHidden(!this.setting.isVisible()); + } + + @Override + public int getHeight() { + if (!open) { + return 14; + } + + int pickerWidth = Math.min(PICKER_SIZE, this.width - 10); + + return 14 + pickerWidth + 4 + 7 + 11 + 7 + 11 + 13 + 4; + } + + @Override + public boolean isHovering(int mouseX, int mouseY) { + for (Widget widget : ChinaGUI.getClickGui().getComponents()) { + if (widget.drag) { + return false; + } + } + + return mouseX >= this.getX() + && mouseX <= this.getX() + this.getWidth() + && mouseY >= this.getY() + && mouseY < this.getY() + this.height; + } + + private boolean isHoveringArea(int mouseX, int mouseY, float left, float top, float right, float bottom) { + for (Widget widget : ChinaGUI.getClickGui().getComponents()) { + if (widget.drag) { + return false; + } + } + + return left <= mouseX && top <= mouseY && right > mouseX && bottom > mouseY; + } + + private void setColor(float[] hsb) { + setColor(hsb, setting.getValue().getAlpha()); + } + + private void setColor(float[] hsb, int alpha) { + Color color = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2])); + setting.setValue(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ConfigActionButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ConfigActionButton.java new file mode 100644 index 0000000..3d4af1c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ConfigActionButton.java @@ -0,0 +1,51 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import net.minecraft.client.gui.GuiGraphics; + +public class ConfigActionButton extends Button { + private final Runnable action; + + public ConfigActionButton(String name, Runnable action) { + super(name); + this.action = action; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + boolean hovering = this.isHovering(mouseX, mouseY); + + drawSmallButtonBackground( + context, + clickGui, + this.x, + this.y, + this.x + this.width, + this.y + this.height, + hovering + ); + + drawAccentBar(context, clickGui, 2.0F); + + drawTrimmedString( + this.getName(), + this.x + 5.0F, + this.y + 3.0F, + this.width - 10, + clickGui.textColor.getValue().getRGB() + ); + } + + @Override + public void toggle() { + if (this.action != null) { + this.action.run(); + } + } + + @Override + public boolean getState() { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ConfigButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ConfigButton.java new file mode 100644 index 0000000..b8c95d1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ConfigButton.java @@ -0,0 +1,235 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.gui.items.Item; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; + +import java.util.ArrayList; +import java.util.List; + +public class ConfigButton extends Button { + private final String configName; + private final Runnable refreshCallback; + private final List actions = new ArrayList<>(); + + private boolean open; + + public ConfigButton(String configName, Runnable refreshCallback) { + super(configName); + + this.configName = configName; + this.refreshCallback = refreshCallback; + + initActions(); + } + + private void initActions() { + actions.clear(); + + actions.add(new ConfigActionButton("Update", () -> runCommand("config update " + configName))); + + actions.add(new ConfigActionButton("Load", () -> runCommand("config load " + configName))); + + actions.add(new ConfigActionButton("LoadVisuals", () -> runCommand("config loadvisuals " + configName))); + + actions.add(new ConfigActionButton("Delete", () -> { + runCommand("config delete " + configName); + + if (refreshCallback != null) { + refreshCallback.run(); + } + })); + } + + private void runCommand(String command) { + String prefix = nolongerhuman.commandManager.getCommandPrefix(); + + if (prefix == null || prefix.isEmpty()) { + prefix = "."; + } + + nolongerhuman.commandManager.onChatSent(prefix + command); + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + super.drawScreen(context, mouseX, mouseY, partialTicks); + + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + String indicator = open ? "−" : "+"; + + drawString( + indicator, + this.x + this.width - mc.font.width(indicator) - 5.0F, + this.y + 3.0F, + clickGui.textColor.getValue().getRGB() + ); + + if (!open) { + return; + } + + float actionY = this.y + 16.0F; + float bottom = this.y + this.getHeight() - 1.0F; + + drawConfigPanelBackground(context, clickGui, actionY - 1.0F, bottom); + + drawAccentBarAt( + context, + clickGui, + this.x + 2.0F, + actionY - 1.0F, + this.x + 3.0F, + bottom + ); + + for (Item action : actions) { + action.setLocation(this.x + 5.0F, actionY); + action.setWidth(this.width - 10); + action.drawScreen(context, mouseX, mouseY, partialTicks); + + actionY += action.getHeight() + 1.0F; + } + } + + private void drawConfigPanelBackground( + GuiGraphics context, + ClickGuiModule clickGui, + float top, + float bottom + ) { + if (clickGui.settingGradient.getValue()) { + drawGradient( + context, + this.x + 2.0F, + top, + this.x + this.width - 2.0F, + bottom, + clickGui.settingGradientStart.getValue(), + clickGui.settingGradientEnd.getValue(), + clickGui.settingGradientDirection.getValue() + ); + return; + } + + RenderUtil.rect( + context, + this.x + 2.0F, + top, + this.x + this.width - 2.0F, + bottom, + clickGui.rowSettingColor.getValue().getRGB() + ); + } + + private void drawAccentBarAt( + GuiGraphics context, + ClickGuiModule clickGui, + float left, + float top, + float right, + float bottom + ) { + if (clickGui.accentGradient.getValue()) { + drawGradient( + context, + left, + top, + right, + bottom, + clickGui.accentGradientStart.getValue(), + clickGui.accentGradientEnd.getValue(), + clickGui.accentGradientDirection.getValue() + ); + return; + } + + RenderUtil.rect( + context, + left, + top, + right, + bottom, + clickGui.panelBorderColor.getValue().getRGB() + ); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (mouseButton == 1 && this.isHovering(mouseX, mouseY)) { + this.open = !this.open; + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + return; + } + + if (!open) { + return; + } + + for (Item action : actions) { + action.mouseClicked(mouseX, mouseY, mouseButton); + } + } + + @Override + public void mouseReleased(int mouseX, int mouseY, int releaseButton) { + if (!open) { + return; + } + + for (Item action : actions) { + action.mouseReleased(mouseX, mouseY, releaseButton); + } + } + + @Override + public void onKeyTyped(String typedChar, int keyCode) { + if (!open) { + return; + } + + for (Item action : actions) { + action.onKeyTyped(typedChar, keyCode); + } + } + + @Override + public void onKeyPressed(int key) { + if (!open) { + return; + } + + for (Item action : actions) { + action.onKeyPressed(key); + } + } + + @Override + public int getHeight() { + if (!open) { + return 14; + } + + int height = 16; + + for (Item action : actions) { + height += action.getHeight() + 1; + } + + return height; + } + + @Override + public void toggle() { + } + + @Override + public boolean getState() { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/EnumButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/EnumButton.java new file mode 100644 index 0000000..7af9c42 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/EnumButton.java @@ -0,0 +1,327 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import me.humanbeing.nolongerhuman.features.gui.Widget; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; + +public class EnumButton extends Button { + private static final int ROW_HEIGHT = 13; + + public Setting> setting; + private boolean open; + + public EnumButton(Setting> setting) { + super(setting.getName()); + this.setting = setting; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + boolean hovering = this.isHovering(mouseX, mouseY); + + drawSettingBackground(context, clickGui, hovering); + drawAccentBar(context, clickGui, 2.0F); + + String value = this.setting.currentEnumName().equalsIgnoreCase("ABC") + ? "ABC" + : this.setting.currentEnumName(); + + String indicator = this.open ? "−" : "+"; + String text = this.setting.getName() + ": " + ChatFormatting.GRAY + value; + + drawTrimmedString( + text, + this.x + 5.0F, + this.y + 3.0F, + this.width - 20, + clickGui.textColor.getValue().getRGB() + ); + + drawString( + indicator, + this.x + this.width - mc.font.width(indicator) - 5.0F, + this.y + 3.0F, + clickGui.textColor.getValue().getRGB() + ); + + if (!this.open) { + return; + } + + drawOptions(context, mouseX, mouseY); + } + + private void drawOptions(GuiGraphics context, int mouseX, int mouseY) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + Object[] options = getEnumConstants(); + + if (options.length == 0) { + return; + } + + float optionY = this.y + 15.0F; + + if (clickGui.settingGradient.getValue()) { + drawGradient( + context, + this.x + 2.0F, + optionY - 1.0F, + this.x + this.width - 2.0F, + optionY + options.length * ROW_HEIGHT, + clickGui.settingGradientStart.getValue(), + clickGui.settingGradientEnd.getValue(), + clickGui.settingGradientDirection.getValue() + ); + } + + for (Object option : options) { + if (!(option instanceof Enum enumOption)) { + continue; + } + + boolean selected = enumOption.name().equalsIgnoreCase(this.setting.getValue().name()); + boolean hoveringOption = isHoveringOption(mouseX, mouseY, optionY); + + drawOptionBackground(context, clickGui, hoveringOption, optionY); + + if (selected) { + drawAccentBarAt( + context, + clickGui, + this.x + 3.0F, + optionY, + this.x + 5.0F, + optionY + ROW_HEIGHT + ); + + drawGradient( + context, + this.x + 5.0F, + optionY, + this.x + this.width - 3.0F, + optionY + ROW_HEIGHT, + clickGui.enabledGradientStart.getValue(), + clickGui.enabledGradientEnd.getValue(), + clickGui.enabledGradientDirection.getValue() + ); + } else { + drawGradient( + context, + this.x + 3.0F, + optionY, + this.x + this.width - 3.0F, + optionY + ROW_HEIGHT, + clickGui.disabledGradientStart.getValue(), + clickGui.disabledGradientEnd.getValue(), + clickGui.disabledGradientDirection.getValue() + ); + } + + String optionName = getProperEnumName(enumOption); + + drawTrimmedString( + optionName, + this.x + 8.0F, + optionY + 3.0F, + this.width - 16, + selected + ? clickGui.textColor.getValue().getRGB() + : clickGui.disabledTextColor.getValue().getRGB() + ); + + optionY += ROW_HEIGHT; + } + } + + private void drawOptionBackground( + GuiGraphics context, + ClickGuiModule clickGui, + boolean hoveringOption, + float optionY + ) { + if (hoveringOption) { + if (clickGui.settingHoverGradient.getValue()) { + drawGradient( + context, + this.x + 3.0F, + optionY, + this.x + this.width - 3.0F, + optionY + ROW_HEIGHT, + clickGui.settingHoverGradientStart.getValue(), + clickGui.settingHoverGradientEnd.getValue(), + clickGui.settingHoverGradientDirection.getValue() + ); + } + return; + } + + if (clickGui.settingGradient.getValue()) { + drawGradient( + context, + this.x + 3.0F, + optionY, + this.x + this.width - 3.0F, + optionY + ROW_HEIGHT, + clickGui.settingGradientStart.getValue(), + clickGui.settingGradientEnd.getValue(), + clickGui.settingGradientDirection.getValue() + ); + } + } + + private void drawAccentBarAt( + GuiGraphics context, + ClickGuiModule clickGui, + float left, + float top, + float right, + float bottom + ) { + if (clickGui.accentGradient.getValue()) { + drawGradient( + context, + left, + top, + right, + bottom, + clickGui.accentGradientStart.getValue(), + clickGui.accentGradientEnd.getValue(), + clickGui.accentGradientDirection.getValue() + ); + return; + } + + net.minecraft.client.gui.GuiGraphics ignored = context; + } + + @Override + public void update() { + this.setHidden(!this.setting.isVisible()); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (mouseButton == 1 && this.isHovering(mouseX, mouseY)) { + this.open = !this.open; + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + return; + } + + if (mouseButton == 0 && this.open) { + if (clickOption(mouseX, mouseY)) { + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + return; + } + } + + if (mouseButton == 0 && this.isHovering(mouseX, mouseY)) { + this.setting.increaseEnum(); + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + } + + private boolean clickOption(int mouseX, int mouseY) { + Object[] options = getEnumConstants(); + + if (options.length == 0) { + return false; + } + + float optionY = this.y + 15.0F; + + for (Object option : options) { + if (!(option instanceof Enum enumOption)) { + optionY += ROW_HEIGHT; + continue; + } + + if (isHoveringOption(mouseX, mouseY, optionY)) { + this.setting.setEnumValue(enumOption.name()); + this.open = false; + return true; + } + + optionY += ROW_HEIGHT; + } + + return false; + } + + private boolean isHoveringOption(int mouseX, int mouseY, float optionY) { + for (Widget widget : ChinaGUI.getClickGui().getComponents()) { + if (widget.drag) { + return false; + } + } + + return mouseX >= this.x + 3.0F + && mouseX <= this.x + this.width - 3.0F + && mouseY >= optionY + && mouseY < optionY + ROW_HEIGHT; + } + + @Override + public boolean isHovering(int mouseX, int mouseY) { + for (Widget widget : ChinaGUI.getClickGui().getComponents()) { + if (widget.drag) { + return false; + } + } + + return mouseX >= this.getX() + && mouseX <= this.getX() + this.getWidth() + && mouseY >= this.getY() + && mouseY < this.getY() + 14.0F; + } + + @Override + public int getHeight() { + if (!open) { + return 14; + } + + return 15 + getEnumConstants().length * ROW_HEIGHT; + } + + @Override + public void toggle() { + this.setting.increaseEnum(); + } + + @Override + public boolean getState() { + return true; + } + + private Object[] getEnumConstants() { + Object[] constants = this.setting.getValue().getClass().getEnumConstants(); + + if (constants == null) { + return new Object[0]; + } + + return constants; + } + + private String getProperEnumName(Enum enumOption) { + String name = enumOption.name(); + + if (name.equalsIgnoreCase("ABC")) { + return "ABC"; + } + + if (name.isEmpty()) { + return ""; + } + + return Character.toUpperCase(name.charAt(0)) + name.toLowerCase().substring(1); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ModuleButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ModuleButton.java new file mode 100644 index 0000000..51e69e9 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/ModuleButton.java @@ -0,0 +1,343 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.gui.items.Item; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Bind; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +public class ModuleButton extends Button { + private final Module module; + private List items = new ArrayList<>(); + private boolean subOpen; + + public ModuleButton(Module module) { + super(module.getName()); + this.module = module; + this.initSettings(); + } + + @SuppressWarnings("unchecked") + public void initSettings() { + ArrayList newItems = new ArrayList<>(); + + if (!this.module.getSettings().isEmpty()) { + for (Setting setting : this.module.getSettings()) { + if (setting.getValue() instanceof Boolean && !setting.getName().equals("Enabled")) { + newItems.add(new BooleanButton((Setting) setting)); + continue; + } + + if (setting.getValue() instanceof Bind + && !setting.getName().equalsIgnoreCase("Keybind") + && !this.module.getName().equalsIgnoreCase("Hud")) { + newItems.add(new BindButton((Setting) setting)); + continue; + } + + if ((setting.getValue() instanceof String || setting.getValue() instanceof Character) + && !setting.getName().equalsIgnoreCase("displayName")) { + newItems.add(new StringButton((Setting) setting)); + continue; + } + + if (setting.isColorSetting()) { + newItems.add(new ColorButton((Setting) setting)); + continue; + } + + if (setting.isNumberSetting() && setting.hasRestriction()) { + newItems.add(new Slider((Setting) setting)); + continue; + } + + if (setting.isEnumSetting()) { + newItems.add(new EnumButton((Setting>) setting)); + } + } + } + + Setting keybindSetting = this.module.getSettingByName("Keybind"); + + if (keybindSetting != null && keybindSetting.getValue() instanceof Bind) { + newItems.add(new BindButton((Setting) keybindSetting)); + } + + this.items = newItems; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + super.drawScreen(context, mouseX, mouseY, partialTicks); + + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + if (!this.items.isEmpty()) { + String indicator = this.subOpen ? "−" : "+"; + + int color = this.module.isEnabled() + ? clickGui.textColor.getValue().getRGB() + : clickGui.disabledTextColor.getValue().getRGB(); + + drawString( + indicator, + this.x + this.width - mc.font.width(indicator) - 5.0F, + this.y + 3.0F, + color + ); + } + + if (!this.items.isEmpty() && this.subOpen) { + float settingY = this.y + 16.0F; + float settingsBottom = this.y + this.getHeight() - 1.0F; + + drawSettingsPanelBackground(context, clickGui, settingY, settingsBottom); + + drawAccentBarAt( + context, + clickGui, + this.x + 2.0F, + settingY - 1.0F, + this.x + 3.0F, + settingsBottom + ); + + for (Item item : this.items) { + item.update(); + + if (item.isHidden()) { + continue; + } + + item.setLocation(this.x + 5.0F, settingY); + item.setWidth(this.width - 10); + item.drawScreen(context, mouseX, mouseY, partialTicks); + + settingY += item.getHeight() + 1.0F; + } + } + } + + private void drawSettingsPanelBackground( + GuiGraphics context, + ClickGuiModule clickGui, + float settingY, + float settingsBottom + ) { + if (clickGui.settingGradient.getValue()) { + drawGradient( + context, + this.x + 2.0F, + settingY - 1.0F, + this.x + this.width - 2.0F, + settingsBottom, + clickGui.settingGradientStart.getValue(), + clickGui.settingGradientEnd.getValue(), + clickGui.settingGradientDirection.getValue() + ); + return; + } + + RenderUtil.rect( + context, + this.x + 2.0F, + settingY - 1.0F, + this.x + this.width - 2.0F, + settingsBottom, + clickGui.rowSettingColor.getValue().getRGB() + ); + } + + private void drawAccentBarAt( + GuiGraphics context, + ClickGuiModule clickGui, + float left, + float top, + float right, + float bottom + ) { + if (clickGui.accentGradient.getValue()) { + drawGradient( + context, + left, + top, + right, + bottom, + clickGui.accentGradientStart.getValue(), + clickGui.accentGradientEnd.getValue(), + clickGui.accentGradientDirection.getValue() + ); + return; + } + + RenderUtil.rect( + context, + left, + top, + right, + bottom, + clickGui.panelBorderColor.getValue().getRGB() + ); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + + if (this.items.isEmpty()) { + return; + } + + if (mouseButton == 1 && this.isHovering(mouseX, mouseY)) { + this.subOpen = !this.subOpen; + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + + if (!this.subOpen) { + return; + } + + for (Item item : this.items) { + if (item.isHidden()) { + continue; + } + + item.mouseClicked(mouseX, mouseY, mouseButton); + } + } + + @Override + public void mouseReleased(int mouseX, int mouseY, int releaseButton) { + super.mouseReleased(mouseX, mouseY, releaseButton); + + if (this.items.isEmpty() || !this.subOpen) { + return; + } + + for (Item item : this.items) { + if (item.isHidden()) { + continue; + } + + item.mouseReleased(mouseX, mouseY, releaseButton); + } + } + + @Override + public void onKeyTyped(String typedChar, int keyCode) { + super.onKeyTyped(typedChar, keyCode); + + if (this.items.isEmpty() || !this.subOpen) { + return; + } + + for (Item item : this.items) { + if (item.isHidden()) { + continue; + } + + item.onKeyTyped(typedChar, keyCode); + } + } + + @Override + public void onKeyPressed(int key) { + super.onKeyPressed(key); + + if (this.items.isEmpty() || !this.subOpen) { + return; + } + + for (Item item : this.items) { + if (item.isHidden()) { + continue; + } + + item.onKeyPressed(key); + } + } + + @Override + public int getHeight() { + if (this.subOpen) { + int expandedHeight = 16; + + for (Item item : this.items) { + item.update(); + + if (item.isHidden()) { + continue; + } + + expandedHeight += item.getHeight() + 1; + } + + return expandedHeight; + } + + return 14; + } + + @Override + protected float getTextScale() { + return 1.0F; + } + + @Override + protected float getTextYOffset() { + return 4.0F; + } + + public Module getModule() { + return this.module; + } + + public String getModuleDescription() { + String description = this.module.getDescription(); + + if (description == null || description.isBlank()) { + return this.module.getName(); + } + + return description; + } + + public boolean matchesSearch(String query) { + if (query == null || query.isBlank()) { + return true; + } + + String loweredQuery = query.toLowerCase(Locale.ROOT); + + if (this.module.getName().toLowerCase(Locale.ROOT).contains(loweredQuery)) { + return true; + } + + String description = this.module.getDescription(); + + if (description != null && description.toLowerCase(Locale.ROOT).contains(loweredQuery)) { + return true; + } + + return this.module.getCategory().getName().toLowerCase(Locale.ROOT).contains(loweredQuery); + } + + @Override + public void toggle() { + this.module.toggle(); + } + + @Override + public boolean getState() { + return this.module.isEnabled(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/Slider.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/Slider.java new file mode 100644 index 0000000..91d1263 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/Slider.java @@ -0,0 +1,295 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import me.humanbeing.nolongerhuman.features.gui.Widget; +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.GuiGraphics; +import org.lwjgl.glfw.GLFW; + +import java.util.Locale; + +public class Slider extends Button { + private static final double DECIMAL_SCALE = 1000.0; + + private final Number min; + private final Number max; + private final double difference; + + public Setting setting; + + private boolean isListening; + private String typedValue = ""; + + public Slider(Setting setting) { + super(setting.getName()); + this.setting = setting; + this.min = setting.getMin(); + this.max = setting.getMax(); + this.difference = this.max.doubleValue() - this.min.doubleValue(); + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + this.dragSetting(mouseX, mouseY); + + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + boolean hovering = this.isHovering(mouseX, mouseY); + + float percent = this.partialMultiplier(); + float barLeft = this.x + 5.0F; + float barRight = this.x + this.width - 5.0F; + float barY = this.y + this.height - 3.0F; + float fillRight = barLeft + (barRight - barLeft) * percent; + + drawSettingBackground(context, clickGui, hovering); + + if (this.isListening) { + drawListeningOverlay(context, clickGui); + drawAccentBar(context, clickGui, 2.0F); + } + + RenderUtil.rect( + context, + barLeft, + barY, + barRight, + barY + 1.0F, + clickGui.panelBorderColor.getValue().getRGB() + ); + + drawSliderFill(context, clickGui, barLeft, barY, fillRight, barY + 1.0F); + + RenderUtil.rect( + context, + fillRight - 1.0F, + barY - 2.0F, + fillRight + 1.0F, + barY + 3.0F, + clickGui.textColor.getValue().getRGB() + ); + + String text = this.isListening + ? this.getName() + ": " + ChatFormatting.YELLOW + this.typedValue + getCursor() + : this.getName() + ": " + ChatFormatting.GRAY + this.getValueString(); + + int textColor = this.isListening + ? clickGui.listeningTextColor.getValue().getRGB() + : clickGui.textColor.getValue().getRGB(); + + drawTrimmedString(text, this.x + 5.0F, this.y + 2.0F, this.width - 10, textColor); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (!this.isHovering(mouseX, mouseY)) { + return; + } + + if (mouseButton == 0) { + if (this.isListening) { + this.applyTypedValue(); + return; + } + + this.setSettingFromX(mouseX); + return; + } + + if (mouseButton == 1) { + this.startListening(); + } + } + + @Override + public void onKeyTyped(String typedChar, int keyCode) { + if (!this.isListening) { + return; + } + + if (typedChar == null || typedChar.isEmpty()) { + return; + } + + String character = typedChar.substring(0, 1); + + if (!this.isValidTypedCharacter(character)) { + return; + } + + this.typedValue += character; + } + + @Override + public void onKeyPressed(int key) { + if (!this.isListening) { + return; + } + + switch (key) { + case GLFW.GLFW_KEY_ENTER -> this.applyTypedValue(); + case GLFW.GLFW_KEY_BACKSPACE -> { + if (!this.typedValue.isEmpty()) { + this.typedValue = this.typedValue.substring(0, this.typedValue.length() - 1); + } + } + case GLFW.GLFW_KEY_ESCAPE -> this.cancelListening(); + } + } + + @Override + public boolean isHovering(int mouseX, int mouseY) { + for (Widget widget : ChinaGUI.getClickGui().getComponents()) { + if (widget.drag) { + return false; + } + } + + return mouseX >= this.getX() + && mouseX <= this.getX() + this.getWidth() + && mouseY >= this.getY() + && mouseY < this.getY() + this.height; + } + + @Override + public void update() { + this.setHidden(!this.setting.isVisible()); + } + + @Override + public boolean getState() { + return true; + } + + private void startListening() { + this.isListening = true; + this.typedValue = ""; + } + + private void cancelListening() { + this.isListening = false; + this.typedValue = ""; + } + + private void applyTypedValue() { + if (this.typedValue.isEmpty() + || this.typedValue.equals("-") + || this.typedValue.equals(".") + || this.typedValue.equals("-.")) { + this.cancelListening(); + return; + } + + try { + double parsed = Double.parseDouble(this.typedValue); + double clamped = clamp(parsed, this.min.doubleValue(), this.max.doubleValue()); + this.applyNumberValue(clamped); + this.cancelListening(); + } catch (NumberFormatException exception) { + this.cancelListening(); + } + } + + private boolean isValidTypedCharacter(String character) { + if (character.matches("[0-9]")) { + return true; + } + + if (character.equals("-")) { + return this.typedValue.isEmpty() && this.min.doubleValue() < 0.0; + } + + if (character.equals(".")) { + return !(this.setting.getValue() instanceof Integer) && !this.typedValue.contains("."); + } + + return false; + } + + private String getCursor() { + return System.currentTimeMillis() % 1000L > 500L ? "_" : ""; + } + + private String getValueString() { + Number value = this.setting.getValue(); + + if (value instanceof Integer) { + return String.valueOf(value.intValue()); + } + + return formatDecimal(value.doubleValue()); + } + + private void dragSetting(int mouseX, int mouseY) { + if (this.isListening) { + return; + } + + if (this.isHovering(mouseX, mouseY) + && GLFW.glfwGetMouseButton(mc.getWindow().handle(), 0) == GLFW.GLFW_PRESS) { + this.setSettingFromX(mouseX); + } + } + + private void setSettingFromX(int mouseX) { + double percent = ((double) mouseX - this.x) / this.width; + percent = clamp(percent, 0.0, 1.0); + + double result = this.min.doubleValue() + this.difference * percent; + + this.applyNumberValue(result); + } + + private void applyNumberValue(double value) { + double rounded = roundToThousandth(value); + + if (this.setting.getValue() instanceof Double) { + this.setting.setValue(rounded); + return; + } + + if (this.setting.getValue() instanceof Float) { + this.setting.setValue((float) rounded); + return; + } + + if (this.setting.getValue() instanceof Integer) { + this.setting.setValue((int) Math.round(value)); + } + } + + private float partialMultiplier() { + if (this.difference == 0.0) { + return 0.0F; + } + + double part = this.setting.getValue().doubleValue() - this.min.doubleValue(); + + return (float) Math.max(0.0, Math.min(1.0, part / this.difference)); + } + + private double roundToThousandth(double value) { + return Math.round(value * DECIMAL_SCALE) / DECIMAL_SCALE; + } + + private double clamp(double value, double minimum, double maximum) { + return Math.max(minimum, Math.min(maximum, value)); + } + + private String formatDecimal(double value) { + String formatted = String.format(Locale.US, "%.3f", value); + + while (formatted.contains(".") && formatted.endsWith("0")) { + formatted = formatted.substring(0, formatted.length() - 1); + } + + if (formatted.endsWith(".")) { + formatted = formatted.substring(0, formatted.length() - 1); + } + + return formatted; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/StringButton.java b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/StringButton.java new file mode 100644 index 0000000..4493d04 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/gui/items/buttons/StringButton.java @@ -0,0 +1,145 @@ +package me.humanbeing.nolongerhuman.features.gui.items.buttons; + +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.models.Timer; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.sounds.SoundEvents; +import org.lwjgl.glfw.GLFW; + +public class StringButton extends Button { + private static final Timer idleTimer = new Timer(); + private static boolean idle; + + private final Setting setting; + + public boolean isListening; + + private CurrentString currentString = new CurrentString(""); + + public StringButton(Setting setting) { + super(setting.getName()); + this.setting = setting; + } + + public static String removeLastChar(String str) { + String output = ""; + + if (str != null && !str.isEmpty()) { + output = str.substring(0, str.length() - 1); + } + + return output; + } + + @Override + public void drawScreen(GuiGraphics context, int mouseX, int mouseY, float partialTicks) { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + boolean hovering = this.isHovering(mouseX, mouseY); + + drawSettingBackground(context, clickGui, hovering); + + if (this.isListening) { + drawListeningOverlay(context, clickGui); + } else { + drawDisabledOverlay(context, clickGui); + } + + drawAccentBar(context, clickGui, 2.0F); + + String text; + + if (this.isListening) { + text = this.currentString.string() + getIdleSign(); + } else if (this.setting.getName().equals("Buttons")) { + text = "Buttons: " + ChatFormatting.GRAY + this.setting.getValue(); + } else if (this.setting.getName().equals("Prefix")) { + text = "Prefix: " + ChatFormatting.GRAY + this.setting.getValue(); + } else { + text = this.setting.getName() + ": " + ChatFormatting.GRAY + this.setting.getValue(); + } + + int textColor = this.isListening + ? clickGui.listeningTextColor.getValue().getRGB() + : clickGui.textColor.getValue().getRGB(); + + drawTrimmedString(text, this.x + 5.0F, this.y + 3.0F, this.width - 10, textColor); + } + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + + if (this.isHovering(mouseX, mouseY)) { + mc.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); + } + } + + @Override + public void onKeyTyped(String typedChar, int keyCode) { + if (this.isListening) { + this.setString(this.currentString.string() + typedChar); + } + } + + @Override + public void onKeyPressed(int key) { + if (!isListening) { + return; + } + + switch (key) { + case GLFW.GLFW_KEY_ENTER -> this.enterString(); + case GLFW.GLFW_KEY_BACKSPACE -> this.setString(StringButton.removeLastChar(this.currentString.string())); + case GLFW.GLFW_KEY_ESCAPE -> { + this.setString(""); + this.onMouseClick(); + } + } + } + + @Override + public void update() { + this.setHidden(!this.setting.isVisible()); + } + + private void enterString() { + if (this.currentString.string().isEmpty()) { + this.setting.setValue(this.setting.getDefaultValue()); + } else { + this.setting.setValue(this.currentString.string()); + } + + this.setString(""); + this.onMouseClick(); + } + + @Override + public void toggle() { + this.isListening = !this.isListening; + } + + @Override + public boolean getState() { + return !this.isListening; + } + + public void setString(String newString) { + this.currentString = new CurrentString(newString); + } + + public static String getIdleSign() { + if (idleTimer.passedMs(500L)) { + idle = !idle; + idleTimer.reset(); + } + + return idle ? "_" : ""; + } + + public record CurrentString(String string) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/Module.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/Module.java new file mode 100644 index 0000000..84190d6 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/Module.java @@ -0,0 +1,326 @@ +package me.humanbeing.nolongerhuman.features.modules; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.ClientEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.settings.Bind; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.ConfigManager; +import me.humanbeing.nolongerhuman.util.traits.Jsonable; +import me.humanbeing.nolongerhuman.util.traits.Toggleable; +import net.minecraft.ChatFormatting; +import org.joml.Vector2f; + +import java.awt.Color; + +public class Module extends Feature implements Jsonable, Toggleable { + private final String description; + private final Category category; + + public final Setting enabled = bool("Enabled", false); + public final Setting drawn = bool("Drawn", true); + public final Setting bind = key("Keybind", Bind.none()); + public final Setting displayName; + + public boolean hidden; + + public Module(String name, String description, Category category) { + super(name); + this.displayName = str("DisplayName", name); + this.description = description; + this.category = category; + } + + public void onEnable() { + } + + public void onDisable() { + } + + public void onToggle() { + } + + public void onLoad() { + } + + public void onTick() { + } + + public void onRender2D(Render2DEvent event) { + } + + public void onRender3D(Render3DEvent event) { + } + + public void onUnload() { + } + + public String getDisplayInfo() { + return null; + } + + public void enable() { + if (this.enabled.getValue()) { + return; + } + + this.enabled.setValue(true); + EVENT_BUS.register(this); + EVENT_BUS.post(new ClientEvent(ClientEvent.Type.TOGGLE_MODULE, this)); + + this.onToggle(); + this.onEnable(); + } + + public void disable() { + if (!this.enabled.getValue()) { + return; + } + + this.enabled.setValue(false); + EVENT_BUS.unregister(this); + EVENT_BUS.post(new ClientEvent(ClientEvent.Type.TOGGLE_MODULE, this)); + + this.onToggle(); + this.onDisable(); + } + + public String getDisplayName() { + return this.displayName.getValue(); + } + + public void setDisplayName(String name) { + Module module = nolongerhuman.moduleManager.getModuleByDisplayName(name); + Module originalModule = nolongerhuman.moduleManager.getModuleByName(name); + + if (module == null && originalModule == null) { + Command.sendMessage( + this.getDisplayName() + ", name: " + this.getName() + ", has been renamed to: " + name, + "general" + ); + + this.displayName.setValue(name); + return; + } + + Command.sendMessage("{red} A module of this name already exists.", "general"); + } + + @Override + public boolean isEnabled() { + return this.enabled.getValue(); + } + + @Override + public boolean isToggled() { + return this.isEnabled(); + } + + public String getDescription() { + return this.description; + } + + public boolean isDrawn() { + return this.drawn.getValue(); + } + + public void setDrawn(boolean drawn) { + this.drawn.setValue(drawn); + } + + public Category getCategory() { + return this.category; + } + + public String getInfo() { + return null; + } + + public Bind getBind() { + return this.bind.getValue(); + } + + public void setBind(int key) { + Bind old = this.bind.getValue(); + + if (old == null) { + this.bind.setValue(new Bind(key, Bind.Mode.Toggle)); + return; + } + + this.bind.setValue(new Bind(key, old.getMode())); + } + + public void setBind(Bind bind) { + this.bind.setValue(bind == null ? Bind.none() : bind); + } + + public String getFullArrayString() { + return this.getDisplayName() + + ChatFormatting.GRAY + + (this.getDisplayInfo() != null + ? " [" + ChatFormatting.WHITE + this.getDisplayInfo() + ChatFormatting.GRAY + "]" + : ""); + } + + @Override + public JsonElement toJson() { + JsonObject object = new JsonObject(); + + for (Setting setting : getSettings()) { + try { + Object value = setting.getValue(); + + if (value instanceof Bind keyBind) { + object.add(setting.getName(), keyBind.toJsonObject()); + } else if (value instanceof Color color) { + object.addProperty( + setting.getName(), + color.getRed() + + "," + + color.getGreen() + + "," + + color.getBlue() + + "," + + color.getAlpha() + ); + } else if (value instanceof Vector2f pos) { + object.addProperty(setting.getName(), pos.x() + "," + pos.y()); + } else { + object.addProperty(setting.getName(), setting.getValueAsString()); + } + } catch (Throwable throwable) { + nolongerhuman.LOGGER.error("Failed to create JSON field", throwable); + } + } + + return object; + } + + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public void fromJson(JsonElement element) { + if (element == null || element.isJsonNull()) { + return; + } + + JsonObject object = element.getAsJsonObject(); + boolean shouldEnable = false; + + if (object.has("Enabled") && !object.get("Enabled").isJsonNull()) { + try { + shouldEnable = object.get("Enabled").getAsBoolean(); + } catch (Throwable ignored) { + try { + shouldEnable = Boolean.parseBoolean(object.get("Enabled").getAsString()); + } catch (Throwable ignoredAgain) { + shouldEnable = false; + } + } + } + + for (Setting setting : getSettings()) { + try { + if (setting.getName().equalsIgnoreCase("Enabled")) { + continue; + } + + JsonElement settingElement = object.get(setting.getName()); + + if (settingElement == null || settingElement.isJsonNull()) { + continue; + } + + if (setting.getValue() instanceof Bind) { + ((Setting) setting).setValue(parseBind(settingElement)); + continue; + } + + ConfigManager.setValueFromJson(this, setting, settingElement); + } catch (Throwable throwable) { + nolongerhuman.LOGGER.error("Failed to load setting from JSON: " + setting.getName(), throwable); + } + } + + try { + if (shouldEnable && !this.isEnabled()) { + this.enable(); + } else if (!shouldEnable && this.isEnabled()) { + this.disable(); + } + } catch (Throwable throwable) { + nolongerhuman.LOGGER.error("Failed to apply enabled state for module: " + this.getName(), throwable); + } + } + + private Bind parseBind(JsonElement element) { + if (element == null || element.isJsonNull()) { + return Bind.none(); + } + + try { + Bind converted = new Bind.BindConverter().reverse().convert(element); + + if (converted != null) { + return converted; + } + } catch (Throwable ignored) { + } + + try { + if (element.isJsonPrimitive() && element.getAsJsonPrimitive().isNumber()) { + return new Bind(element.getAsInt(), Bind.Mode.Toggle); + } + } catch (Throwable ignored) { + } + + try { + String value = element.getAsString(); + + if (value == null) { + return Bind.none(); + } + + value = value.trim(); + + if (value.isEmpty() || value.equalsIgnoreCase("None")) { + return Bind.none(); + } + + try { + return new Bind(Integer.parseInt(value), Bind.Mode.Toggle); + } catch (Throwable ignored) { + } + + Bind converted = new Bind.BindConverter().reverse().convert(element); + + return converted == null ? Bind.none() : converted; + } catch (Throwable ignored) { + return Bind.none(); + } + } + + public enum Category { + COMBAT("Combat"), + RENDER("Render"), + MOVEMENT("Movement"), + PLAYER("Player"), + CLIENT("Client"), + HUD("Hud"); + + private final String name; + + Category(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/ClickGuiModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/ClickGuiModule.java new file mode 100644 index 0000000..53eb023 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/ClickGuiModule.java @@ -0,0 +1,220 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.ClientEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import org.lwjgl.glfw.GLFW; + +import java.awt.Color; + +public class ClickGuiModule extends Module { + private static ClickGuiModule INSTANCE; + + public enum GradientDirection { + LeftToRight, + RightToLeft, + TopToBottom, + BottomToTop + } + + public Setting prefix = str("Prefix", "."); + + public Setting color = color("Color", 105, 95, 255, 230); + public Setting topColor = color("TopColor", 135, 105, 255, 245); + public Setting secondaryColor = color("SecondColor", 55, 175, 255, 225); + + public Setting backgroundColor = color("BackgroundColor", 0, 0, 0, 105); + public Setting vignetteColor = color("Vignette", 0, 0, 0, 80); + + public Setting panelColor = color("PanelColor", 13, 13, 22, 235); + public Setting panelBodyColor = color("PanelBodyColor", 6, 7, 13, 215); + + public Setting panelBackgroundGradient = bool("PanelBackgroundGradient", true); + public Setting panelGradientStart = color("PanelGradientStart", 13, 13, 22, 235); + public Setting panelGradientEnd = color("PanelGradientEnd", 6, 7, 13, 215); + public Setting panelGradientDirection = mode( + "PanelGradientDirection", + GradientDirection.TopToBottom + ); + + public Setting panelBorderColor = color("PanelBorderColor", 105, 95, 255, 210); + public Setting panelShadowColor = color("PanelShadow", 0, 0, 0, 105); + + public Setting panelBorderGlow = bool("PanelBorderGlow", true); + public Setting panelBorderGlowColor = color("PanelBorderGlowColor", 105, 95, 255, 85); + public Setting panelBorderGlowRadius = num("PanelBorderGlowRadius", 4, 0, 12); + + public Setting rowColor = color("RowColor", 18, 18, 31, 185); + public Setting rowHoverColor = color("RowHoverColor", 48, 44, 88, 220); + public Setting rowSettingColor = color("SettingRow", 12, 13, 22, 185); + + public Setting rowGradient = bool("RowGradient", true); + public Setting rowGradientStart = color("RowGradientStart", 18, 18, 31, 185); + public Setting rowGradientEnd = color("RowGradientEnd", 8, 10, 20, 155); + public Setting rowGradientDirection = mode( + "RowGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting rowHoverGradient = bool("RowHoverGradient", true); + public Setting rowHoverGradientStart = color("RowHoverGradientStart", 48, 44, 88, 220); + public Setting rowHoverGradientEnd = color("RowHoverGradientEnd", 25, 35, 70, 190); + public Setting rowHoverGradientDirection = mode( + "RowHoverGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting settingGradient = bool("SettingGradient", true); + public Setting settingGradientStart = color("SettingGradientStart", 12, 13, 22, 185); + public Setting settingGradientEnd = color("SettingGradientEnd", 5, 7, 14, 145); + public Setting settingGradientDirection = mode( + "SettingGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting settingHoverGradient = bool("SettingHoverGradient", true); + public Setting settingHoverGradientStart = color("SettingHoverGradientStart", 48, 44, 88, 220); + public Setting settingHoverGradientEnd = color("SettingHoverGradientEnd", 20, 28, 58, 185); + public Setting settingHoverGradientDirection = mode( + "SettingHoverGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting enabledOverlayColor = color("EnabledOverlay", 105, 95, 255, 70); + + public Setting enabledGradient = bool("EnabledGradient", true); + public Setting enabledGradientStart = color("EnabledGradientStart", 105, 95, 255, 115); + public Setting enabledGradientEnd = color("EnabledGradientEnd", 55, 175, 255, 45); + public Setting enabledGradientDirection = mode( + "EnabledGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting disabledGradient = bool("DisabledGradient", true); + public Setting disabledGradientStart = color("DisabledGradientStart", 20, 22, 36, 120); + public Setting disabledGradientEnd = color("DisabledGradientEnd", 8, 9, 18, 35); + public Setting disabledGradientDirection = mode( + "DisabledGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting accentGradient = bool("AccentGradient", true); + public Setting accentGradientStart = color("AccentGradientStart", 105, 95, 255, 230); + public Setting accentGradientEnd = color("AccentGradientEnd", 55, 175, 255, 210); + public Setting accentGradientDirection = mode( + "AccentGradientDirection", + GradientDirection.TopToBottom + ); + + public Setting sliderGradient = bool("SliderGradient", true); + public Setting sliderGradientStart = color("SliderGradientStart", 105, 95, 255, 245); + public Setting sliderGradientEnd = color("SliderGradientEnd", 55, 175, 255, 245); + public Setting sliderGradientDirection = mode( + "SliderGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting smallButtonGradient = bool("SmallButtonGradient", true); + public Setting smallButtonGradientStart = color("SmallButtonGradientStart", 24, 26, 44, 210); + public Setting smallButtonGradientEnd = color("SmallButtonGradientEnd", 10, 12, 24, 180); + public Setting smallButtonGradientDirection = mode( + "SmallButtonGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting smallButtonHoverGradient = bool("SmallButtonHoverGradient", true); + public Setting smallButtonHoverGradientStart = color("SmallButtonHoverGradientStart", 135, 105, 255, 230); + public Setting smallButtonHoverGradientEnd = color("SmallButtonHoverGradientEnd", 55, 175, 255, 220); + public Setting smallButtonHoverGradientDirection = mode( + "SmallButtonHoverGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting listeningGradient = bool("ListeningGradient", true); + public Setting listeningGradientStart = color("ListeningGradientStart", 255, 226, 145, 95); + public Setting listeningGradientEnd = color("ListeningGradientEnd", 255, 160, 90, 35); + public Setting listeningGradientDirection = mode( + "ListeningGradientDirection", + GradientDirection.LeftToRight + ); + + public Setting catEars = bool("CatEars", true); + public Setting catEarColor = color("CatEarColor", 135, 105, 255, 235); + public Setting catEarInnerColor = color("CatEarInner", 255, 135, 210, 145); + public Setting catEarBorderColor = color("CatEarBorder", 55, 175, 255, 230); + + public Setting categoryTextColor = color("CategoryText", 255, 255, 255, 255); + public Setting textColor = color("ModuleText", 240, 245, 255, 255); + public Setting disabledTextColor = color("DisabledText", 155, 160, 178, 255); + public Setting listeningTextColor = color("ListeningText", 255, 226, 145, 255); + + public Setting searchBarColor = color("SearchBar", 5, 7, 14, 210); + public Setting searchBorderColor = color("SearchBorder", 105, 95, 255, 210); + public Setting searchTextColor = color("SearchText", 240, 245, 255, 255); + public Setting searchPlaceholderColor = color("SearchPlaceholder", 145, 150, 170, 255); + + public Setting blurBackground = bool("DarkenBackground", true); + public Setting shadows = bool("Shadows", true); + public Setting descriptions = bool("DescriptionBar", true); + public Setting searchBar = bool("SearchBar", true); + + public ClickGuiModule() { + super("ClickGui", "Opens the ClickGui", Module.Category.CLIENT); + setBind(GLFW.GLFW_KEY_RIGHT_SHIFT); + INSTANCE = this; + } + + @Subscribe + public void onSettingChange(ClientEvent event) { + if (event.getType() != ClientEvent.Type.SETTING_UPDATE) { + return; + } + + if (event.getSetting() == null || event.getSetting().getFeature() == null) { + return; + } + + if (!event.getSetting().getFeature().equals(this)) { + return; + } + + if (event.getSetting().equals(this.prefix)) { + nolongerhuman.commandManager.setCommandPrefix(this.prefix.getPlannedValue()); + Command.sendMessage("Prefix set to {global} %s", nolongerhuman.commandManager.getCommandPrefix()); + } + + if (event.getSetting().equals(this.color)) { + nolongerhuman.colorManager.setColor(this.color.getPlannedValue()); + } + } + + @Override + public void onEnable() { + if (nullCheck()) { + return; + } + + mc.setScreen(ChinaGUI.getClickGui()); + } + + @Override + public void onLoad() { + nolongerhuman.colorManager.setColor(this.color.getValue()); + nolongerhuman.commandManager.setCommandPrefix(this.prefix.getValue()); + } + + @Override + public void onTick() { + if (!(ClickGuiModule.mc.screen instanceof ChinaGUI)) { + this.disable(); + } + } + + public static ClickGuiModule getInstance() { + return INSTANCE; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/CustomFontModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/CustomFontModule.java new file mode 100644 index 0000000..cbf12d1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/CustomFontModule.java @@ -0,0 +1,66 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.FontManager; + +public class CustomFontModule extends Module { + private static CustomFontModule INSTANCE; + + public final Setting fontName = str("Font", "Arial"); + public final Setting size = num("Size", 18.0f, 8.0f, 32.0f); + public final Setting shadow = bool("Shadow", true); + public final Setting guiOnly = bool("GuiOnly", false); + public final Setting chat = bool("Chat", true); + + public CustomFontModule() { + super("CustomFont", "Replaces Minecraft GUI and chat text with a custom AWT font.", Category.CLIENT); + INSTANCE = this; + } + + @Override + public void onEnable() { + FontManager.reload(fontName.getValue(), size.getValue()); + FontManager.setEnabled(true); + } + + @Override + public void onDisable() { + FontManager.setEnabled(false); + } + + @Override + public void onLoad() { + INSTANCE = this; + + if (isEnabled()) { + FontManager.reload(fontName.getValue(), size.getValue()); + FontManager.setEnabled(true); + } + } + + @Override + public void onTick() { + if (!FontManager.matches(fontName.getValue(), size.getValue())) { + FontManager.reload(fontName.getValue(), size.getValue()); + } + + FontManager.setEnabled(isEnabled()); + } + + public boolean shouldForceShadow() { + return shadow.getValue(); + } + + public boolean shouldRenderGuiOnly() { + return guiOnly.getValue(); + } + + public boolean shouldRenderChat() { + return chat.getValue(); + } + + public static CustomFontModule getInstance() { + return INSTANCE; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/FakePlayerModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/FakePlayerModule.java new file mode 100644 index 0000000..5b48bcc --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/FakePlayerModule.java @@ -0,0 +1,275 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import com.mojang.authlib.GameProfile; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.player.RemotePlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.Vec3; + +import java.lang.reflect.Field; +import java.util.UUID; + +public class FakePlayerModule extends Module { + private static FakePlayerModule INSTANCE; + + private final Setting name = str("Name", "FakePlayer"); + private final Setting copyInventory = bool("CopyInventory", true); + private final Setting copyHealth = bool("CopyHealth", true); + private final Setting copyRotation = bool("CopyRotation", true); + private final Setting copyPose = bool("CopyPose", true); + private final Setting freeze = bool("Freeze", true); + private final Setting autoDisableOnWorldLeave = bool("AutoDisableWorldLeave", true); + + private RemotePlayer fakePlayer; + private int fakePlayerId = -1337; + + public FakePlayerModule() { + super("FakePlayer", "Spawns a client-side fake player", Category.CLIENT); + INSTANCE = this; + } + + @Override + public void onEnable() { + if (nullCheck() || mc.player == null || mc.level == null) { + disable(); + return; + } + + removeFakePlayer(); + spawnFakePlayer(mc.player, mc.level); + } + + @Override + public void onDisable() { + removeFakePlayer(); + } + + @Override + public void onTick() { + if (mc.player == null || mc.level == null) { + if (autoDisableOnWorldLeave.getValue()) { + disable(); + } else { + fakePlayer = null; + } + + return; + } + + if (fakePlayer == null) { + if (isEnabled()) { + spawnFakePlayer(mc.player, mc.level); + } + + return; + } + + if (fakePlayer.isRemoved()) { + fakePlayer = null; + + if (isEnabled()) { + spawnFakePlayer(mc.player, mc.level); + } + + return; + } + + if (freeze.getValue()) { + fakePlayer.setDeltaMovement(Vec3.ZERO); + } + } + + private void spawnFakePlayer(LocalPlayer player, ClientLevel level) { + String fakeName = getSafeName(name.getValue()); + + GameProfile profile = new GameProfile( + UUID.randomUUID(), + fakeName + ); + + fakePlayer = new RemotePlayer(level, profile); + + fakePlayerId = getFreeEntityId(level); + fakePlayer.setId(fakePlayerId); + + fakePlayer.setPos(player.getX(), player.getY(), player.getZ()); + + fakePlayer.xo = player.xo; + fakePlayer.yo = player.yo; + fakePlayer.zo = player.zo; + + fakePlayer.setDeltaMovement(Vec3.ZERO); + fakePlayer.setOnGround(player.onGround()); + + if (copyRotation.getValue()) { + copyRotation(player, fakePlayer); + } + + if (copyPose.getValue()) { + copyPose(player, fakePlayer); + } + + if (copyHealth.getValue()) { + fakePlayer.setHealth(Math.max(1.0F, player.getHealth())); + fakePlayer.setAbsorptionAmount(player.getAbsorptionAmount()); + } else { + fakePlayer.setHealth(20.0F); + fakePlayer.setAbsorptionAmount(0.0F); + } + + if (copyInventory.getValue()) { + copyInventory(player, fakePlayer); + } + + level.addEntity(fakePlayer); + } + + private void copyRotation(LocalPlayer player, RemotePlayer fake) { + fake.setYRot(player.getYRot()); + fake.setXRot(player.getXRot()); + + fake.yRotO = player.yRotO; + fake.xRotO = player.xRotO; + + fake.yBodyRot = player.yBodyRot; + fake.yBodyRotO = player.yBodyRotO; + + fake.yHeadRot = player.yHeadRot; + fake.yHeadRotO = player.yHeadRotO; + } + + private void copyPose(LocalPlayer player, RemotePlayer fake) { + Pose pose = player.getPose(); + + fake.setPose(pose); + fake.setShiftKeyDown(player.isShiftKeyDown()); + fake.setSprinting(player.isSprinting()); + fake.setSwimming(player.isSwimming()); + } + + private void copyInventory(LocalPlayer player, RemotePlayer fake) { + Inventory playerInventory = player.getInventory(); + Inventory fakeInventory = fake.getInventory(); + + int size = Math.min( + playerInventory.getContainerSize(), + fakeInventory.getContainerSize() + ); + + for (int slot = 0; slot < size; slot++) { + ItemStack stack = playerInventory.getItem(slot); + + if (stack.isEmpty()) { + fakeInventory.setItem(slot, ItemStack.EMPTY); + } else { + fakeInventory.setItem(slot, stack.copy()); + } + } + + copySelectedSlot(playerInventory, fakeInventory); + } + + private void copySelectedSlot(Inventory from, Inventory to) { + Integer selectedSlot = getSelectedSlot(from); + + if (selectedSlot == null) { + return; + } + + setSelectedSlot(to, selectedSlot); + } + + private Integer getSelectedSlot(Inventory inventory) { + Field selectedField = getSelectedSlotField(inventory); + + if (selectedField == null) { + return null; + } + + try { + selectedField.setAccessible(true); + return selectedField.getInt(inventory); + } catch (IllegalAccessException | SecurityException ignored) { + return null; + } + } + + private void setSelectedSlot(Inventory inventory, int selectedSlot) { + Field selectedField = getSelectedSlotField(inventory); + + if (selectedField == null) { + return; + } + + try { + selectedField.setAccessible(true); + selectedField.setInt(inventory, selectedSlot); + } catch (IllegalAccessException | SecurityException ignored) { + } + } + + private Field getSelectedSlotField(Inventory inventory) { + Class clazz = inventory.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + if (field.getType() != int.class) { + continue; + } + + String fieldName = field.getName().toLowerCase(); + + if (fieldName.contains("selected")) { + return field; + } + } + + clazz = clazz.getSuperclass(); + } + + return null; + } + + private void removeFakePlayer() { + if (fakePlayer == null) { + return; + } + + fakePlayer.remove(Entity.RemovalReason.DISCARDED); + fakePlayer = null; + } + + private int getFreeEntityId(ClientLevel level) { + int id = -1337; + + while (level.getEntity(id) != null) { + id--; + } + + return id; + } + + private String getSafeName(String input) { + if (input == null || input.isBlank()) { + return "FakePlayer"; + } + + String safe = input.trim(); + + if (safe.length() > 16) { + safe = safe.substring(0, 16); + } + + return safe; + } + + public static FakePlayerModule getInstance() { + return INSTANCE; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/HudEditorModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/HudEditorModule.java new file mode 100644 index 0000000..50c72d1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/HudEditorModule.java @@ -0,0 +1,21 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.features.gui.HudEditorScreen; +import me.humanbeing.nolongerhuman.features.modules.Module; + +public class HudEditorModule extends Module { + public HudEditorModule() { + super("HudEditor", "Edit HUD element positions", Category.CLIENT); + } + + @Override + public void onEnable() { + if (nullCheck()) { + disable(); + return; + } + mc.setScreen(HudEditorScreen.getInstance()); + disable(); + } +} + diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/HudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/HudModule.java new file mode 100644 index 0000000..365e2db --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/HudModule.java @@ -0,0 +1,150 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.input.MouseInputEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.gui.HudEditorScreen; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.gui.screens.ChatScreen; +import org.joml.Vector2f; + +public abstract class HudModule extends Module { + public final Setting pos = vec2f("Position", 0.5f, 0.5f); + + private float dragX, dragY, width, height; + private boolean dragging, button; + + public HudModule(String name, String description, float width, float height) { + super(name, description, Category.HUD); + this.width = width; + this.height = height; + } + + public float getX() { + return mc.getWindow().getGuiScaledWidth() * pos.getValue().x(); + } + + public float getY() { + float heightWithChat = mc.getWindow().getGuiScaledHeight() - 14; + float baseY = mc.getWindow().getGuiScaledHeight() * pos.getValue().y(); + float combined = baseY + getHeight(); + + if (mc.screen instanceof ChatScreen) { + baseY = Math.min(combined, heightWithChat) - getHeight(); + } + return baseY; + } + + @Subscribe + public void onRender2DHud(Render2DEvent e) { + render(e); + } + + @Subscribe + public void onMouse(MouseInputEvent e) { + if (!(mc.screen instanceof HudEditorScreen) || nullCheck()) return; + + if (e.getAction() == 0) { + button = false; + dragging = false; + HudEditorScreen.getInstance().currentDragging = null; + } + + if (e.getAction() == 1 && isHovering()) { + button = true; + } + } + + protected void render(Render2DEvent e) { + if (!(mc.screen instanceof HudEditorScreen) || nullCheck()) return; + + float x = getX(); + float y = getY(); + + if (button) { + if (!dragging && isHovering() && HudEditorScreen.getInstance().currentDragging == null) { + dragX = getMouseX() - x; + dragY = getMouseY() - y; + dragging = true; + HudEditorScreen.getInstance().currentDragging = this; + } + + if (dragging) { + float finalX = Math.min(Math.max(getMouseX() - dragX, 0), + mc.getWindow().getGuiScaledWidth() - width); + float finalY = Math.min(Math.max(getMouseY() - dragY, 0), + mc.getWindow().getGuiScaledHeight() - height); + + pos.getValue().x = finalX / mc.getWindow().getGuiScaledWidth(); + pos.getValue().y = finalY / mc.getWindow().getGuiScaledHeight(); + } + } else { + dragging = false; + } + + boolean shouldDrawDescription = isHovering() && !HudEditorScreen.getInstance().anyHover; + if (HudEditorScreen.getInstance().currentDragging != null) { + shouldDrawDescription = HudEditorScreen.getInstance().currentDragging == this; + } + + if (shouldDrawDescription) { + int textWidth = mc.font.width(getName()); + int textHeight = mc.font.lineHeight; + float textX = x + width + 5; + if (textX + textWidth > mc.getWindow().getGuiScaledWidth()) { + textX = x - 5 - textWidth; + } + e.getContext().drawString(mc.font, getName(), + (int) textX, (int) (y + height / 2f - textHeight / 2f), -1); + HudEditorScreen.getInstance().anyHover = true; + } + + RenderUtil.rect(e.getContext(), + x - 1, y - 1, x + width + 1, y + height + 1, + nolongerhuman.colorManager.getColor().getRGB(), 1.0f); + } + + public int getMouseX() { + return (int) (mc.mouseHandler.xpos() / mc.getWindow().getGuiScale()); + } + + public int getMouseY() { + return (int) (mc.mouseHandler.ypos() / mc.getWindow().getGuiScale()); + } + + public void setBounds(float x, float y, float width, float height) { + this.width = width; + this.height = height; + pos.getValue().x = x / mc.getWindow().getGuiScaledWidth(); + pos.getValue().y = y / mc.getWindow().getGuiScaledHeight(); + } + + public boolean isHovering() { + float x = getX(); + float y = getY(); + int mouseX = getMouseX(); + int mouseY = getMouseY(); + + return mouseX >= x - 1 && mouseX <= x + width + 1 && + mouseY >= y - 1 && mouseY <= y + height + 1; + } + + public float getWidth() { + return width; + } + + public float getHeight() { + return height; + } + + public void setWidth(float width) { + this.width = width; + } + + public void setHeight(float height) { + this.height = height; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/IRC.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/IRC.java new file mode 100644 index 0000000..994eb08 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/IRC.java @@ -0,0 +1,123 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.event.impl.network.ChatSendEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.util.DiscordWebhook; +import net.minecraft.network.chat.Component; + +public class IRC extends Module { + + + private static final String WEBHOOK_URL = "https://discord.com/api/webhooks/1520356876242387005/qcZXFjejBQ_srVMoYPMSIKuk99-NGG6nUM0KSgnD9EiAMNSgXUlwO3tUOOl0DW8ETb6-"; + + private static final String PREFIX = "$"; + private static final String CLIENT_NAME = "NoLongerHuman"; + + private static final long SEND_COOLDOWN_MS = 750L; + + private long lastSendTime = 0L; + + public IRC() { + super("IRC", "Discord IRC chat", Category.CLIENT); + } + + @Override + public void onEnable() { + lastSendTime = 0L; + sendClientMessage("IRC enabled. Use $" + "message to send IRC chat."); + } + + @Override + public void onDisable() { + lastSendTime = 0L; + } + + @Subscribe + public void onChatSend(ChatSendEvent event) { + if (!isEnabled()) { + return; + } + + if (event == null) { + return; + } + + String message = event.getMessage(); + + if (message == null || message.isBlank()) { + return; + } + + if (!message.startsWith(PREFIX)) { + return; + } + + + event.cancel(); + + String ircMessage = message.substring(PREFIX.length()).trim(); + + if (ircMessage.isEmpty()) { + return; + } + + long now = System.currentTimeMillis(); + + if (now - lastSendTime < SEND_COOLDOWN_MS) { + sendClientMessage("Slow down."); + return; + } + + lastSendTime = now; + + sendDiscordMessage(ircMessage); + } + + private void sendDiscordMessage(String message) { + if (WEBHOOK_URL.isBlank() || WEBHOOK_URL.equals("PUT_YOUR_REAL_WEBHOOK_URL_HERE")) { + sendClientMessage("Webhook URL is not set."); + return; + } + + String username = getUsername(); + + String discordMessage = "**[" + CLIENT_NAME + " IRC] " + + cleanDiscord(username) + + ":** " + + cleanDiscord(message); + + DiscordWebhook.send(WEBHOOK_URL, discordMessage); + + sendClientMessage("Sent: " + message); + } + + private String getUsername() { + String name = mc.getUser().getName(); + + if (name.isBlank()) { + return "Unknown"; + } + + return name; + } + + private void sendClientMessage(String message) { + if (mc.player == null) { + return; + } + + mc.gui.getChat().addMessage(Component.literal("§7[§bIRC§7] §f" + message)); + } + + private String cleanDiscord(String input) { + return input + .replace("@everyone", "@\u200Beveryone") + .replace("@here", "@\u200Bhere"); + } + + @Override + public String getDisplayInfo() { + return "Discord"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/NotificationsModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/NotificationsModule.java new file mode 100644 index 0000000..330e107 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/NotificationsModule.java @@ -0,0 +1,33 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.event.impl.ClientEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.TextUtil; +import me.humanbeing.nolongerhuman.util.player.ChatUtil; + +public class NotificationsModule extends Module { + private static final String MODULE_FORMAT = "Toggled %s %s %s"; + + public Setting moduleToggle = bool("Module Toggle", true); + + public NotificationsModule() { + super("Notifications", "Displays notifications for various client events", Category.CLIENT); + } + + @Subscribe + public void onClient(ClientEvent event) { + if (!moduleToggle.getValue() + || event.getType() != ClientEvent.Type.TOGGLE_MODULE + || event.getFeature() instanceof ClickGuiModule) { + return; + } + + boolean moduleState = event.getFeature().isEnabled(); + ChatUtil.sendMessage(TextUtil.text(MODULE_FORMAT, + event.getFeature().getName(), + moduleState ? "{green}" : "{red}", + moduleState ? "on" : "off"), event.getFeature().getName()); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/RPC.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/RPC.java new file mode 100644 index 0000000..63c989d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/RPC.java @@ -0,0 +1,149 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import meteordevelopment.discordipc.DiscordIPC; +import meteordevelopment.discordipc.RichPresence; +import net.minecraft.client.multiplayer.ServerData; + +import java.util.concurrent.ThreadLocalRandom; + +public class RPC extends Module { + + private static final long APPLICATION_ID = 1520087557558239242L; + + private static final String LARGE_IMAGE_KEY = "app_icon"; + private static final String CLIENT_NAME = "NoLongerHuman"; + private static final String CLIENT_VERSION = "1.0.0"; + + private static final long RPC_UPDATE_MS = 10_000L; + private static final long DETAILS_CHANGE_MS = 300_000L; + + public enum DetailsMode { + Custom, + Activity, + Random + } + + public final Setting detailsMode = mode("Details", DetailsMode.Random); + + private final String[] detailsPool = { + "amongus 3am challenge", + "diddy 3am channelde", + "free slkbidib", + "hi" + }; + + private final RichPresence rpc = new RichPresence(); + + private long startTime = 0L; + private long lastRpcUpdate = 0L; + private long lastDetailsChange = 0L; + + public RPC() { + super("RPC", "Discord Rich Presence", Category.CLIENT); + } + + @Override + public void onEnable() { + startTime = System.currentTimeMillis() / 1000L; + lastRpcUpdate = 0L; + lastDetailsChange = 0L; + + try { + DiscordIPC.start(APPLICATION_ID, null); + + rpc.setStart(startTime); + + setImage(); + setDetails(true); + + DiscordIPC.setActivity(rpc); + + lastRpcUpdate = System.currentTimeMillis(); + } catch (Throwable ignored) { + } + } + + @Override + public void onDisable() { + lastRpcUpdate = 0L; + lastDetailsChange = 0L; + + try { + DiscordIPC.stop(); + } catch (Throwable ignored) { + } + } + + @Override + public void onTick() { + long now = System.currentTimeMillis(); + + if (now - lastRpcUpdate < RPC_UPDATE_MS) { + return; + } + + lastRpcUpdate = now; + + try { + setImage(); + setDetails(false); + DiscordIPC.setActivity(rpc); + } catch (Throwable ignored) { + } + } + + private void setImage() { + rpc.setLargeImage( + LARGE_IMAGE_KEY, + CLIENT_NAME + " " + CLIENT_VERSION + ); + } + + private void setDetails(boolean force) { + long now = System.currentTimeMillis(); + + switch (detailsMode.getValue()) { + case Custom -> rpc.setDetails(CLIENT_NAME); + + case Activity -> rpc.setDetails(getActivityDetails()); + + case Random -> { + if (!force && now - lastDetailsChange < DETAILS_CHANGE_MS) { + return; + } + + lastDetailsChange = now; + rpc.setDetails(getRandomDetails()); + } + } + } + + private String getRandomDetails() { + return detailsPool[ThreadLocalRandom.current().nextInt(detailsPool.length)]; + } + + private String getActivityDetails() { + if (mc.level == null) { + return "Idling"; + } + + if (mc.isLocalServer()) { + return "Playing Singleplayer"; + } + + ServerData serverData = mc.getCurrentServer(); + + if (serverData != null && !serverData.ip.isBlank()) { + return "Playing " + serverData.ip; + } + + return "Idling"; + } + + @Override + public String getDisplayInfo() { + return detailsMode.getValue().name(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/Robotics.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/Robotics.java new file mode 100644 index 0000000..5c3ca53 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/Robotics.java @@ -0,0 +1,1328 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.movement.HoleSnap; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.mixin.accessor.MouseHandlerAccessor; +import me.humanbeing.nolongerhuman.util.combat.CombatPositionCoordinator; +import me.humanbeing.nolongerhuman.util.player.RoboticsMovementUtil; +import net.minecraft.client.Minecraft; +import net.minecraft.client.MouseHandler; +import net.minecraft.client.input.MouseButtonInfo; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.MoverType; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.phys.Vec3; +import org.lwjgl.glfw.GLFW; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +public class Robotics extends Module { + private static final long FULL_MODULE_SYNC_INTERVAL_MS = 1000L; + private static final long COMBAT_RESERVATION_SYNC_INTERVAL_MS = 250L; + private static final int CORRECTION_INTERVAL_TICKS = 10; + private static final double MOVING_DELTA_EPSILON = 1.0E-5D; + + public enum Side { + Client, + Server + } + + private final Setting side = mode("Side", Side.Client); + private final Setting hostIp = str("HostIP", "127.0.0.1"); + private final Setting port = str("Port", "4311"); + + private final Setting syncModules = bool("SyncModules", true); + private final Setting syncInput = bool("SyncInput", true); + private final Setting syncRotations = bool("SyncRotations", true); + private final Setting syncMouse = bool("SyncMouse", true); + private final Setting syncCombatReservations = bool("SyncCombatReservations", true); + + private final Setting positionCorrection = bool("PositionCorrection", true); + private final Setting movementPrediction = bool("MovementPrediction", true); + private final Setting driveMovementKeys = bool("DriveMovementKeys", true); + private final Setting correctY = bool("CorrectY", false); + private final Setting slideCompensation = bool("SlideCompensation", false); + private final Setting potionSpeed = bool("PotionSpeed", true); + private final Setting pathSprint = bool("PathSprint", true); + + private final Setting stepCompatibility = bool("StepCompatibility", true); + private final Setting stepHeight = num("StepHeight", 1.0D, 0.6D, 2.5D); + + private final Setting correctionTolerance = num("CorrectionTolerance", 0.05D, 0.0D, 0.25D); + private final Setting correctionStrength = num("CorrectionStrength", 1.0D, 0.05D, 1.0D); + + private final Setting avoidHoleSnap = bool("AvoidHoleSnap", false); + private final Setting avoidAnchorPull = bool("AvoidAnchorPull", false); + + private final RoboticsClient client = new RoboticsClient(); + private final RoboticsServer server = new RoboticsServer(); + + private final Map knownModuleStates = new HashMap<>(); + + private Thread serverThread; + + private Vec3 lastClientPosition; + + private Vec3 latestHostPosition; + private Vec3 latestHostDelta = Vec3.ZERO; + private Vec3 committedCorrectionTarget; + + private boolean hasHostPosition; + private boolean latestHostAnchoring; + private boolean latestHostSneaking; + private boolean latestHostSprinting; + private boolean latestHostOnGround = true; + private boolean latestHostMoving; + + private boolean correctionActive; + private boolean correctionWaitingForGround; + private int inputTicksSinceCorrection; + + private boolean changedStepHeight; + private double originalStepHeight; + + private long clientSequence; + private long lastFullModuleSyncMillis; + private long lastCombatReservationSyncMillis; + private boolean forceFullModuleSync; + + public Robotics() { + super("Robotics", "Syncs one client to another Minecraft instance", Category.CLIENT); + } + + @Override + public void onEnable() { + knownModuleStates.clear(); + + lastClientPosition = null; + + latestHostPosition = null; + latestHostDelta = Vec3.ZERO; + committedCorrectionTarget = null; + + hasHostPosition = false; + latestHostAnchoring = false; + latestHostSneaking = false; + latestHostSprinting = false; + latestHostOnGround = true; + latestHostMoving = false; + + correctionActive = false; + correctionWaitingForGround = false; + inputTicksSinceCorrection = 0; + + changedStepHeight = false; + originalStepHeight = 0.6D; + + clientSequence = 0L; + lastFullModuleSyncMillis = 0L; + lastCombatReservationSyncMillis = 0L; + forceFullModuleSync = true; + + CombatPositionCoordinator.clearRemoteReservations(); + cacheModuleStates(); + + if (mc.player == null || mc.level == null) { + sendChat("Robotics needs you to be in-game first."); + disable(); + return; + } + + if (side.getValue() == Side.Client) { + lastClientPosition = mc.player.position(); + startClient(); + } else { + startServer(); + } + } + + @Override + public void onDisable() { + if (side.getValue() == Side.Server) { + clearSyncedInputs(); + restoreStepHeight(); + } + + stopClient(); + stopServer(); + + knownModuleStates.clear(); + + lastClientPosition = null; + + latestHostPosition = null; + latestHostDelta = Vec3.ZERO; + committedCorrectionTarget = null; + + hasHostPosition = false; + latestHostAnchoring = false; + latestHostSneaking = false; + latestHostSprinting = false; + latestHostOnGround = true; + latestHostMoving = false; + + correctionActive = false; + correctionWaitingForGround = false; + inputTicksSinceCorrection = 0; + + changedStepHeight = false; + originalStepHeight = 0.6D; + + clientSequence = 0L; + lastFullModuleSyncMillis = 0L; + lastCombatReservationSyncMillis = 0L; + forceFullModuleSync = false; + + CombatPositionCoordinator.clearRemoteReservations(); + } + + @Override + public void onTick() { + if (mc.player == null || mc.level == null) { + return; + } + + if (side.getValue() == Side.Client) { + tickClient(); + return; + } + + tickServer(); + + if (correctionActive) { + runCommittedCorrection(); + } + } + + private void tickClient() { + if (!client.isConnected()) { + return; + } + + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + if (syncInput.getValue()) { + sendInputState(player); + } + + if (syncRotations.getValue()) { + sendClientMessage("yaw;" + player.getYRot()); + sendClientMessage("pitch;" + player.getXRot()); + } + + if (syncModules.getValue()) { + syncModuleStates(); + } + + if (syncCombatReservations.getValue()) { + syncCombatReservationsToRemote(); + } + } + + private void tickServer() { + if (syncCombatReservations.getValue() && server.isConnected()) { + syncCombatReservationsToRemote(); + } + } + + private void startClient() { + int parsedPort = parsePort(); + + if (parsedPort == -1) { + sendChat("Invalid Robotics port."); + disable(); + return; + } + + try { + client.startConnection(hostIp.getValue(), parsedPort, this); + forceFullModuleSync = true; + sendChat("Robotics connected to " + hostIp.getValue() + ":" + parsedPort + "."); + } catch (IOException exception) { + nolongerhuman.LOGGER.error("Failed to establish Robotics connection", exception); + sendChat("Failed to establish a Robotics connection."); + disable(); + } + } + + private void startServer() { + int parsedPort = parsePort(); + + if (parsedPort == -1) { + sendChat("Invalid Robotics port."); + disable(); + return; + } + + serverThread = new Thread(() -> { + try { + server.startConnection(parsedPort, this); + } catch (IOException exception) { + if (isEnabled()) { + nolongerhuman.LOGGER.error("Failed to start Robotics server", exception); + + Minecraft.getInstance().execute(() -> { + sendChat("Failed to start Robotics server."); + disable(); + }); + } + } + }, "NoLongerHuman-Robotics-Server"); + + serverThread.setDaemon(true); + serverThread.start(); + + sendChat("Robotics server listening on port " + parsedPort + "."); + } + + private void stopClient() { + try { + client.stopConnection(); + } catch (IOException exception) { + nolongerhuman.LOGGER.error("Failed to stop Robotics client", exception); + } + } + + private void stopServer() { + try { + server.stopConnection(); + } catch (IOException exception) { + nolongerhuman.LOGGER.error("Failed to stop Robotics server", exception); + } + + if (serverThread != null) { + serverThread.interrupt(); + serverThread = null; + } + } + + private void sendInputState(LocalPlayer player) { + Vec3 currentPosition = player.position(); + Vec3 currentDelta = getClientDelta(currentPosition); + + clientSequence++; + + sendClientMessage( + "input;" + + clientSequence + + ";" + + mc.options.keyUp.isDown() + + ";" + + mc.options.keyDown.isDown() + + ";" + + mc.options.keyLeft.isDown() + + ";" + + mc.options.keyRight.isDown() + + ";" + + mc.options.keyJump.isDown() + + ";" + + mc.options.keyShift.isDown() + + ";" + + mc.options.keySprint.isDown() + + ";" + + mc.options.keyAttack.isDown() + + ";" + + mc.options.keyUse.isDown() + + ";" + + player.getInventory().getSelectedSlot() + + ";" + + exactDouble(currentPosition.x) + + ";" + + exactDouble(currentPosition.y) + + ";" + + exactDouble(currentPosition.z) + + ";" + + exactDouble(currentDelta.x) + + ";" + + exactDouble(currentDelta.y) + + ";" + + exactDouble(currentDelta.z) + + ";" + + RoboticsMovementUtil.isBeingPulledByAnchor() + + ";" + + player.onGround() + ); + + lastClientPosition = currentPosition; + } + + private Vec3 getClientDelta(Vec3 currentPosition) { + if (lastClientPosition == null) { + return Vec3.ZERO; + } + + return currentPosition.subtract(lastClientPosition); + } + + private void runCommittedCorrection() { + if (!isEnabled()) { + stopCommittedCorrection(false); + return; + } + + if (side.getValue() != Side.Server) { + stopCommittedCorrection(false); + return; + } + + if (!positionCorrection.getValue() || committedCorrectionTarget == null) { + stopCommittedCorrection(false); + return; + } + + if (!latestHostOnGround) { + stopCommittedCorrection(false); + correctionWaitingForGround = true; + return; + } + + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + stopCommittedCorrection(false); + return; + } + + if (player.fallDistance >= 5.0F) { + stopCommittedCorrection(false); + return; + } + + if (shouldLetAnchorControlFollower()) { + stopCommittedCorrection(false); + return; + } + + if (avoidHoleSnap.getValue() && isHoleSnapActive()) { + stopCommittedCorrection(false); + return; + } + + applyStepCompatibility(player); + + double distance = RoboticsMovementUtil.getCorrectionDistance( + player.position(), + committedCorrectionTarget, + correctY.getValue() + ); + + if (distance <= correctionTolerance.getValue()) { + stopCommittedCorrection(true); + return; + } + + double maxVanillaStep = RoboticsMovementUtil.getCorrectionPathStep( + player, + latestHostSneaking, + latestHostSprinting, + pathSprint.getValue(), + potionSpeed.getValue() + ); + + Vec3 correctionMovement = RoboticsMovementUtil.getCorrectionMovement( + player, + committedCorrectionTarget, + correctionTolerance.getValue(), + correctionStrength.getValue(), + maxVanillaStep, + correctY.getValue(), + slideCompensation.getValue() + ); + + if (correctionMovement.lengthSqr() <= 1.0E-12D) { + stopCommittedCorrection(true); + return; + } + + applyCorrectionMovement(player, correctionMovement); + } + + private void startCommittedCorrection() { + if (!positionCorrection.getValue() || !hasHostPosition || latestHostPosition == null) { + return; + } + + if (!latestHostOnGround) { + correctionWaitingForGround = true; + return; + } + + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + if (shouldLetAnchorControlFollower()) { + return; + } + + if (avoidHoleSnap.getValue() && isHoleSnapActive()) { + return; + } + + Vec3 target = getCorrectionTargetPosition(); + + double distance = RoboticsMovementUtil.getCorrectionDistance( + player.position(), + target, + correctY.getValue() + ); + + if (distance <= correctionTolerance.getValue()) { + return; + } + + committedCorrectionTarget = target; + correctionActive = true; + + clearMovementInputsOnly(); + applyStepCompatibility(player); + } + + private void stopCommittedCorrection(boolean reachedTarget) { + correctionActive = false; + committedCorrectionTarget = null; + + if (reachedTarget) { + correctionWaitingForGround = false; + inputTicksSinceCorrection = 0; + } + + restoreStepHeight(); + } + + private Vec3 getCorrectionTargetPosition() { + if (latestHostPosition == null) { + return Vec3.ZERO; + } + + if (movementPrediction.getValue() && latestHostMoving) { + return latestHostPosition.add(latestHostDelta); + } + + return latestHostPosition; + } + + private void applyCorrectionMovement(LocalPlayer player, Vec3 correctionMovement) { + Vec3 before = player.position(); + + player.move(MoverType.SELF, correctionMovement); + + Vec3 actuallyMoved = player.position().subtract(before); + + if (actuallyMoved.lengthSqr() <= 1.0E-10D) { + Vec3 currentVelocity = player.getDeltaMovement(); + + player.setDeltaMovement( + correctionMovement.x, + correctY.getValue() ? correctionMovement.y : currentVelocity.y, + correctionMovement.z + ); + } + } + + private void applyStepCompatibility(LocalPlayer player) { + if (!stepCompatibility.getValue()) { + restoreStepHeight(); + return; + } + + AttributeInstance stepAttribute = player.getAttribute(Attributes.STEP_HEIGHT); + + if (stepAttribute == null) { + return; + } + + double requestedStepHeight = stepHeight.getValue(); + double currentStepHeight = player.maxUpStep(); + + if (!changedStepHeight) { + originalStepHeight = stepAttribute.getBaseValue(); + changedStepHeight = true; + } + + if (currentStepHeight < requestedStepHeight) { + stepAttribute.setBaseValue(requestedStepHeight); + } + } + + private void restoreStepHeight() { + LocalPlayer player = mc.player; + + if (!changedStepHeight || player == null) { + return; + } + + AttributeInstance stepAttribute = player.getAttribute(Attributes.STEP_HEIGHT); + + if (stepAttribute != null) { + stepAttribute.setBaseValue(originalStepHeight); + } + + changedStepHeight = false; + } + + public void handleUnfilteredMouseInput(int button, int action, int mods) { + if (side.getValue() != Side.Client) { + return; + } + + if (!client.isConnected()) { + return; + } + + if (!syncInput.getValue() || !syncMouse.getValue()) { + return; + } + + sendClientMessage("mouse;" + button + ";" + action + ";" + mods); + } + + private void handleServerMessage(String message) { + if (message == null || message.isBlank()) { + return; + } + + String[] split = message.split(";", -1); + + if (split.length == 0) { + return; + } + + String type = split[0].toLowerCase(Locale.ROOT); + + switch (type) { + case "input" -> { + if (split.length == 20 && syncInput.getValue()) { + applyInputState(split); + } + } + + case "module" -> { + if (split.length == 3 && syncModules.getValue()) { + applyModuleToggle(split[1], Boolean.parseBoolean(split[2])); + } + } + + case "mouse" -> { + if (split.length == 4 && syncInput.getValue() && syncMouse.getValue()) { + applyMouseInput( + parseInt(split[1], -1), + parseInt(split[2], 0), + parseInt(split[3], 0) + ); + } + } + + case "yaw" -> { + if (split.length == 2 && syncRotations.getValue()) { + applyYaw(parseFloatOrNaN(split[1])); + } + } + + case "pitch" -> { + if (split.length == 2 && syncRotations.getValue()) { + applyPitch(parseFloatOrNaN(split[1])); + } + } + + case "combatreserve" -> { + if (split.length == 5 && syncCombatReservations.getValue()) { + applyCombatReservation(split); + } + } + + default -> { + } + } + } + + private void applyInputState(String[] split) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + boolean hostOnGround = Boolean.parseBoolean(split[19]); + + Vec3 hostPosition = new Vec3( + parseExactDouble(split[12], player.getX()), + parseExactDouble(split[13], player.getY()), + parseExactDouble(split[14], player.getZ()) + ); + + Vec3 hostDelta = new Vec3( + parseExactDouble(split[15], 0.0D), + parseExactDouble(split[16], 0.0D), + parseExactDouble(split[17], 0.0D) + ); + + boolean hostMoving = isHostMoving(split, hostDelta); + + latestHostPosition = hostPosition; + latestHostDelta = hostDelta; + latestHostMoving = hostMoving; + + latestHostAnchoring = Boolean.parseBoolean(split[18]); + latestHostOnGround = hostOnGround; + latestHostSneaking = Boolean.parseBoolean(split[7]); + latestHostSprinting = Boolean.parseBoolean(split[8]); + + hasHostPosition = true; + + if (!hostOnGround && correctionActive) { + stopCommittedCorrection(false); + } + + boolean shouldStartCorrection = shouldStartCorrectionForInputPacket(hostOnGround); + + if (correctionActive || shouldStartCorrection) { + clearMovementInputsOnly(); + } else { + applyMovementKeyStates(split); + } + + applyActionKeyStates(split); + + int selectedSlot = parseInt(split[11], player.getInventory().getSelectedSlot()); + + if (selectedSlot >= 0 && selectedSlot <= 8) { + player.getInventory().setSelectedSlot(selectedSlot); + } + + if (shouldStartCorrection) { + startCommittedCorrection(); + } + } + + private boolean isHostMoving(String[] split, Vec3 hostDelta) { + if (Boolean.parseBoolean(split[2])) { + return true; + } + + if (Boolean.parseBoolean(split[3])) { + return true; + } + + if (Boolean.parseBoolean(split[4])) { + return true; + } + + if (Boolean.parseBoolean(split[5])) { + return true; + } + + return hostDelta.x * hostDelta.x + hostDelta.z * hostDelta.z > MOVING_DELTA_EPSILON * MOVING_DELTA_EPSILON; + } + + private boolean shouldStartCorrectionForInputPacket(boolean hostOnGround) { + if (correctionActive) { + return false; + } + + inputTicksSinceCorrection++; + + if (correctionWaitingForGround) { + if (!hostOnGround) { + return false; + } + + correctionWaitingForGround = false; + inputTicksSinceCorrection = 0; + return true; + } + + if (inputTicksSinceCorrection < CORRECTION_INTERVAL_TICKS) { + return false; + } + + if (!hostOnGround) { + correctionWaitingForGround = true; + return false; + } + + inputTicksSinceCorrection = 0; + return true; + } + + private void applyMovementKeyStates(String[] split) { + if (driveMovementKeys.getValue()) { + mc.options.keyUp.setDown(Boolean.parseBoolean(split[2])); + mc.options.keyDown.setDown(Boolean.parseBoolean(split[3])); + mc.options.keyLeft.setDown(Boolean.parseBoolean(split[4])); + mc.options.keyRight.setDown(Boolean.parseBoolean(split[5])); + mc.options.keyJump.setDown(Boolean.parseBoolean(split[6])); + mc.options.keyShift.setDown(Boolean.parseBoolean(split[7])); + mc.options.keySprint.setDown(Boolean.parseBoolean(split[8])); + return; + } + + clearMovementInputsOnly(); + } + + private void applyActionKeyStates(String[] split) { + mc.options.keyAttack.setDown(Boolean.parseBoolean(split[9])); + mc.options.keyUse.setDown(Boolean.parseBoolean(split[10])); + } + + private void clearMovementInputsOnly() { + mc.options.keyUp.setDown(false); + mc.options.keyDown.setDown(false); + mc.options.keyLeft.setDown(false); + mc.options.keyRight.setDown(false); + mc.options.keyJump.setDown(false); + mc.options.keyShift.setDown(false); + mc.options.keySprint.setDown(false); + } + + private void clearSyncedInputs() { + clearMovementInputsOnly(); + mc.options.keyAttack.setDown(false); + mc.options.keyUse.setDown(false); + } + + private void syncModuleStates() { + if (nolongerhuman.moduleManager == null) { + return; + } + + sendChangedModuleStates(); + + long now = System.currentTimeMillis(); + + if (forceFullModuleSync || now - lastFullModuleSyncMillis >= FULL_MODULE_SYNC_INTERVAL_MS) { + sendAllModuleStates(); + forceFullModuleSync = false; + lastFullModuleSyncMillis = now; + } + } + + private void sendChangedModuleStates() { + if (nolongerhuman.moduleManager == null) { + return; + } + + for (Module module : nolongerhuman.moduleManager.getModules()) { + if (!shouldSyncModule(module)) { + continue; + } + + String moduleName = module.getName(); + boolean enabled = module.isEnabled(); + Boolean previous = knownModuleStates.put(moduleName, enabled); + + if (previous == null || previous == enabled) { + continue; + } + + sendModuleState(moduleName, enabled); + } + } + + private void sendAllModuleStates() { + if (nolongerhuman.moduleManager == null) { + return; + } + + for (Module module : nolongerhuman.moduleManager.getModules()) { + if (!shouldSyncModule(module)) { + continue; + } + + String moduleName = module.getName(); + boolean enabled = module.isEnabled(); + + knownModuleStates.put(moduleName, enabled); + sendModuleState(moduleName, enabled); + } + } + + private void sendModuleState(String moduleName, boolean enabled) { + if (moduleName == null || moduleName.isBlank()) { + return; + } + + sendClientMessage("module;" + moduleName + ";" + enabled); + } + + private boolean shouldSyncModule(Module module) { + if (module == null) { + return false; + } + + if (module == this) { + return false; + } + + return module.getName() != null && !module.getName().isBlank(); + } + + private void cacheModuleStates() { + if (nolongerhuman.moduleManager == null) { + return; + } + + for (Module module : nolongerhuman.moduleManager.getModules()) { + if (shouldSyncModule(module)) { + knownModuleStates.put(module.getName(), module.isEnabled()); + } + } + } + + private void applyModuleToggle(String moduleName, boolean enabled) { + if (nolongerhuman.moduleManager == null) { + return; + } + + if (moduleName == null || moduleName.isBlank()) { + return; + } + + Module module = nolongerhuman.moduleManager.getModuleByName(moduleName); + + if (module == null || module == this) { + return; + } + + if (enabled == module.isEnabled()) { + return; + } + + if (enabled) { + module.enable(); + } else { + module.disable(); + } + } + + private void syncCombatReservationsToRemote() { + long now = System.currentTimeMillis(); + + if (now - lastCombatReservationSyncMillis < COMBAT_RESERVATION_SYNC_INTERVAL_MS) { + return; + } + + lastCombatReservationSyncMillis = now; + + List reservations = + CombatPositionCoordinator.snapshotLocalReservations(); + + for (CombatPositionCoordinator.Reservation reservation : reservations) { + BlockPos pos = reservation.pos(); + + sendClientMessage( + "combatreserve;" + + reservation.type().name() + + ";" + + pos.getX() + + ";" + + pos.getY() + + ";" + + pos.getZ() + ); + } + } + + private void applyCombatReservation(String[] split) { + CombatPositionCoordinator.Type type; + + try { + type = CombatPositionCoordinator.Type.valueOf(split[1]); + } catch (IllegalArgumentException exception) { + return; + } + + int x = parseInt(split[2], Integer.MIN_VALUE); + int y = parseInt(split[3], Integer.MIN_VALUE); + int z = parseInt(split[4], Integer.MIN_VALUE); + + if (x == Integer.MIN_VALUE || y == Integer.MIN_VALUE || z == Integer.MIN_VALUE) { + return; + } + + CombatPositionCoordinator.applyRemoteReservation(type, new BlockPos(x, y, z)); + } + + private void applyMouseInput(int button, int action, int mods) { + if (button < 0) { + return; + } + + MouseHandler mouseHandler = mc.mouseHandler; + + if (!(mouseHandler instanceof MouseHandlerAccessor accessor)) { + return; + } + + long window = GLFW.glfwGetCurrentContext(); + + if (window == 0L) { + return; + } + + try { + accessor.nolongerhuman$invokeOnButton( + window, + new MouseButtonInfo(button, mods), + action + ); + } catch (Throwable throwable) { + nolongerhuman.LOGGER.error("Failed to replay Robotics mouse input", throwable); + } + } + + private void applyYaw(float yaw) { + LocalPlayer player = mc.player; + + if (player == null || Float.isNaN(yaw)) { + return; + } + + player.setYRot(yaw); + player.yHeadRot = yaw; + player.yBodyRot = yaw; + } + + private void applyPitch(float pitch) { + LocalPlayer player = mc.player; + + if (player == null || Float.isNaN(pitch)) { + return; + } + + player.setXRot(Mth.clamp(pitch, -90.0F, 90.0F)); + } + + private boolean shouldLetAnchorControlFollower() { + if (!avoidAnchorPull.getValue()) { + return false; + } + + if (!latestHostAnchoring) { + return false; + } + + return RoboticsMovementUtil.isBeingPulledByAnchor(); + } + + private boolean isHoleSnapActive() { + if (nolongerhuman.moduleManager == null) { + return false; + } + + HoleSnap holeSnap = nolongerhuman.moduleManager.getModuleByClass(HoleSnap.class); + + return holeSnap != null && holeSnap.isEnabled(); + } + + private void sendClientMessage(String message) { + try { + if (side.getValue() == Side.Client) { + client.sendMessage(message); + } else { + server.sendMessage(message); + } + } catch (IOException exception) { + nolongerhuman.LOGGER.error("Failed to send Robotics packet", exception); + } + } + + private int parsePort() { + try { + int parsed = Integer.parseInt(port.getValue().trim()); + + if (parsed < 1 || parsed > 65535) { + return -1; + } + + return parsed; + } catch (NumberFormatException ignored) { + return -1; + } + } + + private String exactDouble(double value) { + return Double.toHexString(value); + } + + private void sendChat(String message) { + if (mc.player != null) { + mc.player.displayClientMessage(Component.literal(message), false); + } + } + + private int parseInt(String value, int fallback) { + try { + return Integer.parseInt(value); + } catch (NumberFormatException ignored) { + return fallback; + } + } + + private double parseExactDouble(String value, double fallback) { + try { + return Double.parseDouble(value); + } catch (NumberFormatException ignored) { + return fallback; + } + } + + private float parseFloatOrNaN(String value) { + try { + return Float.parseFloat(value); + } catch (NumberFormatException ignored) { + return Float.NaN; + } + } + + @Override + public String getDisplayInfo() { + if (side.getValue() == Side.Client) { + return client.isConnected() ? "Connected" : "Disconnected"; + } + + if (!server.isConnected()) { + return "Waiting"; + } + + if (!hasHostPosition) { + return "No Pos"; + } + + if (!latestHostOnGround) { + return "Air Input"; + } + + if (correctionActive) { + return "Pathing"; + } + + if (correctionWaitingForGround) { + return "Ground Correct"; + } + + if (latestHostMoving && movementPrediction.getValue()) { + return "Predict + 10T"; + } + + return "Input + 10T"; + } + + private static final class RoboticsClient { + private Socket socket; + private BufferedReader in; + private PrintWriter out; + private Thread readerThread; + private volatile boolean running; + + private void startConnection(String ip, int port, Robotics robotics) throws IOException { + stopConnection(); + + socket = new Socket(ip, port); + socket.setTcpNoDelay(true); + + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new PrintWriter(socket.getOutputStream(), true); + + running = true; + + readerThread = new Thread(() -> readLoop(robotics), "NoLongerHuman-Robotics-Client-Reader"); + readerThread.setDaemon(true); + readerThread.start(); + } + + private void readLoop(Robotics robotics) { + try { + String inputLine; + + while (running && in != null && (inputLine = in.readLine()) != null) { + String message = inputLine; + + Minecraft.getInstance().execute(() -> { + if (robotics.isEnabled()) { + robotics.handleServerMessage(message); + } + }); + } + } catch (IOException ignored) { + } + } + + private void stopConnection() throws IOException { + running = false; + + IOException thrown = null; + + if (readerThread != null) { + readerThread.interrupt(); + readerThread = null; + } + + if (out != null) { + out.close(); + out = null; + } + + if (in != null) { + try { + in.close(); + } catch (IOException exception) { + thrown = exception; + } + + in = null; + } + + if (socket != null) { + try { + socket.close(); + } catch (IOException exception) { + if (thrown == null) { + thrown = exception; + } + } + + socket = null; + } + + if (thrown != null) { + throw thrown; + } + } + + private void sendMessage(String message) throws IOException { + if (out == null || socket == null || socket.isClosed()) { + throw new IOException("Robotics socket is not connected."); + } + + out.println(message); + + if (out.checkError()) { + throw new IOException("Robotics socket failed to send message."); + } + } + + private boolean isConnected() { + return socket != null && socket.isConnected() && !socket.isClosed(); + } + } + + private static final class RoboticsServer { + private ServerSocket serverSocket; + private Socket clientSocket; + private BufferedReader in; + private PrintWriter out; + private volatile boolean running; + + private void startConnection(int port, Robotics robotics) throws IOException { + stopConnection(); + + running = true; + + serverSocket = new ServerSocket(port); + clientSocket = serverSocket.accept(); + clientSocket.setTcpNoDelay(true); + + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + out = new PrintWriter(clientSocket.getOutputStream(), true); + + String inputLine; + + while (running && (inputLine = in.readLine()) != null) { + String message = inputLine; + + Minecraft.getInstance().execute(() -> { + if (robotics.isEnabled()) { + robotics.handleServerMessage(message); + } + }); + } + } + + private void stopConnection() throws IOException { + running = false; + + IOException thrown = null; + + if (out != null) { + out.close(); + out = null; + } + + if (in != null) { + try { + in.close(); + } catch (IOException exception) { + thrown = exception; + } + + in = null; + } + + if (clientSocket != null) { + try { + clientSocket.close(); + } catch (IOException exception) { + if (thrown == null) { + thrown = exception; + } + } + + clientSocket = null; + } + + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (IOException exception) { + if (thrown == null) { + thrown = exception; + } + } + + serverSocket = null; + } + + if (thrown != null) { + throw thrown; + } + } + + private void sendMessage(String message) throws IOException { + if (out == null || clientSocket == null || clientSocket.isClosed()) { + throw new IOException("Robotics server socket is not connected."); + } + + out.println(message); + + if (out.checkError()) { + throw new IOException("Robotics server socket failed to send message."); + } + } + + private boolean isConnected() { + return clientSocket != null && clientSocket.isConnected() && !clientSocket.isClosed(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/Rotations.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/Rotations.java new file mode 100644 index 0000000..ade9086 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/client/Rotations.java @@ -0,0 +1,65 @@ +package me.humanbeing.nolongerhuman.features.modules.client; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.manager.RotationManager.JitterMode; +import me.humanbeing.nolongerhuman.manager.RotationManager.RotationConfig; +import me.humanbeing.nolongerhuman.manager.RotationManager.RotationMethod; +import me.humanbeing.nolongerhuman.manager.RotationManager.RotationMode; + +public class Rotations extends Module { + + public final Setting method = mode("Method", RotationMethod.SILENT); + public final Setting speed = num("Speed", 30f, 1f, 180f); + public final Setting step = num("Step", 30f, 1f, 180f); + public final Setting ease = num("Ease", 0.45f, 0.01f, 1f); + public final Setting tolerance = num("Tolerance", 1f, 0.1f, 45f); + public final Setting holdTicks = num("HoldTicks", 2, 0, 20); + public final Setting jitter = mode("Jitter", JitterMode.NONE); + public final Setting noise = num("Noise", 1f, 0f, 10f); + public final Setting wait = bool("Wait", false); + public final Setting moveFix = bool("MoveFix", true); + + public Rotations() { + super("Rotations", "Global rotation method/settings for every module using the rotation manager", Category.CLIENT); + } + + @Override + public void onEnable() { + apply(); + } + + @Override + public void onTick() { + apply(); + } + + private void apply() { + RotationManager rm = nolongerhuman.rotationManager; + if (rm == null) return; + + RotationConfig cfg = rm.getConfig(); + cfg.setRotationMethod(method.getValue()); + cfg.setRotationSpeed(speed.getValue()); + cfg.setRotationStep(step.getValue()); + cfg.setRotationEase(ease.getValue()); + cfg.setRotationThreshold(tolerance.getValue()); + cfg.setHoldTicks(holdTicks.getValue()); + cfg.setJitterMode(jitter.getValue()); + cfg.setRotationNoise(noise.getValue()); + cfg.setRotationWait(wait.getValue()); + cfg.setMoveFixEnabled(moveFix.getValue()); + + cfg.setRotationMode(toLegacyMode(method.getValue())); + } + + private static RotationMode toLegacyMode(RotationMethod method) { + return switch (method) { + case NORMAL -> RotationMode.NORMAL; + case SILENT, PACKET -> RotationMode.SILENT; + default -> RotationMode.MOTION; + }; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AnchorBlocker.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AnchorBlocker.java new file mode 100644 index 0000000..e262bd2 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AnchorBlocker.java @@ -0,0 +1,884 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.RespawnAnchorBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class AnchorBlocker extends Module { + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + public enum Priority { + HighestDamage, + Closest + } + + private static final String ROT_ID = "anchorblocker"; + private static final int ROT_PRIORITY = 3; + + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting priority = mode("Priority", Priority.HighestDamage); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting multitask = bool("MultiTask", false); + public final Setting rotate = bool("Rotate", true); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting anchorRange = num("AnchorRange", 9.0, 1.0, 16.0); + public final Setting placeRange = num("PlaceRange", 5.0f, 0.0f, 8.0f); + public final Setting wallsRange = num("WallsRange", 3.5f, 0.0f, 8.0f); + public final Setting minDamage = num("MinDamage", 6.0, 1.0, 36.0); + public final Setting explosionDamage = num("ExplosionDamage", 4.0, 0.0, 36.0); + public final Setting delay = num("Delay", 0, 0, 20); + public final Setting obsidian = bool("Obsidian", true); + public final Setting enderChest = bool("EnderChest", true); + public final Setting anchors = bool("Anchors", false); + public final Setting netherite = bool("Netherite", false); + public final Setting ancientDebris = bool("AncientDebris", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 80, 160, 45)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 80, 160, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private int ticks = 0; + private int invSwapSlot = -1; + private double lastDamage = 0.0D; + private float lastHealth = -1.0F; + private int damageBypassTicks = 0; + private BlockPos lastPlacedBlock = null; + private BlockPos lastPlacementPlayerPos = null; + private BlockPos lastAnchorPos = null; + + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + public AnchorBlocker() { + super("AnchorBlocker", "Places blast-resistant blocks between you and charged respawn anchors.", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = 0; + invSwapSlot = -1; + lastDamage = 0.0D; + lastHealth = -1.0F; + damageBypassTicks = 0; + lastPlacedBlock = null; + lastPlacementPlayerPos = null; + lastAnchorPos = null; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + ticks = 0; + invSwapSlot = -1; + lastDamage = 0.0D; + lastHealth = -1.0F; + damageBypassTicks = 0; + lastPlacedBlock = null; + lastPlacementPlayerPos = null; + lastAnchorPos = null; + renderPositions.clear(); + renderFadeState.reset(); + clearRotations(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + boolean tookExplosionDamage = updateDamageBypass(player); + + if (tookExplosionDamage) { + ticks = delay.getValue(); + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + renderPositions.clear(); + + boolean allowBlockedRecheck = damageBypassTicks > 0; + AnchorPlan plan = getBestAnchorPlan(player, level, allowBlockedRecheck); + + if (plan == null) { + ticks = 0; + lastDamage = 0.0D; + decrementDamageBypass(); + return; + } + + lastDamage = plan.damage(); + + if (!allowBlockedRecheck && lastPlacedBlockStillUseful(player, level, plan.anchorPos())) { + renderPositions.add(lastPlacedBlock); + ticks = 0; + decrementDamageBypass(); + return; + } + + BlockPos currentPlayerPos = player.blockPosition(); + boolean playerMovedSinceLastPlacement = lastPlacementPlayerPos == null || !lastPlacementPlayerPos.equals(currentPlayerPos); + + if (!playerMovedSinceLastPlacement && !allowBlockedRecheck) { + ticks = 0; + decrementDamageBypass(); + return; + } + + BlockPos pos = plan.blockPos(); + + if (pos == null) { + ticks = 0; + decrementDamageBypass(); + return; + } + + if (cannotPlaceAt(level, player, pos)) { + ticks = 0; + decrementDamageBypass(); + return; + } + + if (!airPlace.getValue() && findPlaceDirection(level, player, pos, strictDirection.getValue()) == null) { + ticks = 0; + decrementDamageBypass(); + return; + } + + renderPositions.add(pos); + + int slot = findBlockSlot(player); + + if (slot == -1) { + ticks = 0; + decrementDamageBypass(); + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + + if (!doSwitch(player, slot, oldSlot)) { + ticks = 0; + decrementDamageBypass(); + return; + } + + if (rotate.getValue()) { + applyRotations(Vec3.atCenterOf(pos)); + } + + if (placeBlock(player, gameMode, pos)) { + lastPlacedBlock = pos.immutable(); + lastPlacementPlayerPos = currentPlayerPos.immutable(); + lastAnchorPos = plan.anchorPos().immutable(); + damageBypassTicks = 0; + } + + switchBack(player, oldSlot); + resetSpoofIfNeeded(); + ticks = 0; + } + + private boolean updateDamageBypass(LocalPlayer player) { + float currentHealth = player.getHealth() + player.getAbsorptionAmount(); + + if (lastHealth < 0.0F) { + lastHealth = currentHealth; + return false; + } + + float lost = lastHealth - currentHealth; + lastHealth = currentHealth; + + if (lost >= explosionDamage.getValue()) { + damageBypassTicks = 2; + return true; + } + + return false; + } + + private void decrementDamageBypass() { + if (damageBypassTicks > 0) { + damageBypassTicks--; + } + } + + private AnchorPlan getBestAnchorPlan(LocalPlayer player, ClientLevel level, boolean allowBlockedRecheck) { + List plans = new ArrayList<>(); + + int range = (int) Math.ceil(anchorRange.getValue()); + double rangeSq = anchorRange.getValue() * anchorRange.getValue(); + BlockPos base = player.blockPosition(); + + for (int x = -range; x <= range; x++) { + for (int y = -range; y <= range; y++) { + for (int z = -range; z <= range; z++) { + BlockPos anchorPos = base.offset(x, y, z); + + if (player.distanceToSqr(Vec3.atCenterOf(anchorPos)) > rangeSq) { + continue; + } + + if (!isDangerousAnchor(level, anchorPos)) { + continue; + } + + double damage = getAnchorDamage(anchorPos, player); + + if (damage < minDamage.getValue()) { + continue; + } + + Vec3 anchorVec = getAnchorVec(anchorPos); + + if (hasBlockingBlockBetween(level, player, anchorVec) && !allowBlockedRecheck) { + continue; + } + + BlockPos blockPos = findBestBlockPosition(player, level, anchorPos); + + if (blockPos == null) { + continue; + } + + plans.add(new AnchorPlan(anchorPos.immutable(), blockPos.immutable(), damage)); + } + } + } + + if (plans.isEmpty()) { + return null; + } + + sortPlans(player, plans); + return plans.get(0); + } + + private boolean isDangerousAnchor(ClientLevel level, BlockPos pos) { + BlockState state = level.getBlockState(pos); + + if (!state.is(Blocks.RESPAWN_ANCHOR)) { + return false; + } + + try { + return state.getValue(RespawnAnchorBlock.CHARGE) > 0; + } catch (Throwable ignored) { + return true; + } + } + + private void sortPlans(LocalPlayer player, List plans) { + switch (priority.getValue()) { + case Closest -> plans.sort(Comparator.comparingDouble(plan -> + player.distanceToSqr(Vec3.atCenterOf(plan.anchorPos())) + )); + + case HighestDamage -> plans.sort((a, b) -> Double.compare(b.damage(), a.damage())); + } + } + + private double getAnchorDamage(BlockPos anchorPos, LocalPlayer player) { + Vec3 explosion = getAnchorVec(anchorPos); + double distance = player.position().distanceTo(explosion); + + if (distance > 10.0D) { + return 0.0D; + } + + double factor = 1.0D - distance / 10.0D; + return Math.max(0.0D, (factor * factor + factor) * 36.0D + 1.0D); + } + + private BlockPos findBestBlockPosition(LocalPlayer player, ClientLevel level, BlockPos anchorPos) { + List candidates = getAnchorBlockCandidates(player, anchorPos); + + BlockPos best = null; + double bestScore = Double.NEGATIVE_INFINITY; + + Vec3 playerEye = player.getEyePosition(); + Vec3 anchorVec = getAnchorVec(anchorPos); + int anchorY = anchorPos.getY(); + + for (BlockPos pos : candidates) { + if (!isRequiredPlacementY(pos, anchorY)) { + continue; + } + + if (!isBetweenHorizontal(anchorVec, playerEye, pos)) { + continue; + } + + if (cannotPlaceAt(level, player, pos)) { + continue; + } + + if (!canReach(player, level, pos)) { + continue; + } + + double score = scoreBlockPosition(playerEye, anchorVec, pos, anchorY); + + if (score > bestScore) { + bestScore = score; + best = pos; + } + } + + return best; + } + + private List getAnchorBlockCandidates(LocalPlayer player, BlockPos anchorPos) { + return getLineBlockCandidates(player, getAnchorVec(anchorPos), anchorPos.getY()); + } + + private List getLineBlockCandidates(LocalPlayer player, Vec3 targetVec, int targetY) { + List candidates = new ArrayList<>(); + + Vec3 playerEye = player.getEyePosition(); + + double dx = playerEye.x - targetVec.x; + double dz = playerEye.z - targetVec.z; + double horizontalDistance = Math.sqrt(dx * dx + dz * dz); + + if (horizontalDistance < 0.25D) { + return candidates; + } + + int samples = Math.max(2, (int) Math.ceil(horizontalDistance * 4.0D)); + + for (int i = 1; i < samples; i++) { + double t = i / (double) samples; + double x = targetVec.x + dx * t; + double z = targetVec.z + dz * t; + + addCandidate(candidates, new BlockPos((int) Math.floor(x), targetY, (int) Math.floor(z))); + addCandidate(candidates, new BlockPos((int) Math.floor(x), targetY - 1, (int) Math.floor(z))); + } + + return candidates; + } + + private void addCandidate(List candidates, BlockPos pos) { + if (!candidates.contains(pos)) { + candidates.add(pos); + } + } + + private boolean isRequiredPlacementY(BlockPos pos, int targetY) { + return pos.getY() == targetY || pos.getY() == targetY - 1; + } + + private boolean isBetweenHorizontal(Vec3 targetVec, Vec3 playerVec, BlockPos pos) { + Vec3 center = Vec3.atCenterOf(pos); + + double lineX = playerVec.x - targetVec.x; + double lineZ = playerVec.z - targetVec.z; + double lengthSq = lineX * lineX + lineZ * lineZ; + + if (lengthSq <= 0.0001D) { + return false; + } + + double pointX = center.x - targetVec.x; + double pointZ = center.z - targetVec.z; + double t = (pointX * lineX + pointZ * lineZ) / lengthSq; + + if (t <= 0.05D || t >= 0.95D) { + return false; + } + + return horizontalDistanceToSegment(center, targetVec, playerVec) <= 1.25D; + } + + private boolean hasBlockingBlockBetween(ClientLevel level, LocalPlayer player, Vec3 targetVec) { + Vec3 playerEye = player.getEyePosition(); + Vec3 delta = playerEye.subtract(targetVec); + + if (delta.lengthSqr() <= 0.0001D) { + return false; + } + + Vec3 start = targetVec.add(delta.normalize().scale(0.75D)); + + HitResult result = level.clip(new ClipContext( + start, + playerEye, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.BLOCK; + } + + private boolean lastPlacedBlockStillUseful(LocalPlayer player, ClientLevel level, BlockPos anchorPos) { + if (lastPlacedBlock == null || lastAnchorPos == null) { + return false; + } + + if (!lastAnchorPos.equals(anchorPos)) { + return false; + } + + BlockState state = level.getBlockState(lastPlacedBlock); + + if (state.isAir() || state.canBeReplaced()) { + return false; + } + + int anchorY = anchorPos.getY(); + + if (!isRequiredPlacementY(lastPlacedBlock, anchorY)) { + return false; + } + + Vec3 anchorVec = getAnchorVec(anchorPos); + Vec3 playerEye = player.getEyePosition(); + Vec3 blockCenter = Vec3.atCenterOf(lastPlacedBlock); + + return isBetweenHorizontal(anchorVec, playerEye, lastPlacedBlock) + && horizontalDistanceToSegment(blockCenter, anchorVec, playerEye) <= 0.95D; + } + + private double scoreBlockPosition(Vec3 playerEye, Vec3 targetVec, BlockPos pos, int targetY) { + Vec3 center = Vec3.atCenterOf(pos); + + double distToLine = horizontalDistanceToSegment(center, targetVec, playerEye); + double distToTarget = horizontalDistance(center, targetVec); + double distToPlayer = horizontalDistance(center, playerEye); + double yPenalty = pos.getY() == targetY ? 0.0D : 0.5D; + + return -distToLine * 10.0D + - distToTarget * 1.0D + - distToPlayer * 0.15D + - yPenalty; + } + + private double horizontalDistance(Vec3 a, Vec3 b) { + double dx = a.x - b.x; + double dz = a.z - b.z; + return Math.sqrt(dx * dx + dz * dz); + } + + private double horizontalDistanceToSegment(Vec3 point, Vec3 start, Vec3 end) { + double lineX = end.x - start.x; + double lineZ = end.z - start.z; + double lengthSq = lineX * lineX + lineZ * lineZ; + + if (lengthSq <= 0.0001D) { + return horizontalDistance(point, start); + } + + double pointX = point.x - start.x; + double pointZ = point.z - start.z; + double t = (pointX * lineX + pointZ * lineZ) / lengthSq; + + t = Math.max(0.0D, Math.min(1.0D, t)); + + double closestX = start.x + lineX * t; + double closestZ = start.z + lineZ * t; + + double dx = point.x - closestX; + double dz = point.z - closestZ; + + return Math.sqrt(dx * dx + dz * dz); + } + + private boolean canReach(LocalPlayer player, ClientLevel level, BlockPos pos) { + Vec3 eye = player.getEyePosition(); + Vec3 center = Vec3.atCenterOf(pos); + double distance = eye.distanceTo(center); + + if (distance <= placeRange.getValue() && hasLineOfSight(player, level, eye, center)) { + return true; + } + + return distance <= wallsRange.getValue(); + } + + private boolean hasLineOfSight(LocalPlayer player, ClientLevel level, Vec3 from, Vec3 to) { + HitResult result = level.clip(new ClipContext( + from, + to, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.MISS; + } + + private boolean placeBlock(LocalPlayer player, MultiPlayerGameMode gameMode, BlockPos pos) { + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Direction directionToNeighbor = findPlaceDirection(level, player, pos, strictDirection.getValue()); + + if (directionToNeighbor == null) { + return null; + } + + BlockPos neighbor = pos.relative(directionToNeighbor); + Direction hitSide = directionToNeighbor.getOpposite(); + + Vec3 hitVec = Vec3.atCenterOf(neighbor).add( + hitSide.getStepX() * 0.5D, + hitSide.getStepY() * 0.5D, + hitSide.getStepZ() * 0.5D + ); + + return new BlockHitResult(hitVec, hitSide, neighbor, false); + } + + private Direction findPlaceDirection(ClientLevel level, LocalPlayer player, BlockPos pos, boolean strictDir) { + Direction bestDirection = null; + double bestDistance = Double.MAX_VALUE; + Vec3 eye = player.getEyePosition(); + + for (Direction direction : Direction.values()) { + BlockPos neighbor = pos.relative(direction); + BlockState neighborState = level.getBlockState(neighbor); + + if (neighborState.isAir() || neighborState.canBeReplaced()) { + continue; + } + + if (neighborState.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction hitSide = direction.getOpposite(); + + Vec3 faceCenter = Vec3.atCenterOf(neighbor).add( + hitSide.getStepX() * 0.5D, + hitSide.getStepY() * 0.5D, + hitSide.getStepZ() * 0.5D + ); + + if (strictDir) { + Vec3 toEye = eye.subtract(faceCenter).normalize(); + + Vec3 faceNormal = new Vec3( + hitSide.getStepX(), + hitSide.getStepY(), + hitSide.getStepZ() + ).normalize(); + + if (toEye.dot(faceNormal) <= 0.0D) { + continue; + } + } + + double distance = eye.distanceTo(faceCenter); + + if (distance < bestDistance) { + bestDistance = distance; + bestDirection = direction; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + return bestDirection; + } + + private boolean cannotPlaceAt(ClientLevel level, LocalPlayer player, BlockPos pos) { + if (level.isOutsideBuildHeight(pos)) { + return true; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return true; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return true; + } + + if (player.getBoundingBox().intersects(box)) { + return true; + } + + return !airPlace.getValue() && buildHitResult(pos) == null; + } + + private int findBlockSlot(LocalPlayer player) { + int selected = player.getInventory().getSelectedSlot(); + + if (isValidBlock(player.getInventory().getItem(selected))) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (isValidBlock(player.getInventory().getItem(i))) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (isValidBlock(player.getInventory().getItem(i))) { + return i; + } + } + + return -1; + } + + private boolean isValidBlock(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return false; + } + + if (!(stack.getItem() instanceof BlockItem blockItem)) { + return false; + } + + return isResistant(blockItem.getBlock()); + } + + private boolean isResistant(Block block) { + if (obsidian.getValue() && (block == Blocks.OBSIDIAN || block == Blocks.CRYING_OBSIDIAN)) { + return true; + } + + if (enderChest.getValue() && block == Blocks.ENDER_CHEST) { + return true; + } + + if (anchors.getValue() && block == Blocks.RESPAWN_ANCHOR) { + return true; + } + + if (netherite.getValue() && block == Blocks.NETHERITE_BLOCK) { + return true; + } + + return ancientDebris.getValue() && block == Blocks.ANCIENT_DEBRIS; + } + + private boolean doSwitch(LocalPlayer player, int slot, int currentHotbarSlot) { + if (mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(LocalPlayer player, int oldSlot) { + boolean shouldRestoreSlot = switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1; + + if (shouldRestoreSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot == -1) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + + private Vec3 getAnchorVec(BlockPos anchorPos) { + return Vec3.atCenterOf(anchorPos); + } + + private void applyRotations(Vec3 vec) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + @Override + public void onRender3D(Render3DEvent event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (!render.getValue() || player == null || level == null) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + @Override + public String getDisplayInfo() { + if (lastDamage <= 0.0D) { + return String.valueOf(renderPositions.size()); + } + + return String.format("%.1f", lastDamage); + } + + private record AnchorPlan(BlockPos anchorPos, BlockPos blockPos, double damage) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Anti32k.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Anti32k.java new file mode 100644 index 0000000..649a974 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Anti32k.java @@ -0,0 +1,130 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Anti32k extends Module { + + public final Setting mainhandTotems = bool("MainhandTotems", true); + public final Setting survivalRange = num("Range", 13.0, 6.0, 20.0); + public final Setting log = bool("Log", true); + public final Setting sharpnessThreshold = num("Sharpness", 100, 5, 32767); + + public final Set visitedPositions = new HashSet<>(); + + private Player opponent; + + public Anti32k() { + super("Anti32k", "Mainhands a totem or logs when someone nearby has a 32k", Category.COMBAT); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return; + + doSurvival(player, level); + } + + private void doSurvival(LocalPlayer player, ClientLevel level) { + if (isSafe(player, level)) return; + + int totemSlot = findHotbarTotem(player); + boolean hasOffhandTotem = player.getOffhandItem().is(Items.TOTEM_OF_UNDYING); + + if (totemSlot == -1 && !hasOffhandTotem && log.getValue()) { + String opponentName = opponent == null ? "Someone" : opponent.getName().getString(); + float hp = player.getHealth() + player.getAbsorptionAmount(); + + player.connection.getConnection().disconnect(Component.literal( + "[Anti32k]\n" + opponentName + " tried to 32k you!\nLogged with " + String.format("%.1f", hp) + " health remaining!" + )); + return; + } + + if (totemSlot == -1) return; + + if (mainhandTotems.getValue()) { + switchSlot(player, totemSlot); + } + } + + private boolean isSafe(LocalPlayer self, ClientLevel level) { + if (is32k(self.getMainHandItem())) { + opponent = null; + return true; + } + + for (Player player : level.players()) { + if (player == self) continue; + if (!player.isAlive()) continue; + if (nolongerhuman.friendManager.isFriend(player)) continue; + if (self.distanceTo(player) > survivalRange.getValue()) continue; + if (!is32k(player.getMainHandItem())) continue; + + opponent = player; + return false; + } + + opponent = null; + return true; + } + + public boolean is32k(ItemStack stack) { + if (stack == null || stack.isEmpty()) return false; + + String raw = stack.getEnchantments().toString().toLowerCase(Locale.ROOT); + if (!raw.contains("sharpness")) return false; + + int highest = 0; + Matcher matcher = Pattern.compile("\\d+").matcher(raw); + while (matcher.find()) { + try { + highest = Math.max(highest, Integer.parseInt(matcher.group())); + } catch (NumberFormatException ignored) { + } + } + + return highest >= sharpnessThreshold.getValue(); + } + + private int findHotbarTotem(LocalPlayer player) { + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(Items.TOTEM_OF_UNDYING)) { + return i; + } + } + + return -1; + } + + private void switchSlot(LocalPlayer player, int slot) { + if (slot < 0 || slot > 8) return; + + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + @Override + public String getDisplayInfo() { + return opponent == null ? "Safe" : opponent.getName().getString(); + } + + public record BlockPosCompat(int x, int y, int z) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiChainPop.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiChainPop.java new file mode 100644 index 0000000..ed7a3de --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiChainPop.java @@ -0,0 +1,187 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.TickShiftUtil; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +public class AntiChainPop extends Module { + private final Setting maxTicks = num("Ticks", 15, 1, 50); + private final Setting ticksPerTick = num("TicksPerTick", 3, 1, 10); + private final Setting chargeSpeed = num("ChargeSpeed", 0.25, 0.01, 2.0); + private final Setting chargeAmount = num("ChargeAmount", 5, 1, 20); + private final Setting maxFallDistance = num("MaxFallDistance", 5.0, 0.0, 20.0); + private final Setting requireMovement = bool("RequireMovement", true); + private final Setting autoDisable = bool("AutoDisable", false); + + private int ticksLeft; + private int lastTotemCount; + private float chargeProgress; + private boolean active; + private boolean shifting; + + public AntiChainPop() { + super("AntiChainPop", "Tickshifts after popping a totem to prevent chain pops", Category.COMBAT); + } + + @Override + public void onEnable() { + LocalPlayer player = mc.player; + + ticksLeft = maxTicks.getValue(); + lastTotemCount = player == null ? 0 : countTotems(player); + chargeProgress = 0.0F; + active = false; + shifting = false; + } + + @Override + public void onDisable() { + ticksLeft = 0; + chargeProgress = 0.0F; + active = false; + shifting = false; + } + + @Override + public void onTick() { + if (TickShiftUtil.isTickShifting()) { + return; + } + + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + active = false; + shifting = false; + return; + } + + updatePopState(player); + + if (shouldPause(player)) { + active = false; + shifting = false; + recharge(); + return; + } + + if (!active) { + shifting = false; + recharge(); + return; + } + + if (requireMovement.getValue() && !isPlayerMoving()) { + shifting = false; + recharge(); + return; + } + + if (ticksLeft <= 0) { + finishShift(); + return; + } + + int shiftedTicks = tickShift(player); + + shifting = shiftedTicks > 0; + + if (shifting) { + ticksLeft -= shiftedTicks; + chargeProgress = 0.0F; + } + + if (ticksLeft <= 0) { + finishShift(); + } + } + + private void updatePopState(LocalPlayer player) { + int currentTotemCount = countTotems(player); + boolean totemCountDropped = currentTotemCount < lastTotemCount; + boolean likelyPop = totemCountDropped && player.getHealth() > 0.0F; + + lastTotemCount = currentTotemCount; + + if (!likelyPop) { + return; + } + + active = ticksLeft > 0; + } + + private int countTotems(LocalPlayer player) { + int count = 0; + + for (int slot = 0; slot < player.getInventory().getContainerSize(); slot++) { + ItemStack stack = player.getInventory().getItem(slot); + + if (stack.is(Items.TOTEM_OF_UNDYING)) { + count += stack.getCount(); + } + } + + return count; + } + + private int tickShift(LocalPlayer player) { + int ticks = Math.min(ticksLeft, ticksPerTick.getValue()); + return TickShiftUtil.runExtraTicks(player, ticks); + } + + private void finishShift() { + active = false; + shifting = false; + + if (autoDisable.getValue()) { + disable(); + } + } + + private boolean shouldPause(LocalPlayer player) { + return player.isSpectator() + || player.isInWater() + || player.isInLava() + || player.fallDistance >= maxFallDistance.getValue().floatValue(); + } + + private void recharge() { + int max = maxTicks.getValue(); + + if (ticksLeft >= max) { + ticksLeft = max; + chargeProgress = 0.0F; + return; + } + + chargeProgress += chargeSpeed.getValue().floatValue(); + + while (chargeProgress >= 1.0F) { + chargeProgress -= 1.0F; + ticksLeft = Math.min(ticksLeft + chargeAmount.getValue(), max); + } + } + + private boolean isPlayerMoving() { + return mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown() + || mc.options.keyJump.isDown(); + } + + public String getInfo() { + if (active && shifting) { + return ticksLeft + " shifting"; + } + + if (active) { + return ticksLeft + " ready"; + } + + return String.valueOf(ticksLeft); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiMace.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiMace.java new file mode 100644 index 0000000..a94c73b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiMace.java @@ -0,0 +1,512 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.TickShiftUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +public class AntiMace extends Module { + private enum Mode { + Move, + TickShift + } + + private enum ThreatType { + Normal, + Elytra, + WindCharge + } + + private final Setting mode = mode("Mode", Mode.TickShift); + + private final Setting preTicks = num("PreTicks", 3, 1, 10); + private final Setting maxTicks = num("Ticks", 8, 1, 50); + private final Setting ticksPerTick = num("TicksPerTick", 3, 1, 10); + + private final Setting moveSpeed = num("MoveSpeed", 1.2, 0.1, 5.0); + private final Setting detectRange = num("DetectRange", 8.0, 3.0, 16.0); + private final Setting attackRange = num("AttackRange", 3.25, 2.5, 6.0); + private final Setting minFallDistance = num("MinFallDistance", 1.5, 0.0, 8.0); + + private final Setting verticalDodge = bool("VerticalDodge", true); + private final Setting autoDisable = bool("AutoDisable", false); + + private int ticksLeft; + private boolean active; + private boolean shifting; + + private ThreatType currentThreatType; + private Player currentThreat; + + public AntiMace() { + super("AntiMace", "Moves or tickshifts away from imminent mace attacks", Category.COMBAT); + } + + @Override + public void onEnable() { + ticksLeft = maxTicks.getValue(); + active = false; + shifting = false; + currentThreatType = ThreatType.Normal; + currentThreat = null; + } + + @Override + public void onDisable() { + ticksLeft = 0; + active = false; + shifting = false; + currentThreat = null; + } + + @Override + public void onTick() { + + if (mode.getValue() == Mode.TickShift && TickShiftUtil.isTickShifting()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + resetState(); + return; + } + + MaceThreat threat = findThreat(player, level); + + if (threat == null) { + active = false; + shifting = false; + currentThreat = null; + ticksLeft = Math.min(ticksLeft + 1, maxTicks.getValue()); + return; + } + + currentThreat = threat.attacker(); + currentThreatType = threat.type(); + active = true; + + switch (mode.getValue()) { + case Move -> moveAway(player, level, threat.attacker()); + case TickShift -> handleTickShift(player, level, threat.attacker()); + } + } + + private void handleTickShift(LocalPlayer player, ClientLevel level, Player attacker) { + if (ticksLeft <= 0) { + finishShift(); + return; + } + + int shiftedTicks = tickShiftAway(player, level, attacker); + + shifting = shiftedTicks > 0; + + if (shifting) { + ticksLeft -= shiftedTicks; + } + + if (ticksLeft <= 0) { + finishShift(); + } + } + + private void moveAway(LocalPlayer player, ClientLevel level, Player attacker) { + Vec3 dodge = getBestDodgeMovement(player, level, attacker); + + shifting = false; + ticksLeft = maxTicks.getValue(); + + if (dodge.lengthSqr() <= 0.0D) { + return; + } + + applyDodge(player, dodge); + } + + private int tickShiftAway(LocalPlayer player, ClientLevel level, Player attacker) { + int ticks = Math.min(ticksLeft, ticksPerTick.getValue()); + int shifted = 0; + + for (int i = 0; i < ticks; i++) { + Vec3 dodge = getBestDodgeMovement(player, level, attacker); + + if (dodge.lengthSqr() <= 0.0D) { + break; + } + + applyDodge(player, dodge); + + int ranTicks = TickShiftUtil.runExtraTick(player); + + if (ranTicks <= 0) { + break; + } + + shifted += ranTicks; + } + + return shifted; + } + + private MaceThreat findThreat(LocalPlayer player, ClientLevel level) { + MaceThreat bestThreat = null; + double bestDistance = Double.MAX_VALUE; + + for (Player attacker : level.players()) { + if (!isValidAttacker(player, attacker)) { + continue; + } + + MaceThreat threat = getThreat(player, attacker); + + if (threat == null) { + continue; + } + + double distance = player.distanceToSqr(attacker); + + if (distance < bestDistance) { + bestDistance = distance; + bestThreat = threat; + } + } + + return bestThreat; + } + + private boolean isValidAttacker(LocalPlayer player, Player attacker) { + if (attacker == player) { + return false; + } + + if (attacker.isDeadOrDying() || attacker.isSpectator() || attacker.isCreative()) { + return false; + } + + if (!isHoldingMace(attacker)) { + return false; + } + + return player.distanceTo(attacker) <= detectRange.getValue(); + } + + private boolean isHoldingMace(Player player) { + return isMace(player.getMainHandItem()) || isMace(player.getOffhandItem()); + } + + private boolean isMace(ItemStack stack) { + return stack.is(Items.MACE); + } + + private MaceThreat getThreat(LocalPlayer player, Player attacker) { + ThreatType type = detectThreatType(player, attacker); + + if (type == null) { + return null; + } + + int ticksUntilHit = getTicksUntilHit(player, attacker, type); + + if (ticksUntilHit < 0 || ticksUntilHit > preTicks.getValue()) { + return null; + } + + return new MaceThreat(attacker, type, ticksUntilHit); + } + + private ThreatType detectThreatType(LocalPlayer player, Player attacker) { + Vec3 attackerVelocity = attacker.getDeltaMovement(); + + boolean descending = attackerVelocity.y < -0.08D + || attacker.fallDistance >= minFallDistance.getValue().floatValue(); + + boolean abovePlayer = attacker.getY() > player.getY() + 0.75D; + + boolean closeHorizontally = horizontalDistance(player.position(), attacker.position()) + <= attackRange.getValue() + 1.0D; + + boolean closing = isClosingDistance(player, attacker); + + if (attacker.isFallFlying() && closing && closeHorizontally) { + return ThreatType.Elytra; + } + + if (isLikelyWindChargeMace(player, attacker, descending, abovePlayer, closing)) { + return ThreatType.WindCharge; + } + + if (descending && abovePlayer && closing && closeHorizontally) { + return ThreatType.Normal; + } + + return null; + } + + private boolean isLikelyWindChargeMace( + LocalPlayer player, + Player attacker, + boolean descending, + boolean abovePlayer, + boolean closing + ) { + Vec3 velocity = attacker.getDeltaMovement(); + + double horizontalSpeed = horizontalSpeed(velocity); + double verticalDifference = attacker.getY() - player.getY(); + + boolean launchedUpOrFallingFast = attacker.fallDistance >= minFallDistance.getValue().floatValue() + || velocity.y < -0.25D + || verticalDifference > 2.0D; + + boolean windChargeStyleMovement = horizontalSpeed > 0.35D + || Math.abs(velocity.y) > 0.35D + || attacker.hurtMarked; + + return launchedUpOrFallingFast + && windChargeStyleMovement + && descending + && abovePlayer + && closing; + } + + private int getTicksUntilHit(LocalPlayer player, Player attacker, ThreatType type) { + Vec3 playerPos = player.position(); + Vec3 attackerPos = attacker.position(); + + Vec3 playerVelocity = player.getDeltaMovement(); + Vec3 attackerVelocity = attacker.getDeltaMovement(); + + int maxPredictionTicks = Math.max(preTicks.getValue(), 1); + + for (int tick = 0; tick <= maxPredictionTicks; tick++) { + double predictedRange = getPredictedAttackRange(type, tick); + + double distance = playerPos.distanceTo(attackerPos); + double horizontal = horizontalDistance(playerPos, attackerPos); + + boolean heightValid = attackerPos.y >= playerPos.y - 0.5D; + + if (distance <= predictedRange && horizontal <= predictedRange && heightValid) { + return tick; + } + + playerPos = playerPos.add(playerVelocity); + attackerPos = attackerPos.add(attackerVelocity); + + playerVelocity = dampPlayerVelocity(playerVelocity); + attackerVelocity = dampAttackerVelocity(attackerVelocity, type); + } + + return -1; + } + + private double getPredictedAttackRange(ThreatType type, int tick) { + double baseRange = attackRange.getValue(); + + return switch (type) { + case Elytra -> baseRange + 0.55D + (tick * 0.08D); + case WindCharge -> baseRange + 0.35D + (tick * 0.06D); + case Normal -> baseRange + 0.15D; + }; + } + + private Vec3 dampPlayerVelocity(Vec3 velocity) { + return new Vec3( + velocity.x * 0.91D, + velocity.y * 0.98D, + velocity.z * 0.91D + ); + } + + private Vec3 dampAttackerVelocity(Vec3 velocity, ThreatType type) { + double horizontalDrag = type == ThreatType.Elytra ? 0.99D : 0.91D; + double y = velocity.y - 0.08D; + + return new Vec3( + velocity.x * horizontalDrag, + y * 0.98D, + velocity.z * horizontalDrag + ); + } + + private boolean isClosingDistance(LocalPlayer player, Player attacker) { + Vec3 playerToAttacker = attacker.position().subtract(player.position()); + Vec3 relativeVelocity = attacker.getDeltaMovement().subtract(player.getDeltaMovement()); + + return playerToAttacker.dot(relativeVelocity) < 0.0D; + } + + private Vec3 getBestDodgeMovement(LocalPlayer player, ClientLevel level, Player attacker) { + Vec3 away = player.position().subtract(attacker.position()); + Vec3 flatAway = new Vec3(away.x, 0.0D, away.z); + + if (flatAway.lengthSqr() < 0.0001D) { + flatAway = getFallbackAway(player); + } + + flatAway = flatAway.normalize(); + + Vec3[] candidates = getDodgeCandidates(flatAway); + + Vec3 best = Vec3.ZERO; + double bestScore = -1.0D; + + for (Vec3 candidate : candidates) { + Vec3 movement = candidate.scale(moveSpeed.getValue()); + + if (verticalDodge.getValue() && canMove(player, level, movement.add(0.0D, 0.42D, 0.0D))) { + movement = movement.add(0.0D, 0.42D, 0.0D); + } + + if (!canMove(player, level, movement)) { + continue; + } + + double score = scoreDodge(player, attacker, movement); + + if (score > bestScore) { + bestScore = score; + best = movement; + } + } + + return best; + } + + private Vec3 getFallbackAway(LocalPlayer player) { + double yaw = Math.toRadians(player.getYRot() + 180.0F); + + return new Vec3( + -Math.sin(yaw), + 0.0D, + Math.cos(yaw) + ); + } + + private Vec3[] getDodgeCandidates(Vec3 away) { + Vec3 left = rotateY(away, 45.0D); + Vec3 right = rotateY(away, -45.0D); + Vec3 hardLeft = rotateY(away, 90.0D); + Vec3 hardRight = rotateY(away, -90.0D); + Vec3 backLeft = rotateY(away, 135.0D); + Vec3 backRight = rotateY(away, -135.0D); + + return new Vec3[]{ + away, + left, + right, + hardLeft, + hardRight, + backLeft, + backRight + }; + } + + private Vec3 rotateY(Vec3 vector, double degrees) { + double radians = Math.toRadians(degrees); + double cos = Math.cos(radians); + double sin = Math.sin(radians); + + return new Vec3( + (vector.x * cos) - (vector.z * sin), + 0.0D, + (vector.x * sin) + (vector.z * cos) + ).normalize(); + } + + private boolean canMove(LocalPlayer player, ClientLevel level, Vec3 movement) { + AABB movedBox = player.getBoundingBox().move(movement); + + return level.noCollision(player, movedBox); + } + + private double scoreDodge(LocalPlayer player, Player attacker, Vec3 movement) { + Vec3 predictedPlayerPos = player.position().add(movement); + Vec3 predictedAttackerPos = attacker.position().add(attacker.getDeltaMovement()); + + double distanceScore = predictedPlayerPos.distanceToSqr(predictedAttackerPos); + + Vec3 away = player.position().subtract(attacker.position()); + + if (away.lengthSqr() <= 0.0001D || movement.lengthSqr() <= 0.0001D) { + return distanceScore; + } + + double awayScore = movement.normalize().dot(away.normalize()); + + return distanceScore + awayScore; + } + + private void applyDodge(LocalPlayer player, Vec3 dodge) { + Vec3 current = player.getDeltaMovement(); + + double y = dodge.y; + + if (!verticalDodge.getValue()) { + y = current.y; + } + + player.setDeltaMovement( + dodge.x, + y, + dodge.z + ); + } + + private void finishShift() { + active = false; + shifting = false; + currentThreat = null; + + if (autoDisable.getValue()) { + disable(); + } + } + + private void resetState() { + active = false; + shifting = false; + currentThreat = null; + } + + private double horizontalDistance(Vec3 first, Vec3 second) { + double x = first.x - second.x; + double z = first.z - second.z; + + return Math.sqrt((x * x) + (z * z)); + } + + private double horizontalSpeed(Vec3 velocity) { + return Math.sqrt((velocity.x * velocity.x) + (velocity.z * velocity.z)); + } + + public String getInfo() { + if (!active || currentThreat == null) { + return mode.getValue() == Mode.TickShift + ? String.valueOf(ticksLeft) + : mode.getValue().name(); + } + + if (mode.getValue() == Mode.Move) { + return currentThreatType.name() + " Move"; + } + + if (shifting) { + return currentThreatType.name() + " " + ticksLeft; + } + + return currentThreat.getName().getString(); + } + + private record MaceThreat(Player attacker, ThreatType type, int ticksUntilHit) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiPop.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiPop.java new file mode 100644 index 0000000..297e4fe --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiPop.java @@ -0,0 +1,148 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.TickShiftUtil; +import net.minecraft.client.player.LocalPlayer; + +public class AntiPop extends Module { + private final Setting health = num("Health", 10.0, 0.5, 36.0); + private final Setting includeAbsorption = bool("Absorption", true); + private final Setting maxTicks = num("Ticks", 15, 1, 50); + private final Setting ticksPerTick = num("TicksPerTick", 3, 1, 10); + private final Setting chargeSpeed = num("ChargeSpeed", 0.25, 0.01, 2.0); + private final Setting chargeAmount = num("ChargeAmount", 5, 1, 20); + private final Setting maxFallDistance = num("MaxFallDistance", 5.0, 0.0, 20.0); + private final Setting requireMovement = bool("RequireMovement", true); + private final Setting autoDisable = bool("AutoDisable", false); + + private int ticksLeft; + private float chargeProgress; + private boolean shifting; + + public AntiPop() { + super("AntiPop", "Tickshifts when your health is low", Category.COMBAT); + } + + @Override + public void onEnable() { + ticksLeft = maxTicks.getValue(); + chargeProgress = 0.0F; + shifting = false; + } + + @Override + public void onDisable() { + ticksLeft = 0; + chargeProgress = 0.0F; + shifting = false; + } + + @Override + public void onTick() { + if (TickShiftUtil.isTickShifting()) { + return; + } + + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + shifting = false; + return; + } + + if (shouldPause(player)) { + shifting = false; + recharge(); + return; + } + + if (getHealth(player) > health.getValue().floatValue()) { + shifting = false; + recharge(); + return; + } + + if (requireMovement.getValue() && !isPlayerMoving()) { + shifting = false; + recharge(); + return; + } + + if (ticksLeft <= 0) { + shifting = false; + + if (autoDisable.getValue()) { + disable(); + } + + return; + } + + int shiftedTicks = tickShift(player); + + shifting = shiftedTicks > 0; + + if (shifting) { + ticksLeft -= shiftedTicks; + chargeProgress = 0.0F; + } + + if (ticksLeft <= 0 && autoDisable.getValue()) { + disable(); + } + } + + private float getHealth(LocalPlayer player) { + if (includeAbsorption.getValue()) { + return player.getHealth() + player.getAbsorptionAmount(); + } + + return player.getHealth(); + } + + private int tickShift(LocalPlayer player) { + int ticks = Math.min(ticksLeft, ticksPerTick.getValue()); + return TickShiftUtil.runExtraTicks(player, ticks); + } + + private boolean shouldPause(LocalPlayer player) { + return player.isSpectator() + || player.isInWater() + || player.isInLava() + || player.fallDistance >= maxFallDistance.getValue().floatValue(); + } + + private void recharge() { + int max = maxTicks.getValue(); + + if (ticksLeft >= max) { + ticksLeft = max; + chargeProgress = 0.0F; + return; + } + + chargeProgress += chargeSpeed.getValue().floatValue(); + + while (chargeProgress >= 1.0F) { + chargeProgress -= 1.0F; + ticksLeft = Math.min(ticksLeft + chargeAmount.getValue(), max); + } + } + + private boolean isPlayerMoving() { + return mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown() + || mc.options.keyJump.isDown(); + } + + public String getInfo() { + if (shifting) { + return ticksLeft + " shifting"; + } + + return String.valueOf(ticksLeft); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiShulker.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiShulker.java new file mode 100644 index 0000000..3f2508e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AntiShulker.java @@ -0,0 +1,1041 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.render.CrystalCircles; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class AntiShulker extends Module { + public enum PlacementMode { + Native, + NCP + } + + public enum SwitchMode { + None, + Normal, + Silent, + AltSwap + } + + public enum SwingMode { + Default, + None, + Packet, + Mainhand, + Offhand, + Both + } + + public enum BreakMode { + Vanilla, + Packet + } + + public enum Priority { + Shulkers, + Items, + Closest, + HighestDamage + } + + public enum RenderMode { + None, + Fill, + Outline, + Both + } + + private enum TargetType { + Shulker, + Item + } + + private static final String ROT_ID = "antishulker"; + private static final int ROT_PRIORITY = 4; + + public final Setting place = bool("Place", true); + public final Setting placeSpeed = num("PlaceSpeed", 40f, 0.1f, 40f); + public final Setting placeDelay = num("PlaceDelay", 0, 0, 500); + public final Setting placeRange = num("PlaceRange", 5.0, 0.0, 6.0); + public final Setting placeWallsRange = num("PlaceWallsRange", 3.5, 0.0, 6.0); + public final Setting placeRadius = num("PlaceRadius", 4.0, 1.0, 8.0); + + public final Setting attack = bool("Attack", true); + public final Setting breakSpeed = num("BreakSpeed", 20f, 0.1f, 40f); + public final Setting attackDelay = num("AttackDelay", 0, 0, 500); + public final Setting attackRange = num("AttackRange", 4.5, 0.0, 8.0); + public final Setting attackWallsRange = num("AttackWallsRange", 4.5, 0.0, 8.0); + public final Setting breakMode = mode("BreakMode", BreakMode.Vanilla); + public final Setting maxBreaksPerTick = num("MaxBreaks", 2, 1, 10); + public final Setting ticksExisted = num("TicksExisted", 0, 0, 20); + + public final Setting targetRange = num("TargetRange", 14.0, 1.0, 24.0); + public final Setting itemTargetRange = num("ItemRange", 8.0, 1.0, 12.0); + public final Setting trackTime = num("TrackTime", 3000, 250, 15000); + public final Setting minItemAge = num("MinItemAge", 0, 0, 100); + public final Setting minimumDamage = num("MinimumDamage", 4.0, 0.0, 36.0); + public final Setting maximumSelfDamage = num("MaximumSelfDamage", 10.0, 0.0, 36.0); + public final Setting antiSuicide = bool("AntiSuicide", true); + public final Setting selfDamageBuffer = num("SelfDamageBuffer", 2.0, 0.0, 10.0); + + public final Setting priority = mode("Priority", Priority.Shulkers); + public final Setting placementsMode = mode("PlacementsMode", PlacementMode.Native); + public final Setting autoSwitch = mode("Switch", SwitchMode.Silent); + public final Setting swing = mode("Swing", SwingMode.Default); + public final Setting multitask = bool("MultiTask", false); + public final Setting rotate = bool("Rotate", true); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting raytrace = bool("Raytrace", false); + public final Setting oldVersion = bool("1.12", false); + public final Setting worldBorder = bool("WorldBorder", true); + + public final Setting renderMode = mode("RenderMode", RenderMode.Both); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting renderLineWidth = num("RenderLineWidth", 1.0f, 0.1f, 5.0f); + + private final Timer placeTimer = new Timer(); + private final Timer attackTimer = new Timer(); + + private final Map trackedShulkers = new HashMap<>(); + private final List renderPositions = new ArrayList<>(); + + private int invSwapSlot = -1; + private double lastDamage = 0.0; + private TargetType lastTargetType = TargetType.Shulker; + + public AntiShulker() { + super("AntiShulker", "antiregear for shulkers and their items EZ", Category.COMBAT); + } + + @Override + public void onEnable() { + invSwapSlot = -1; + lastDamage = 0.0; + lastTargetType = TargetType.Shulker; + trackedShulkers.clear(); + renderPositions.clear(); + placeTimer.reset(); + attackTimer.reset(); + } + + @Override + public void onDisable() { + clearRotations(); + invSwapSlot = -1; + lastDamage = 0.0; + lastTargetType = TargetType.Shulker; + trackedShulkers.clear(); + renderPositions.clear(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + renderPositions.clear(); + + updateTrackedShulkers(player, level); + expireTrackedShulkers(); + + List targets = getTargets(player, level); + + if (targets.isEmpty()) { + lastDamage = 0.0; + clearRotations(); + return; + } + + sortTargets(player, targets); + + int attackEvery = Math.max(1, Math.round(20f / breakSpeed.getValue())); + long attackMs = Math.max(attackDelay.getValue(), attackEvery * 50L); + + if (attack.getValue() && attackTimer.passedMs(attackMs)) { + int broken = breakCrystals(player, level, targets); + + if (broken > 0) { + attackTimer.reset(); + } + } + + int placeEvery = Math.max(1, Math.round(20f / placeSpeed.getValue())); + long placeMs = Math.max(placeDelay.getValue(), placeEvery * 50L); + + if (place.getValue() && placeTimer.passedMs(placeMs)) { + PlacePlan plan = findBestPlacement(player, level, targets); + + if (plan != null) { + renderPositions.add(plan.basePos()); + doPlace(player, plan); + placeTimer.reset(); + } + } + } + + private void updateTrackedShulkers(LocalPlayer player, ClientLevel level) { + int range = (int) Math.ceil(targetRange.getValue()); + double rangeSq = targetRange.getValue() * targetRange.getValue(); + long now = System.currentTimeMillis(); + + BlockPos base = player.blockPosition(); + + for (int x = -range; x <= range; x++) { + for (int y = -range; y <= range; y++) { + for (int z = -range; z <= range; z++) { + BlockPos pos = base.offset(x, y, z); + + if (player.distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + continue; + } + + if (isShulkerBoxBlock(level.getBlockState(pos).getBlock())) { + trackedShulkers.put(pos.immutable(), now); + } + } + } + } + } + + private void expireTrackedShulkers() { + long now = System.currentTimeMillis(); + + trackedShulkers.entrySet().removeIf(entry -> now - entry.getValue() > trackTime.getValue()); + } + + private List getTargets(LocalPlayer player, ClientLevel level) { + List targets = new ArrayList<>(); + double rangeSq = targetRange.getValue() * targetRange.getValue(); + + for (BlockPos pos : trackedShulkers.keySet()) { + Vec3 center = Vec3.atCenterOf(pos); + + if (player.distanceToSqr(center) > rangeSq) { + continue; + } + + if (!isShulkerBoxBlock(level.getBlockState(pos).getBlock())) { + continue; + } + + targets.add(new TargetPoint(center, TargetType.Shulker)); + } + + AABB itemSearchBox = player.getBoundingBox().inflate(targetRange.getValue()); + + for (ItemEntity item : level.getEntitiesOfClass(ItemEntity.class, itemSearchBox)) { + if (!item.isAlive()) { + continue; + } + + if (item.tickCount < minItemAge.getValue()) { + continue; + } + + boolean shulkerItem = isShulkerItem(item.getItem()); + boolean nearTrackedShulker = isNearTrackedShulker(item.position()); + + if (!shulkerItem && !nearTrackedShulker) { + continue; + } + + targets.add(new TargetPoint(item.position(), TargetType.Item)); + } + + return targets; + } + + private boolean isNearTrackedShulker(Vec3 itemPos) { + double rangeSq = itemTargetRange.getValue() * itemTargetRange.getValue(); + + for (BlockPos pos : trackedShulkers.keySet()) { + if (itemPos.distanceToSqr(Vec3.atCenterOf(pos)) <= rangeSq) { + return true; + } + } + + return false; + } + + private void sortTargets(LocalPlayer player, List targets) { + switch (priority.getValue()) { + case Shulkers -> targets.sort((a, b) -> { + if (a.type() != b.type()) { + return a.type() == TargetType.Shulker ? -1 : 1; + } + + return Double.compare( + player.distanceToSqr(a.pos()), + player.distanceToSqr(b.pos()) + ); + }); + + case Items -> targets.sort((a, b) -> { + if (a.type() != b.type()) { + return a.type() == TargetType.Item ? -1 : 1; + } + + return Double.compare( + player.distanceToSqr(a.pos()), + player.distanceToSqr(b.pos()) + ); + }); + + case Closest -> targets.sort(Comparator.comparingDouble(target -> player.distanceToSqr(target.pos()))); + + case HighestDamage -> targets.sort((a, b) -> Double.compare( + calculatePointDamage(player.position(), b.pos()), + calculatePointDamage(player.position(), a.pos()) + )); + } + + lastTargetType = targets.getFirst().type(); + } + + private int breakCrystals(LocalPlayer player, ClientLevel level, List targets) { + List crystals = collectAttackableCrystals(player, level, targets); + + if (crystals.isEmpty()) { + return 0; + } + + int broken = 0; + + for (CrystalPlan plan : crystals) { + if (broken >= maxBreaksPerTick.getValue()) { + break; + } + + EndCrystal crystal = plan.crystal(); + + if (!crystal.isAlive()) { + continue; + } + + if (rotationFailed(crystal.position())) { + break; + } + + attackCrystal(player, crystal); + swingHand(InteractionHand.MAIN_HAND); + + broken++; + lastDamage = plan.damage(); + lastTargetType = plan.targetType(); + } + + return broken; + } + + private List collectAttackableCrystals( + LocalPlayer player, + ClientLevel level, + List targets + ) { + List result = new ArrayList<>(); + double selfHealth = player.getHealth() + player.getAbsorptionAmount(); + + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof EndCrystal crystal)) { + continue; + } + + if (!crystal.isAlive()) { + continue; + } + + if (ticksExisted.getValue() > 0 && crystal.tickCount < ticksExisted.getValue()) { + continue; + } + + if (worldBorder.getValue() && !level.getWorldBorder().isWithinBounds(crystal.blockPosition())) { + continue; + } + + Vec3 crystalPos = crystal.position(); + + if (!inAttackRange(player, level, crystalPos)) { + continue; + } + + double selfDamage = calculatePointDamage(crystalPos, player.position()); + + if (selfDamageUnsafe(selfDamage, selfHealth)) { + continue; + } + + TargetPoint bestTarget = null; + double bestDamage = 0.0; + + for (TargetPoint target : targets) { + double damage = calculatePointDamage(crystalPos, target.pos()); + + if (damage > bestDamage) { + bestDamage = damage; + bestTarget = target; + } + } + + if (bestTarget == null || bestDamage < minimumDamage.getValue()) { + continue; + } + + result.add(new CrystalPlan(crystal, bestDamage, bestTarget.type())); + } + + result.sort((a, b) -> Double.compare(b.damage(), a.damage())); + + return result; + } + + private boolean inAttackRange(LocalPlayer player, ClientLevel level, Vec3 crystalPos) { + Vec3 eye = player.getEyePosition(); + Vec3 center = crystalPos.add(0.0, 0.5, 0.0); + double distance = eye.distanceTo(center); + + boolean hasLos = level.clip(new ClipContext( + eye, + center, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + + if (raytrace.getValue() && !hasLos) { + return false; + } + + double range = hasLos ? attackRange.getValue() : attackWallsRange.getValue(); + + return distance <= range; + } + + private PlacePlan findBestPlacement( + LocalPlayer player, + ClientLevel level, + List targets + ) { + Set candidates = getPlaceCandidates(targets); + + BlockPos bestPos = null; + double bestScore = -1.0; + double bestDamage = 0.0; + TargetType bestType = TargetType.Shulker; + + double selfHealth = player.getHealth() + player.getAbsorptionAmount(); + + for (BlockPos pos : candidates) { + if (cannotPlaceCrystal(pos)) { + continue; + } + + Vec3 crystalPos = crystalVec(pos); + + if (!inPlaceRange(player, level, crystalPos)) { + continue; + } + + double selfDamage = calculatePointDamage(crystalPos, player.position()); + + if (selfDamageUnsafe(selfDamage, selfHealth)) { + continue; + } + + for (TargetPoint target : targets) { + double damage = calculatePointDamage(crystalPos, target.pos()); + + if (damage < minimumDamage.getValue()) { + continue; + } + + double score = scorePlacement(player, crystalPos, target, damage, selfDamage); + + if (score > bestScore) { + bestScore = score; + bestPos = pos; + bestDamage = damage; + bestType = target.type(); + } + } + } + + if (bestPos == null) { + return null; + } + + lastDamage = bestDamage; + lastTargetType = bestType; + + return new PlacePlan(bestPos); + } + + private Set getPlaceCandidates(List targets) { + Set candidates = new LinkedHashSet<>(); + int radius = (int) Math.ceil(placeRadius.getValue()); + + for (TargetPoint target : targets) { + BlockPos center = BlockPos.containing(target.pos().x, target.pos().y, target.pos().z); + + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= radius; y++) { + for (int z = -radius; z <= radius; z++) { + BlockPos pos = center.offset(x, y, z); + + if (Vec3.atCenterOf(pos).distanceTo(target.pos()) > placeRadius.getValue()) { + continue; + } + + candidates.add(pos); + } + } + } + } + + return candidates; + } + + private boolean inPlaceRange(LocalPlayer player, ClientLevel level, Vec3 crystalPos) { + Vec3 eye = player.getEyePosition(); + double distance = eye.distanceTo(crystalPos); + + boolean hasLos = level.clip(new ClipContext( + eye, + crystalPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + + if (raytrace.getValue() && !hasLos) { + return false; + } + + double range = hasLos ? placeRange.getValue() : placeWallsRange.getValue(); + + return distance <= range; + } + + private double scorePlacement( + LocalPlayer player, + Vec3 crystalPos, + TargetPoint target, + double targetDamage, + double selfDamage + ) { + double typeBonus = target.type() == TargetType.Shulker ? 2.0 : 1.0; + double distance = player.getEyePosition().distanceTo(crystalPos); + + return (targetDamage * typeBonus * (targetDamage + 2.0)) + / (selfDamage + 2.0) + - distance * 0.05; + } + + private void doPlace(LocalPlayer player, PlacePlan plan) { + MultiPlayerGameMode gameMode = mc.gameMode; + + if (gameMode == null) { + return; + } + + BlockPos basePos = plan.basePos(); + + if (cannotPlaceCrystal(basePos)) { + return; + } + + InteractionHand hand = InteractionHand.MAIN_HAND; + + boolean hasCrystalOffhand = player.getOffhandItem().is(Items.END_CRYSTAL); + boolean hasCrystalMainhand = player.getMainHandItem().is(Items.END_CRYSTAL); + + SwitchData switchData = null; + + if (hasCrystalOffhand) { + hand = InteractionHand.OFF_HAND; + } else if (!hasCrystalMainhand) { + int slot = findCrystalSlot(player); + + if (slot == -1) { + return; + } + + int selected = player.getInventory().getSelectedSlot(); + switchData = doSwitch(player, slot, selected); + + if (!switchData.success()) { + return; + } + } + + Vec3 crystalPos = crystalVec(basePos); + + if (rotationFailed(crystalPos)) { + switchBack(player, switchData); + return; + } + + BlockHitResult hitResult = placementsMode.getValue() == PlacementMode.NCP + ? buildNcpHitResult(basePos) + : new BlockHitResult(crystalPos, Direction.UP, basePos, false); + + gameMode.useItemOn(player, hand, hitResult); + swingHand(hand); + + switchBack(player, switchData); + resetSpoofIfNeeded(); + } + + private void attackCrystal(LocalPlayer player, EndCrystal crystal) { + MultiPlayerGameMode gameMode = mc.gameMode; + + CrystalCircles.spawn(crystal); + + if (breakMode.getValue() == BreakMode.Packet) { + player.connection.send(ServerboundInteractPacket.createAttackPacket(crystal, player.isShiftKeyDown())); + return; + } + + if (gameMode != null) { + gameMode.attack(player, crystal); + } + } + + private boolean cannotPlaceCrystal(BlockPos pos) { + ClientLevel level = mc.level; + + if (level == null) { + return true; + } + + if (worldBorder.getValue() && !level.getWorldBorder().isWithinBounds(pos)) { + return true; + } + + BlockState state = level.getBlockState(pos); + Block block = state.getBlock(); + + if (block != Blocks.OBSIDIAN && block != Blocks.BEDROCK) { + return true; + } + + BlockPos air = pos.above(); + + if (!level.getBlockState(air).isAir()) { + return true; + } + + if (oldVersion.getValue() && !level.getBlockState(air.above()).isAir()) { + return true; + } + + int height = oldVersion.getValue() ? 2 : 1; + + AABB crystalBox = new AABB( + air.getX(), + air.getY(), + air.getZ(), + air.getX() + 1.0, + air.getY() + height, + air.getZ() + 1.0 + ); + + return !level.getEntitiesOfClass(Entity.class, crystalBox, entity -> !(entity instanceof EndCrystal)).isEmpty(); + } + + private BlockHitResult buildNcpHitResult(BlockPos pos) { + PlaceResult result = computePlaceResult(pos, strictDirection.getValue()); + + if (result != null) { + return new BlockHitResult(result.hitVec(), result.direction(), result.neighbor(), false); + } + + return new BlockHitResult(crystalVec(pos), Direction.UP, pos, false); + } + + private PlaceResult computePlaceResult(BlockPos pos, boolean strictDir) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + Vec3 eye = player.getEyePosition(); + + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDistance = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + if (strictDir) { + Vec3 toEye = eye.subtract(hit).normalize(); + + Vec3 faceNormal = new Vec3( + side.getStepX(), + side.getStepY(), + side.getStepZ() + ).normalize(); + + if (toEye.dot(faceNormal) <= 0.0) { + continue; + } + } + + double distance = eye.distanceTo(hit); + + if (distance < bestDistance) { + bestDistance = distance; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + } + + if (bestSide == null) { + return null; + } + + return new PlaceResult(bestNeighbor, bestSide, bestHit); + } + + private double calculatePointDamage(Vec3 explosion, Vec3 target) { + double distance = explosion.distanceTo(target); + + if (distance > 12.0) { + return 0.0; + } + + double factor = 1.0 - distance / 12.0; + + return Math.max(0.0, (factor * factor + factor) * 42.0 + 1.0); + } + + private boolean selfDamageUnsafe(double selfDamage, double selfHealth) { + if (selfDamage > maximumSelfDamage.getValue()) { + return true; + } + + return antiSuicide.getValue() && selfDamage + selfDamageBuffer.getValue() >= selfHealth; + } + + private Vec3 crystalVec(BlockPos base) { + return new Vec3( + base.getX() + 0.5, + base.getY() + 1.0, + base.getZ() + 0.5 + ); + } + + private int findCrystalSlot(LocalPlayer player) { + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).is(Items.END_CRYSTAL)) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(Items.END_CRYSTAL)) { + return i; + } + } + + if (autoSwitch.getValue() == SwitchMode.Silent || autoSwitch.getValue() == SwitchMode.AltSwap) { + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).is(Items.END_CRYSTAL)) { + return i; + } + } + } + + return -1; + } + + private SwitchData doSwitch(LocalPlayer player, int slot, int selectedSlot) { + if (mc.gameMode == null) { + return SwitchData.failed(); + } + + if (slot < 0 || slot > 35) { + return SwitchData.failed(); + } + + if (autoSwitch.getValue() == SwitchMode.None) { + return player.getInventory().getSelectedSlot() == slot + ? new SwitchData(true, selectedSlot, -1, false) + : SwitchData.failed(); + } + + if (slot == selectedSlot) { + return new SwitchData(true, selectedSlot, -1, false); + } + + if (slot <= 8) { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + + return new SwitchData(true, selectedSlot, -1, true); + } + + if (autoSwitch.getValue() != SwitchMode.Silent && autoSwitch.getValue() != SwitchMode.AltSwap) { + return SwitchData.failed(); + } + + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + selectedSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + + player.getInventory().setSelectedSlot(selectedSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(selectedSlot)); + + return new SwitchData(true, selectedSlot, slot, true); + } + + private void switchBack(LocalPlayer player, SwitchData data) { + if (data == null || !data.success() || !data.switched()) { + return; + } + + if (autoSwitch.getValue() == SwitchMode.Normal) { + invSwapSlot = -1; + return; + } + + player.getInventory().setSelectedSlot(data.oldSlot()); + player.connection.send(new ServerboundSetCarriedItemPacket(data.oldSlot())); + + if (data.inventorySlot() != -1 && invSwapSlot == data.inventorySlot() && mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + data.oldSlot(), + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + + private boolean isShulkerItem(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return false; + } + + Item item = stack.getItem(); + + if (item instanceof BlockItem blockItem) { + return isShulkerBoxBlock(blockItem.getBlock()); + } + + return false; + } + + private boolean isShulkerBoxBlock(Block block) { + return block == Blocks.SHULKER_BOX + || block == Blocks.WHITE_SHULKER_BOX + || block == Blocks.ORANGE_SHULKER_BOX + || block == Blocks.MAGENTA_SHULKER_BOX + || block == Blocks.LIGHT_BLUE_SHULKER_BOX + || block == Blocks.YELLOW_SHULKER_BOX + || block == Blocks.LIME_SHULKER_BOX + || block == Blocks.PINK_SHULKER_BOX + || block == Blocks.GRAY_SHULKER_BOX + || block == Blocks.LIGHT_GRAY_SHULKER_BOX + || block == Blocks.CYAN_SHULKER_BOX + || block == Blocks.PURPLE_SHULKER_BOX + || block == Blocks.BLUE_SHULKER_BOX + || block == Blocks.BROWN_SHULKER_BOX + || block == Blocks.GREEN_SHULKER_BOX + || block == Blocks.RED_SHULKER_BOX + || block == Blocks.BLACK_SHULKER_BOX; + } + + private boolean rotationFailed(Vec3 pos) { + if (!rotate.getValue()) { + return false; + } + + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return false; + } + + return !rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void swingHand(InteractionHand hand) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + switch (swing.getValue()) { + case Default -> player.swing(hand); + case Mainhand -> player.swing(InteractionHand.MAIN_HAND); + case Offhand -> player.swing(InteractionHand.OFF_HAND); + case Both -> { + player.swing(InteractionHand.MAIN_HAND); + player.swing(InteractionHand.OFF_HAND); + } + case Packet -> player.connection.send(new ServerboundSwingPacket(hand)); + case None -> { + } + } + } + + @Override + public void onRender3D(Render3DEvent event) { + if (renderMode.getValue() == RenderMode.None || renderPositions.isEmpty()) { + return; + } + + PoseStack stack = event.getMatrix(); + + for (BlockPos pos : renderPositions) { + if (renderMode.getValue() == RenderMode.Fill || renderMode.getValue() == RenderMode.Both) { + RenderUtil.drawBoxFilled(stack, pos, fillColor.getValue()); + } + + if (renderMode.getValue() == RenderMode.Outline || renderMode.getValue() == RenderMode.Both) { + RenderUtil.drawBox(stack, pos, outlineColor.getValue(), renderLineWidth.getValue()); + } + } + } + + @Override + public String getDisplayInfo() { + if (lastDamage <= 0.0) { + return lastTargetType.name(); + } + + return lastTargetType.name() + " " + String.format("%.1f", lastDamage); + } + + private record TargetPoint(Vec3 pos, TargetType type) { + } + + private record PlacePlan(BlockPos basePos) { + } + + private record CrystalPlan(EndCrystal crystal, double damage, TargetType targetType) { + } + + private record PlaceResult(BlockPos neighbor, Direction direction, Vec3 hitVec) { + } + + private record SwitchData(boolean success, int oldSlot, int inventorySlot, boolean switched) { + private static SwitchData failed() { + return new SwitchData(false, -1, -1, false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Aura.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Aura.java new file mode 100644 index 0000000..1c2ea1b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Aura.java @@ -0,0 +1,431 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.render.AuraCircles; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.animal.Animal; +import net.minecraft.world.entity.monster.Monster; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class Aura extends Module { + + public enum Sorting { + Distance, + FOV + } + + public enum MultiTask { + None, + Soft, + Strong + } + + public enum DelayMode { + Cooldown, + Delay + } + + public enum RotateType { + Auto, + Head, + Torso, + Feet + } + + private static final String ROT_ID = "aura"; + private static final int ROT_PRIORITY = 4; + + public final Setting range = num("Range", 5.0, 3.0, 6.0); + public final Setting wallsRange = num("WallsRange", 3.5, 0.0, 6.0); + + private final Setting sorting = mode("Sorting", Sorting.Distance); + private final Setting multiTask = mode("MultiTask", MultiTask.None); + + private final Setting players = bool("Players", true); + private final Setting mobs = bool("Mobs", true); + private final Setting animals = bool("Animals", false); + private final Setting vehicles = bool("Vehicles", false); + + private final Setting delay = mode("Mode", DelayMode.Cooldown); + private final Setting attackSpeed = num("AttackSpeed", 20.0, 0.1, 20.0); + + private final Setting autoSwitch = bool("AutoSwitch", false); + private final Setting noGapSwitch = bool("EatPause", false); + private final Setting onlyWeapon = bool("OnlyWeapon", true); + + private final Setting rotate = bool("Rotate", true); + private final Setting silent = bool("Persist", true); + private final Setting rotateType = mode("Type", RotateType.Auto); + + private final Timer hitTimer = new Timer(); + + public Entity target; + + public Aura() { + super("Aura", "self explanatory", Category.COMBAT); + } + + @Override + public void onDisable() { + target = null; + clearRotations(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!player.isAlive()) { + return; + } + + Entity newTarget = findTarget(player, level); + + if (newTarget == null) { + target = null; + clearRotations(); + return; + } + + if (onlyWeapon.getValue()) { + boolean holdingWeapon = isWeapon(player.getMainHandItem()); + + if (!holdingWeapon && autoSwitch.getValue() && (!noGapSwitch.getValue() || !player.isUsingItem())) { + equipBestWeapon(player); + holdingWeapon = isWeapon(player.getMainHandItem()); + } + + if (!holdingWeapon) { + target = null; + return; + } + } + + target = newTarget; + + Vec3 attackVec = getAttackRotateVec(player, target); + + if (!isInAttackRange(player, level, attackVec)) { + return; + } + + if (player.isUsingItem()) { + switch (multiTask.getValue()) { + case Soft -> { + if (player.getUsedItemHand() != InteractionHand.OFF_HAND) { + target = null; + return; + } + } + + case Strong -> { + target = null; + return; + } + + case None -> { + } + } + } + + boolean canAttack = canAttack(player); + + if (rotate.getValue() && (silent.getValue() || canAttack)) { + applyRotations(attackVec); + } + + if (canAttack) { + attack(player, gameMode, target); + } + } + + private Entity findTarget(LocalPlayer self, ClientLevel level) { + List entities = new ArrayList<>(); + + for (Entity entity : level.entitiesForRendering()) { + if (entity == self) { + continue; + } + + if (!entity.isAlive()) { + continue; + } + + if (self.distanceTo(entity) > range.getValue()) { + continue; + } + + if (!isValidType(entity)) { + continue; + } + + if (entity instanceof Player player && nolongerhuman.friendManager.isFriend(player)) { + continue; + } + + entities.add(entity); + } + + entities.sort(getComparator(self)); + + return entities.isEmpty() ? null : entities.get(0); + } + + private Comparator getComparator(LocalPlayer self) { + if (sorting.getValue() == Sorting.FOV) { + return Comparator.comparingDouble(entity -> angleTo(self, entity)); + } + + return Comparator.comparingDouble(self::distanceTo); + } + + private boolean isValidType(Entity entity) { + if (entity instanceof Player) { + return players.getValue(); + } + + if (entity instanceof Monster) { + return mobs.getValue(); + } + + if (entity instanceof Animal) { + return animals.getValue(); + } + + return vehicles.getValue() && isVehicle(entity); + } + + private boolean isVehicle(Entity entity) { + String type = entity.getType().toString().toLowerCase(); + + return type.contains("boat") || type.contains("minecart"); + } + + private boolean canAttack(LocalPlayer player) { + if (delay.getValue() == DelayMode.Cooldown) { + return player.getAttackStrengthScale(0.0F) >= 1.0F; + } + + long delayMs = Math.max(1L, Math.round(1000.0 / attackSpeed.getValue())); + + if (hitTimer.passedMs(delayMs)) { + hitTimer.reset(); + return true; + } + + return false; + } + + private void attack(LocalPlayer player, MultiPlayerGameMode gameMode, Entity entity) { + AuraCircles.spawn(entity); + + player.connection.send(ServerboundInteractPacket.createAttackPacket(entity, player.isShiftKeyDown())); + gameMode.attack(player, entity); + player.swing(InteractionHand.MAIN_HAND); + } + + private void equipBestWeapon(LocalPlayer player) { + int bestSlot = -1; + double bestScore = -1.0; + + for (int i = 0; i < 9; i++) { + ItemStack stack = player.getInventory().getItem(i); + double score = weaponScore(stack); + + if (score > bestScore) { + bestScore = score; + bestSlot = i; + } + } + + if (bestSlot != -1 && bestSlot != player.getInventory().getSelectedSlot()) { + player.getInventory().setSelectedSlot(bestSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(bestSlot)); + } + } + + private static double weaponScore(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return -1.0; + } + + Item item = stack.getItem(); + + if (item == Items.MACE) { + return 5.0; + } + + if (item == Items.NETHERITE_SWORD) { + return 4.8; + } + + if (item == Items.DIAMOND_SWORD) { + return 4.6; + } + + if (item == Items.IRON_SWORD) { + return 4.4; + } + + if (item == Items.STONE_SWORD) { + return 4.2; + } + + if (item == Items.GOLDEN_SWORD) { + return 4.0; + } + + if (item == Items.WOODEN_SWORD) { + return 3.8; + } + + if (item == Items.NETHERITE_AXE) { + return 3.7; + } + + if (item == Items.DIAMOND_AXE) { + return 3.6; + } + + if (item == Items.IRON_AXE) { + return 3.5; + } + + if (item == Items.STONE_AXE) { + return 3.4; + } + + if (item == Items.GOLDEN_AXE) { + return 3.3; + } + + if (item == Items.WOODEN_AXE) { + return 3.2; + } + + if (item == Items.TRIDENT) { + return 2.0; + } + + return -1.0; + } + + private boolean isWeapon(ItemStack stack) { + return weaponScore(stack) > 0.0; + } + + private boolean isInAttackRange(LocalPlayer player, ClientLevel level, Vec3 entityPos) { + double distance = player.getEyePosition().distanceTo(entityPos); + + if (distance > range.getValue()) { + return false; + } + + HitResult result = level.clip(new ClipContext( + player.getEyePosition(), + entityPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + boolean visible = result.getType() == HitResult.Type.MISS; + + return visible || distance <= wallsRange.getValue(); + } + + private Vec3 getAttackRotateVec(LocalPlayer player, Entity entity) { + Vec3 feet = entity.position(); + + return switch (rotateType.getValue()) { + case Feet -> feet; + + case Torso -> feet.add(0.0, entity.getBbHeight() * 0.5, 0.0); + + case Head -> entity.getEyePosition(); + + case Auto -> { + Vec3 torso = feet.add(0.0, entity.getBbHeight() * 0.5, 0.0); + Vec3 eyes = entity.getEyePosition(); + + Vec3 best = feet; + double bestDist = player.getEyePosition().distanceToSqr(feet); + + double torsoDist = player.getEyePosition().distanceToSqr(torso); + + if (torsoDist < bestDist) { + bestDist = torsoDist; + best = torso; + } + + double eyesDist = player.getEyePosition().distanceToSqr(eyes); + + if (eyesDist < bestDist) { + best = eyes; + } + + yield best; + } + }; + } + + private double angleTo(LocalPlayer player, Entity entity) { + Vec3 diff = entity.position().subtract(player.position()); + double yaw = Math.toDegrees(Math.atan2(diff.z, diff.x)) - 90.0; + + return Math.abs(net.minecraft.util.Mth.wrapDegrees((float) (yaw - player.getYRot()))); + } + + private void applyRotations(Vec3 vec) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + @Override + public String getDisplayInfo() { + return target == null ? "None" : target.getName().getString(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Aura32k.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Aura32k.java new file mode 100644 index 0000000..41d4a97 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Aura32k.java @@ -0,0 +1,230 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.phys.Vec3; + +import java.util.Comparator; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Aura32k extends Module { + + public enum Mode { + Tick, + Fps + } + + public enum AttackMode { + Client, + Packet + } + + private static final String ROT_ID = "32kaura"; + private static final int ROT_PRIORITY = 4; + + private final Setting mode = mode("Mode", Mode.Tick); + private final Setting targetRange = num("Range", 5.0, 5.0, 50.0); + private final Setting rotate = bool("Rotate", true); + private final Setting switchTo32k = bool("SwitchTo32k", true); + private final Setting only32k = bool("Only32k", true); + private final Setting waitTick = num("Delay", 10, 0, 20); + private final Setting attackMode = mode("Attack", AttackMode.Client); + private final Setting totem32k = bool("Totem32k", false); + private final Setting antiTotem = bool("AntiTotem", false); + private final Setting antiTotemTries = num("AntiTotemTries", 1, 1, 10); + private final Setting sharpnessThreshold = num("Sharpness", 100, 100, 32767); + + private int waitCounter = 0; + private Entity target; + + public Aura32k() { + super("Aura32k", "Fast aura intended for 32k/superweapons", Category.COMBAT); + } + + @Override + public void onDisable() { + target = null; + waitCounter = 0; + clearRotations(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) return; + if (!player.isAlive()) return; + + target = findTarget(player, level, targetRange.getValue()); + + if (target == null) { + clearRotations(); + return; + } + + if (rotate.getValue()) { + applyRotations(getAttackVec(target)); + } + + if (mode.getValue() == Mode.Tick) { + doAura(player, gameMode); + } + } + + private void doAura(LocalPlayer player, MultiPlayerGameMode gameMode) { + if (!player.isAlive()) return; + + boolean shield = player.getOffhandItem().is(Items.SHIELD) && player.getUsedItemHand() == InteractionHand.OFF_HAND; + if (player.isUsingItem() && !shield) return; + + if (waitCounter < waitTick.getValue()) { + waitCounter++; + return; + } + + waitCounter = 0; + + Entity t = target; + if (t == null || !t.isAlive()) return; + + for (int i = 0; i < Math.max(1, antiTotem.getValue() ? antiTotemTries.getValue() : 1); i++) { + attack(player, gameMode, t, attackMode.getValue() == AttackMode.Packet); + } + } + + private void attack(LocalPlayer player, MultiPlayerGameMode gameMode, Entity entity, boolean forcePacket) { + boolean holding32k = is32k(player.getMainHandItem()) && !totem32k.getValue(); + + int newSlot = -1; + int totemSlot = findHotbarItem(player, Items.TOTEM_OF_UNDYING); + + if (switchTo32k.getValue() && !holding32k) { + for (int i = 0; i < 9; i++) { + ItemStack stack = player.getInventory().getItem(i); + if (stack.isEmpty()) continue; + + if (is32k(stack)) { + newSlot = i; + break; + } + } + + if (newSlot != -1) { + if (totem32k.getValue() && totemSlot != -1) { + switchSlot(player, totemSlot); + } else { + switchSlot(player, newSlot); + } + + holding32k = true; + } + } + + if (only32k.getValue() && !holding32k) return; + + if (totem32k.getValue() && newSlot != -1 && totemSlot != -1) { + serverSwap(player, newSlot); + } + + if (forcePacket) { + player.connection.send(ServerboundInteractPacket.createAttackPacket(entity, player.isShiftKeyDown())); + } else { + player.connection.send(ServerboundInteractPacket.createAttackPacket(entity, player.isShiftKeyDown())); + gameMode.attack(player, entity); + } + + if (totem32k.getValue() && totemSlot != -1 && newSlot != -1) { + serverSwap(player, totemSlot); + } + + player.swing(InteractionHand.MAIN_HAND); + } + + private Entity findTarget(LocalPlayer self, ClientLevel level, double range) { + return level.players() + .stream() + .filter(p -> p != self) + .filter(Player::isAlive) + .filter(p -> !nolongerhuman.friendManager.isFriend(p)) + .filter(p -> self.distanceTo(p) <= range) + .min(Comparator.comparingDouble(self::distanceTo)) + .orElse(null); + } + + private Vec3 getAttackVec(Entity entity) { + return entity.position().add(0.0, entity.getBbHeight() * 0.5, 0.0); + } + + private boolean is32k(ItemStack stack) { + if (stack == null || stack.isEmpty()) return false; + + String raw = stack.getEnchantments().toString().toLowerCase(Locale.ROOT); + if (!raw.contains("sharpness")) return false; + + int highest = 0; + Matcher matcher = Pattern.compile("\\d+").matcher(raw); + while (matcher.find()) { + try { + highest = Math.max(highest, Integer.parseInt(matcher.group())); + } catch (NumberFormatException ignored) { + } + } + + return highest >= sharpnessThreshold.getValue(); + } + + private int findHotbarItem(LocalPlayer player, net.minecraft.world.item.Item item) { + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(item)) return i; + } + + return -1; + } + + private void switchSlot(LocalPlayer player, int slot) { + if (slot < 0 || slot > 8) return; + + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private void serverSwap(LocalPlayer player, int slot) { + if (slot < 0 || slot > 8) return; + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private boolean applyRotations(Vec3 vec) { + RotationManager rm = nolongerhuman.rotationManager; + return rm == null || rm.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + if (rm == null) return; + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + @Override + public String getDisplayInfo() { + return target == null ? "None" : target.getName().getString(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoCity.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoCity.java new file mode 100644 index 0000000..32041d3 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoCity.java @@ -0,0 +1,1214 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +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.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import me.humanbeing.nolongerhuman.util.combat.CombatPositionCoordinator; + +import java.awt.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class AutoCity extends Module { + public enum TargetMode { + Closest, + LowestHealth, + HighestArmor + } + + public enum SwitchMode { + None, + Normal, + Silent, + AltSwap + } + + public enum PlaceMode { + Native, + NCP + } + + public enum MineMode { + Surround, + Below, + Both + } + + public enum RenderAnimationMode { + None, + Linear, + EaseIn, + EaseOut, + EaseInOut, + Elastic, + Fade + } + + private static final String ROT_ID = "autocity"; + private static final int ROT_PRIORITY = 5; + + private static final EquipmentSlot[] ARMOR_SLOTS = { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + + private final Setting targetMode = mode("TargetMode", TargetMode.Closest); + private final Setting mineMode = mode("Mine", MineMode.Both); + + private final Setting targetRange = num("TargetRange", 10.0, 5.0, 20.0); + private final Setting range = num("Range", 5.0, 1.0, 6.0); + private final Setting wallsRange = num("WallsRange", 3.5, 0.0, 6.0); + + private final Setting delay = num("Delay", 2, 0, 20); + private final Setting retryDelay = num("RetryDelay", 10, 1, 60); + + private final Setting requirePacketMine = bool("RequirePacketMine", true); + private final Setting pauseEat = bool("PauseEat", false); + private final Setting selfMine = bool("SelfMine", false); + private final Setting mineWeb = bool("MineWeb", false); + private final Setting strictDirection = bool("StrictDirection", false); + + private final Setting placeCrystal = bool("PlaceCrystal", true); + private final Setting crystalSwitch = mode("CrystalSwitch", SwitchMode.Silent); + private final Setting placeMode = mode("PlaceMode", PlaceMode.Native); + private final Setting crystalDelay = num("CrystalDelay", 0, 0, 20); + private final Setting placeRange = num("PlaceRange", 5.0, 1.0, 8.0); + private final Setting placeWallsRange = num("PlaceWallsRange", 5.0, 1.0, 8.0); + + private final Setting useAutoCrystalValues = bool("UseACValues", true); + private final Setting damageCheck = bool("DamageCheck", true); + private final Setting minDamage = num("MinDamage", 4.0, 0.0, 36.0); + private final Setting maxSelfDamage = num("MaxSelfDamage", 8.0, 0.0, 36.0); + private final Setting antiSuicide = bool("AntiSuicide", true); + private final Setting oldVersion = bool("1.12", false); + + private final Setting rotate = bool("Rotate", true); + private final Setting swing = bool("Swing", true); + + private final Setting render = bool("Render", true); + private final Setting mineFill = color("MineFill", new Color(255, 90, 90, 70)); + private final Setting mineOutline = color("MineOutline", new Color(255, 90, 90, 220)); + private final Setting crystalFill = color("CrystalFill", new Color(90, 255, 90, 70)); + private final Setting crystalOutline = color("CrystalOutline", new Color(90, 255, 90, 220)); + private final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + private final Setting renderAnimation = mode("RenderAnimation", RenderAnimationMode.EaseOut); + private final Setting renderAnimationTime = num("RenderAnimTime", 150, 0, 1000); + + private final Timer delayTimer = new Timer(); + private final Timer retryTimer = new Timer(); + private final Timer crystalTimer = new Timer(); + + private Player target; + private BlockPos currentMine; + private BlockPos lastCrystalBase; + + private final RenderAnimState mineRenderAnim = new RenderAnimState(); + private final RenderAnimState crystalRenderAnim = new RenderAnimState(); + + public AutoCity() { + super("AutoCity", "Mines surround blocks and places crystals after mining", Category.COMBAT); + } + + @Override + public void onEnable() { + target = null; + currentMine = null; + lastCrystalBase = null; + + mineRenderAnim.reset(); + crystalRenderAnim.reset(); + + delayTimer.reset(); + retryTimer.reset(); + crystalTimer.reset(); + } + + @Override + public void onDisable() { + clearRotations(); + + target = null; + currentMine = null; + lastCrystalBase = null; + + mineRenderAnim.reset(); + crystalRenderAnim.reset(); + CombatPositionCoordinator.clearSource(CombatPositionCoordinator.Source.AUTO_CITY); + + } + + @Override + public void onTick() { + if (nullCheck()) return; + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) return; + + if (pauseEat.getValue() && player.isUsingItem()) return; + + PacketMine packetMine = nolongerhuman.moduleManager.getModuleByClass(PacketMine.class); + + if (requirePacketMine.getValue() && (packetMine == null || !packetMine.isEnabled())) { + return; + } + + target = findTarget(); + + if (target == null) { + currentMine = null; + lastCrystalBase = null; + + mineRenderAnim.reset(); + crystalRenderAnim.reset(); + + return; + } + + handleFinishedMine(); + + if (!delayTimer.passedMs(delay.getValue().longValue() * 50L)) { + return; + } + + BlockPos next = findBestMinePosition(target); + + if (next == null) { + return; + } + + if (currentMine != null + && currentMine.equals(next) + && !retryTimer.passedMs(retryDelay.getValue().longValue() * 50L)) { + return; + } + + Direction side = getMineSide(next); + + if (strictDirection.getValue() && side == null) { + return; + } + + if (!canMine(next)) { + return; + } + + mineWithPacketMine(next, side == null ? Direction.UP : side); + + currentMine = next; + + CombatPositionCoordinator.reserveCityMine( + CombatPositionCoordinator.Source.AUTO_CITY, + next + ); + + retryTimer.reset(); + delayTimer.reset(); + } + + private void handleFinishedMine() { + if (currentMine == null || mc.level == null) return; + + if (!mc.level.getBlockState(currentMine).isAir()) { + return; + } + + if (placeCrystal.getValue() && crystalTimer.passedMs(crystalDelay.getValue().longValue() * 50L)) { + tryPlaceCrystalAfterMine(currentMine); + crystalTimer.reset(); + } + + currentMine = null; + } + + private void mineWithPacketMine(BlockPos pos, Direction side) { + if (mc.gameMode == null) return; + + mc.gameMode.startDestroyBlock(pos, side); + } + + private Player findTarget() { + if (mc.player == null || mc.level == null) return null; + + List players = new ArrayList<>(); + + for (Player player : mc.level.players()) { + if (player == mc.player) continue; + if (!player.isAlive()) continue; + if (nolongerhuman.friendManager.isFriend(player)) continue; + if (mc.player.distanceTo(player) > targetRange.getValue()) continue; + + players.add(player); + } + + if (players.isEmpty()) { + return null; + } + + return switch (targetMode.getValue()) { + case LowestHealth -> players.stream() + .min(Comparator.comparingDouble(p -> p.getHealth() + p.getAbsorptionAmount())) + .orElse(null); + + case HighestArmor -> players.stream() + .max(Comparator.comparingDouble(this::getArmorScore)) + .orElse(null); + + case Closest -> players.stream() + .min(Comparator.comparingDouble(mc.player::distanceTo)) + .orElse(null); + }; + } + + private double getArmorScore(Player player) { + double score = 0.0; + + for (EquipmentSlot slot : ARMOR_SLOTS) { + if (!player.getItemBySlot(slot).isEmpty()) { + score += 1.0; + } + } + + return score; + } + + private BlockPos findBestMinePosition(Player target) { + List surround = getSurroundPositions(target); + List below = getBelowPositions(target); + + List validSurround = new ArrayList<>(); + List validBelow = new ArrayList<>(); + + if (mineMode.getValue() == MineMode.Surround || mineMode.getValue() == MineMode.Both) { + for (BlockPos pos : surround) { + if (canMine(pos)) { + validSurround.add(pos); + } + } + } + + if (mineMode.getValue() == MineMode.Below || mineMode.getValue() == MineMode.Both) { + for (BlockPos pos : below) { + if (canMine(pos)) { + validBelow.add(pos); + } + } + } + + validSurround.sort(this::compareMinePositions); + validBelow.sort(this::compareMinePositions); + + + if (!validSurround.isEmpty()) { + return validSurround.get(0); + } + + if (!validBelow.isEmpty()) { + return validBelow.get(0); + } + + return null; + } + + private int compareMinePositions(BlockPos a, BlockPos b) { + double scoreA = getMineScore(a); + double scoreB = getMineScore(b); + + return Double.compare(scoreB, scoreA); + } + + private double getMineScore(BlockPos pos) { + double score = 0.0; + + if (mc.player != null) { + score -= mc.player.distanceToSqr(Vec3.atCenterOf(pos)) * 0.01; + } + + BlockPos crystalBase = getBestCrystalBaseForMine(pos); + + if (crystalBase != null && target != null) { + AutoCrystal autoCrystal = getAutoCrystal(); + + if (autoCrystal != null) { + Vec3 crystalPos = getCrystalPos(crystalBase); + score += autoCrystal.calculateDamage(crystalPos.x, crystalPos.y, crystalPos.z, target) * 2.0; + + if (mc.player != null) { + score -= autoCrystal.calculateDamage(crystalPos.x, crystalPos.y, crystalPos.z, mc.player); + } + } else { + score += 2.0; + } + } + + return score; + } + + private List getSurroundPositions(Player player) { + Set positions = new LinkedHashSet<>(); + + for (BlockPos feet : getOccupiedFeetPositions(player)) { + for (Direction direction : Direction.Plane.HORIZONTAL) { + positions.add(feet.relative(direction)); + } + } + + return new ArrayList<>(positions); + } + + private List getBelowPositions(Player player) { + Set positions = new LinkedHashSet<>(); + + for (BlockPos feet : getOccupiedFeetPositions(player)) { + positions.add(feet.below()); + } + + return new ArrayList<>(positions); + } + + private List getOccupiedFeetPositions(Player player) { + List positions = new ArrayList<>(); + AABB box = player.getBoundingBox(); + + int minX = Mth.floor(box.minX); + int maxX = Mth.floor(box.maxX); + int minZ = Mth.floor(box.minZ); + int maxZ = Mth.floor(box.maxZ); + int y = player.blockPosition().getY(); + + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + positions.add(new BlockPos(x, y, z)); + } + } + + if (positions.isEmpty()) { + positions.add(player.blockPosition()); + } + + return positions; + } + + private boolean canMine(BlockPos pos) { + if (mc.player == null || mc.level == null) return false; + if (pos == null) return false; + + if ((currentMine == null || !currentMine.equals(pos)) + && CombatPositionCoordinator.isCityMineReservedByOther( + CombatPositionCoordinator.Source.AUTO_CITY, + pos + )) { + return false; + } + + if (!selfMine.getValue() && pos.equals(mc.player.blockPosition())) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (state.isAir()) return false; + if (state.is(Blocks.BEDROCK)) return false; + if (state.is(Blocks.BARRIER)) return false; + if (state.is(Blocks.END_PORTAL_FRAME)) return false; + if (state.getDestroySpeed(mc.level, pos) < 0.0f) return false; + + if (!mineWeb.getValue() && state.is(Blocks.COBWEB)) { + return false; + } + + if (!canReach(pos, range.getValue(), wallsRange.getValue())) { + return false; + } + + return !strictDirection.getValue() || getMineSide(pos) != null; + } + + private boolean canReach(BlockPos pos, double visibleRange, double wallRange) { + if (mc.player == null || mc.level == null) return false; + + Vec3 eye = mc.player.getEyePosition(); + Vec3 hit = Vec3.atCenterOf(pos); + + double distance = eye.distanceTo(hit); + + if (distance <= visibleRange && hasLineOfSight(eye, hit)) { + return true; + } + + return distance <= wallRange; + } + + private boolean hasLineOfSight(Vec3 from, Vec3 to) { + if (mc.level == null || mc.player == null) return false; + + HitResult result = mc.level.clip(new ClipContext( + from, + to, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + mc.player + )); + + return result.getType() == HitResult.Type.MISS; + } + + private Direction getMineSide(BlockPos pos) { + if (mc.player == null || mc.level == null) return Direction.UP; + + Vec3 eye = mc.player.getEyePosition(); + + Direction bestSide = null; + double bestDistance = Double.MAX_VALUE; + + for (Direction direction : Direction.values()) { + Vec3 hit = Vec3.atCenterOf(pos).add( + direction.getStepX() * 0.5, + direction.getStepY() * 0.5, + direction.getStepZ() * 0.5 + ); + + double distance = eye.distanceTo(hit); + + if (distance >= bestDistance) { + continue; + } + + if (!strictDirection.getValue() || hasLineOfSight(eye, hit)) { + bestDistance = distance; + bestSide = direction; + } + } + + return bestSide; + } + + private void tryPlaceCrystalAfterMine(BlockPos minedPos) { + BlockPos base = getBestCrystalBaseForMine(minedPos); + if (base == null) { + return; + } + + if (CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CITY, + base + )) { + return; + } + + if (!canPlaceCrystal(base)) { + return; + } + if (!passesCrystalDamage(base)) { + return; + } + + placeCrystal(base); + } + + private BlockPos getBestCrystalBaseForMine(BlockPos minedPos) { + BlockPos below = minedPos.below(); + + if (!CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CITY, + below + ) && canPlaceCrystal(below)) { + return below; + } + + if (!CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CITY, + minedPos + ) && canPlaceCrystal(minedPos)) { + return minedPos; + } + + return null; + } + + private boolean canPlaceCrystal(BlockPos base) { + if (mc.player == null || mc.level == null) return false; + + ClientLevel level = mc.level; + + if (level.isOutsideBuildHeight(base)) { + return false; + } + + AutoCrystal autoCrystal = getAutoCrystal(); + + boolean useOldVersion = useAutoCrystalValues.getValue() && autoCrystal != null + ? autoCrystal.oldVersion.getValue() + : oldVersion.getValue(); + + boolean checkWorldBorder = autoCrystal == null || autoCrystal.worldBorder.getValue(); + + if (checkWorldBorder && !level.getWorldBorder().isWithinBounds(base)) { + return false; + } + + BlockState baseState = level.getBlockState(base); + + if (!baseState.is(Blocks.OBSIDIAN) && !baseState.is(Blocks.BEDROCK)) { + return false; + } + + BlockPos crystalAir = base.above(); + + if (!level.getBlockState(crystalAir).isAir()) { + return false; + } + + if (useOldVersion && !level.getBlockState(crystalAir.above()).isAir()) { + return false; + } + + int height = useOldVersion ? 2 : 1; + + AABB crystalBox = new AABB( + crystalAir.getX(), + crystalAir.getY(), + crystalAir.getZ(), + crystalAir.getX() + 1.0, + crystalAir.getY() + height, + crystalAir.getZ() + 1.0 + ); + + if (!level.getEntitiesOfClass( + Entity.class, + crystalBox, + entity -> !(entity instanceof EndCrystal) && !(entity instanceof ItemEntity) + ).isEmpty()) { + return false; + } + + Vec3 crystalPos = getCrystalPos(base); + + double distance = mc.player.getEyePosition().distanceTo(crystalPos); + boolean visible = hasLineOfSight(mc.player.getEyePosition(), crystalPos); + + if (visible) { + return distance <= placeRange.getValue(); + } + + return distance <= placeWallsRange.getValue(); + } + + private boolean passesCrystalDamage(BlockPos base) { + if (!damageCheck.getValue()) { + return true; + } + + AutoCrystal autoCrystal = getAutoCrystal(); + + if (autoCrystal == null || target == null || mc.player == null) { + return true; + } + + Vec3 crystalPos = getCrystalPos(base); + + double targetDamage = autoCrystal.calculateDamage( + crystalPos.x, + crystalPos.y, + crystalPos.z, + target + ); + + double selfDamage = autoCrystal.calculateDamage( + crystalPos.x, + crystalPos.y, + crystalPos.z, + mc.player + ); + + double requiredMinDamage = useAutoCrystalValues.getValue() + ? autoCrystal.minimumDamage.getValue() + : minDamage.getValue(); + + double allowedSelfDamage = useAutoCrystalValues.getValue() + ? autoCrystal.maximumSelfDamage.getValue() + : maxSelfDamage.getValue(); + + double selfHealth = mc.player.getHealth() + mc.player.getAbsorptionAmount(); + + if (selfDamage > allowedSelfDamage) { + return false; + } + + if (antiSuicide.getValue() && selfDamage >= selfHealth) { + return false; + } + + return targetDamage >= requiredMinDamage + || targetDamage >= target.getHealth() + target.getAbsorptionAmount(); + } + + private Vec3 getCrystalPos(BlockPos base) { + return new Vec3( + base.getX() + 0.5, + base.getY() + 1.0, + base.getZ() + 0.5 + ); + } + + private void placeCrystal(BlockPos base) { + if (mc.player == null || mc.gameMode == null) return; + + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + int oldSlot = player.getInventory().getSelectedSlot(); + + InteractionHand hand = getCrystalHand(); + SwitchData switchData = null; + + if (hand == null) { + int crystalSlot = findCrystalSlot(); + + if (crystalSlot == -1) { + return; + } + + switchData = switchToCrystal(crystalSlot, oldSlot); + + if (!switchData.success()) { + return; + } + + hand = InteractionHand.MAIN_HAND; + } + + Vec3 crystalPos = getCrystalPos(base); + + if (rotate.getValue()) { + if (!applyRotations(crystalPos)) { + switchBack(switchData); + return; + } + } + + BlockHitResult hitResult = buildCrystalHitResult(base); + + gameMode.useItemOn(player, hand, hitResult); + + CombatPositionCoordinator.reserveCrystalBase( + CombatPositionCoordinator.Source.AUTO_CITY, + base + ); + + if (swing.getValue()) { + player.swing(hand); + } + + switchBack(switchData); + lastCrystalBase = base; + } + + private InteractionHand getCrystalHand() { + if (mc.player == null) return null; + + if (mc.player.getOffhandItem().is(Items.END_CRYSTAL)) { + return InteractionHand.OFF_HAND; + } + + if (mc.player.getMainHandItem().is(Items.END_CRYSTAL)) { + return InteractionHand.MAIN_HAND; + } + + return null; + } + + private int findCrystalSlot() { + if (mc.player == null) return -1; + + for (int i = 0; i < 9; i++) { + if (mc.player.getInventory().getItem(i).is(Items.END_CRYSTAL)) { + return i; + } + } + + if (crystalSwitch.getValue() == SwitchMode.AltSwap) { + for (int i = 9; i < 36; i++) { + if (mc.player.getInventory().getItem(i).is(Items.END_CRYSTAL)) { + return i; + } + } + } + + return -1; + } + + private SwitchData switchToCrystal(int slot, int oldSlot) { + if (mc.player == null || mc.gameMode == null) { + return SwitchData.failed(); + } + + if (crystalSwitch.getValue() == SwitchMode.None) { + return SwitchData.failed(); + } + + if (slot == oldSlot) { + return new SwitchData(true, oldSlot, -1, false); + } + + if (slot >= 0 && slot <= 8) { + mc.player.getInventory().setSelectedSlot(slot); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + + return new SwitchData(true, oldSlot, -1, true); + } + + if (slot >= 9 && slot < 36 && crystalSwitch.getValue() == SwitchMode.AltSwap) { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + slot, + oldSlot, + ClickType.SWAP, + mc.player + ); + + mc.player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + + return new SwitchData(true, oldSlot, slot, true); + } + + return SwitchData.failed(); + } + + private void switchBack(SwitchData data) { + if (data == null || !data.success() || !data.switched()) return; + if (mc.player == null || mc.gameMode == null) return; + + if (crystalSwitch.getValue() == SwitchMode.Normal) { + return; + } + + if (data.inventorySlot() != -1) { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + data.inventorySlot(), + data.oldSlot(), + ClickType.SWAP, + mc.player + ); + + return; + } + + if (crystalSwitch.getValue() == SwitchMode.Silent || crystalSwitch.getValue() == SwitchMode.AltSwap) { + mc.player.getInventory().setSelectedSlot(data.oldSlot()); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(data.oldSlot())); + } + } + + private BlockHitResult buildCrystalHitResult(BlockPos base) { + if (placeMode.getValue() == PlaceMode.Native) { + return new BlockHitResult( + Vec3.atCenterOf(base).add(0.0, 0.5, 0.0), + Direction.UP, + base, + false + ); + } + + PlaceResult result = computePlaceResult(base); + + if (result != null) { + return new BlockHitResult( + result.hitVec(), + result.direction(), + result.neighbor(), + false + ); + } + + return new BlockHitResult( + Vec3.atCenterOf(base).add(0.0, 0.5, 0.0), + Direction.UP, + base, + false + ); + } + + private PlaceResult computePlaceResult(BlockPos pos) { + if (mc.player == null || mc.level == null) return null; + + Vec3 eye = mc.player.getEyePosition(); + + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDistance = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = mc.level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) continue; + if (state.getCollisionShape(mc.level, neighbor).isEmpty()) continue; + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double distance = eye.distanceTo(hit); + + if (distance < bestDistance) { + bestDistance = distance; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + } + + if (bestSide == null) { + return null; + } + + return new PlaceResult(bestNeighbor, bestSide, bestHit); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return true; + } + + return rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + private AutoCrystal getAutoCrystal() { + return nolongerhuman.moduleManager == null + ? null + : nolongerhuman.moduleManager.getModuleByClass(AutoCrystal.class); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + mineRenderAnim.reset(); + crystalRenderAnim.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + renderAnimatedBox( + stack, + mineRenderAnim, + currentMine, + mineFill.getValue(), + mineOutline.getValue() + ); + + renderAnimatedBox( + stack, + crystalRenderAnim, + lastCrystalBase == null ? null : lastCrystalBase.above(), + crystalFill.getValue(), + crystalOutline.getValue() + ); + } + + private void renderAnimatedBox(PoseStack stack, RenderAnimState state, BlockPos pos, Color fill, Color outline) { + if (pos == null) { + state.reset(); + return; + } + + AABB target = new AABB(pos); + + updateRenderAnimation(state, pos, target); + + if (renderAnimation.getValue() == RenderAnimationMode.Fade) { + renderFadeBox(stack, state, fill, outline); + return; + } + + AABB box = getMovingRenderBox(state); + + if (box == null) { + return; + } + + drawRenderBox(stack, box, fill, outline); + } + + private void updateRenderAnimation(RenderAnimState state, BlockPos pos, AABB newTarget) { + RenderAnimationMode mode = renderAnimation.getValue(); + + if (mode == RenderAnimationMode.None || renderAnimationTime.getValue() <= 0) { + state.startBox = newTarget; + state.currentBox = newTarget; + state.targetBox = newTarget; + + state.fadeOutBox = null; + state.fadeInBox = newTarget; + + state.lastPos = pos; + state.animationStart = System.currentTimeMillis(); + + return; + } + + if (state.targetBox == null || state.lastPos == null || !state.lastPos.equals(pos)) { + if (mode == RenderAnimationMode.Fade) { + state.fadeOutBox = state.targetBox; + state.fadeInBox = newTarget; + + state.startBox = newTarget; + state.currentBox = newTarget; + state.targetBox = newTarget; + } else { + state.startBox = state.currentBox == null ? newTarget : state.currentBox; + state.targetBox = newTarget; + + state.fadeOutBox = null; + state.fadeInBox = null; + } + + state.lastPos = pos; + state.animationStart = System.currentTimeMillis(); + } + } + + private AABB getMovingRenderBox(RenderAnimState state) { + if (state.targetBox == null) { + return null; + } + + if (renderAnimation.getValue() == RenderAnimationMode.None || renderAnimationTime.getValue() <= 0) { + state.currentBox = state.targetBox; + return state.currentBox; + } + + if (state.startBox == null) { + state.startBox = state.targetBox; + } + + long now = System.currentTimeMillis(); + + double progress = (double) (now - state.animationStart) / (double) renderAnimationTime.getValue(); + progress = clamp(progress, 0.0, 1.0); + + double eased = ease(progress, renderAnimation.getValue()); + + state.currentBox = lerp(state.startBox, state.targetBox, eased); + + if (progress >= 1.0) { + state.currentBox = state.targetBox; + state.startBox = state.targetBox; + } + + return state.currentBox; + } + + private void renderFadeBox(PoseStack stack, RenderAnimState state, Color fill, Color outline) { + if (state.targetBox == null) { + return; + } + + if (renderAnimationTime.getValue() <= 0) { + drawRenderBox(stack, state.targetBox, fill, outline); + + state.fadeOutBox = null; + state.fadeInBox = state.targetBox; + state.currentBox = state.targetBox; + + return; + } + + long now = System.currentTimeMillis(); + + double progress = (double) (now - state.animationStart) / (double) renderAnimationTime.getValue(); + progress = clamp(progress, 0.0, 1.0); + + double eased = ease(progress, RenderAnimationMode.EaseOut); + double fadeOutAlpha = 1.0 - eased; + + if (state.fadeOutBox != null && fadeOutAlpha > 0.01) { + drawRenderBox( + stack, + state.fadeOutBox, + withAlphaMultiplier(fill, fadeOutAlpha), + withAlphaMultiplier(outline, fadeOutAlpha) + ); + } + + if (state.fadeInBox != null && eased > 0.01) { + drawRenderBox( + stack, + state.fadeInBox, + withAlphaMultiplier(fill, eased), + withAlphaMultiplier(outline, eased) + ); + } + + if (progress >= 1.0) { + state.fadeOutBox = null; + state.fadeInBox = state.targetBox; + state.currentBox = state.targetBox; + } + } + + private void drawRenderBox(PoseStack stack, AABB box, Color fill, Color outline) { + RenderUtil.drawBoxFilled(stack, box, fill); + RenderUtil.drawBox(stack, box, outline, lineWidth.getValue()); + } + + private AABB lerp(AABB from, AABB to, double progress) { + return new AABB( + lerp(from.minX, to.minX, progress), + lerp(from.minY, to.minY, progress), + lerp(from.minZ, to.minZ, progress), + lerp(from.maxX, to.maxX, progress), + lerp(from.maxY, to.maxY, progress), + lerp(from.maxZ, to.maxZ, progress) + ); + } + + private double lerp(double from, double to, double progress) { + return from + (to - from) * progress; + } + + private double ease(double progress, RenderAnimationMode mode) { + progress = clamp(progress, 0.0, 1.0); + + return switch (mode) { + case None, Linear, Fade -> progress; + + case EaseIn -> progress * progress * progress; + + case EaseOut -> { + double inverse = 1.0 - progress; + yield 1.0 - inverse * inverse * inverse; + } + + case EaseInOut -> { + if (progress < 0.5) { + yield 4.0 * progress * progress * progress; + } + + double value = -2.0 * progress + 2.0; + yield 1.0 - (value * value * value) / 2.0; + } + + case Elastic -> { + if (progress == 0.0 || progress == 1.0) { + yield progress; + } + + double c4 = (2.0 * Math.PI) / 3.0; + yield Math.pow(2.0, -10.0 * progress) * Math.sin((progress * 10.0 - 0.75) * c4) + 1.0; + } + }; + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = clamp(multiplier, 0.0, 1.0); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + private double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private static class RenderAnimState { + private AABB startBox = null; + private AABB currentBox = null; + private AABB targetBox = null; + + private AABB fadeOutBox = null; + private AABB fadeInBox = null; + + private BlockPos lastPos = null; + private long animationStart = 0L; + + private void reset() { + startBox = null; + currentBox = null; + targetBox = null; + + fadeOutBox = null; + fadeInBox = null; + + lastPos = null; + animationStart = 0L; + } + } + + @Override + public String getDisplayInfo() { + return target == null ? "None" : target.getName().getString(); + } + + private record SwitchData(boolean success, int oldSlot, int inventorySlot, boolean switched) { + private static SwitchData failed() { + return new SwitchData(false, -1, -1, false); + } + } + + private record PlaceResult(BlockPos neighbor, Direction direction, Vec3 hitVec) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoCrystal.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoCrystal.java new file mode 100644 index 0000000..be3b9fc --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoCrystal.java @@ -0,0 +1,2253 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.EnchantmentUtil; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import me.humanbeing.nolongerhuman.features.modules.render.CrystalCircles; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.server.level.BlockDestructionProgress; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.ai.attributes.Attributes; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.AxeItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import me.humanbeing.nolongerhuman.util.combat.CombatPositionCoordinator; + + +import java.awt.Color; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; + +public class AutoCrystal extends Module { + public enum AntiWeaknessMode { None, Normal, Silent, AltSwap } + public enum PlacementMode { Native, NCP } + public enum SwitchMode { None, Normal, Silent, AltSwap } + public enum SwingMode { Default, None, Packet, Mainhand, Offhand, Both } + public enum WhileEatingMode { None, Attack, Place, Both } + public enum FacePlaceMode { None, Dynamic, Always } + public enum RenderMode { None, Fill, Outline, Both } + + public enum RenderAnimationMode {None, Linear, EaseIn, EaseOut, EaseInOut, Elastic, Fade} + public enum SequentialMode { None, Strict, Strong } + public enum PredictSwingMode { None, Normal, Strict } + public enum TargetMode { Closest, LowestHealth, HighestDamage } + public enum SetDeadMode { None, Ghost } + public enum BreakMode { Vanilla, Packet } + public enum CrystalSelectMode { Score, HighestDamage, Closest } + + private static final EquipmentSlot[] ARMOR_SLOTS = { + EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET + }; + + private static final String ROT_ID = "autocrystal"; + private static final int ROT_PRIORITY = 80; + private static final double DEFAULT_PREDICT_LINEAR_WEIGHT = 1.0D; + private static final double DEFAULT_PREDICT_ADAPTIVE_WEIGHT = 1.0D; + private static final double DEFAULT_PREDICT_STRAFE_WEIGHT = 1.0D; + private static final boolean DEFAULT_PREDICT_VERTICAL = false; + private static final double DEFAULT_PREDICT_DRAG = 0.91D; + private static final double DEFAULT_PREDICT_GRAVITY = 0.08D; + private static final double DEFAULT_PREDICT_SENSITIVITY = 3.0D; + private static final boolean DEFAULT_PREDICT_ONLY_MOVING = true; + private static final double DEFAULT_PREDICT_MOVE_THRESHOLD = 0.05D; + + //strafe + private static final int DEFAULT_STRAFE_SAMPLES = 6; + private static final float DEFAULT_STRAFE_MAX_TURN = 35f; + private static final double DEFAULT_STRAFE_MIN_SPEED = 0.08D; + private static final boolean DEFAULT_STRAFE_DECAY = true; + private static final float DEFAULT_STRAFE_DECAY_RATE = 0.85f; + private static final boolean DEFAULT_STRAFE_USE_HISTORY_VELOCITY = true; + + + private static final Field ENTITY_ID_FIELD; + private static final Field LEVEL_RENDERER_DESTROY_FIELD; + private static final Field GM_DESTROY_PROGRESS_FIELD; + private static final Field GM_DESTROY_POS_FIELD; + + static { + Field f = null; + try { + f = ServerboundInteractPacket.class.getDeclaredField("entityId"); + f.setAccessible(true); + } catch (Exception ignored) { } + ENTITY_ID_FIELD = f; + } + + static { + Field destroy = null; + for (String name : new String[]{"destructionProgress", "destroyingBlocks"}) { + try { + Field cand = LevelRenderer.class.getDeclaredField(name); + cand.setAccessible(true); + destroy = cand; + break; + } catch (Exception ignored) { } + } + if (destroy == null) { + for (Field cand : LevelRenderer.class.getDeclaredFields()) { + if (Map.class.isAssignableFrom(cand.getType())) { + try { + cand.setAccessible(true); + destroy = cand; + break; + } catch (Exception ignored) { } + } + } + } + LEVEL_RENDERER_DESTROY_FIELD = destroy; + + Field prog = null; + for (String name : new String[]{"destroyProgress", "field_78770_f"}) { + try { + Field cand = MultiPlayerGameMode.class.getDeclaredField(name); + cand.setAccessible(true); + if (cand.getType() == float.class) { + prog = cand; + break; + } + } catch (Exception ignored) { } + } + Field pos = null; + for (String name : new String[]{"destroyBlockPos", "field_78778_j"}) { + try { + Field cand = MultiPlayerGameMode.class.getDeclaredField(name); + cand.setAccessible(true); + if (BlockPos.class.isAssignableFrom(cand.getType())) { + pos = cand; + break; + } + } catch (Exception ignored) { } + } + GM_DESTROY_PROGRESS_FIELD = prog; + GM_DESTROY_POS_FIELD = pos; + } + + //place + public final Setting place = bool("Place", true); + public final Setting placeDelay = num("PlaceDelay", 0, 0, 500); + public final Setting placeSpeed = num("PlaceSpeed", 20f, 0.1f, 40f); + public final Setting placeRandom = num("PlaceRandom", 0, 0, 100); + public final Setting placeRange = num("PlaceRange", 4.5, 0.0, 8.0); + public final Setting placeWallsRange = num("PlaceWallsRange", 4.5, 0.0, 8.0); + public final Setting placementsMode = mode("PlacementsMode", PlacementMode.Native); + public final Setting sequential = mode("Sequential", SequentialMode.Strict); + public final Setting facePlaceMode = mode("FaceplaceMode", FacePlaceMode.Dynamic); + public final Setting facePlaceDelay = num("FacePlaceDelay", 10, 0, 20); + public final Setting minimumDamage = num("MinimumDamage", 4.0, 0.0, 36.0); + public final Setting maximumSelfDamage = num("MaximumSelfDamage", 10.0, 0.0, 36.0); + public final Setting healthPlace = bool("HealthPlace", true); + public final Setting health = num("Health", 8f, 0f, 36f); + public final Setting armorPlace = bool("ArmorPlace", true); + public final Setting percentage = num("Percentage", 10, 2, 100); + public final Setting antiSurround = bool("AntiSurround", true); + public final Setting antiSurroundBreak = num("AntiSurroundBreak", 85, 1, 100); + + //break + public final Setting attack = bool("Attack", true); + public final Setting breakSpeed = num("BreakSpeed", 40f, 0.1f, 40f); + public final Setting attackDelay = num("AttackDelay", 0, 0, 500); + public final Setting breakRandom = num("BreakRandom", 0, 0, 100); + public final Setting instant = bool("Instant", true); + public final Setting attackRange = num("AttackRange", 5.0, 0.0, 6.0); + public final Setting attackWallsRange = num("AttackWallsRange", 3.5, 0.0, 6.0); + public final Setting breakMode = mode("BreakMode", BreakMode.Vanilla); + public final Setting inhibit = bool("Inhibit", true); + public final Setting inhibitTime = num("InhibitTime", 50, 0, 1000); + public final Setting multiBreak = bool("MultiBreak", true); + public final Setting maxBreaksPerTick = num("MaxBreaks", 2, 1, 10); + public final Setting hits = num("Hits", 1, 1, 3); + public final Setting maxHits = num("MaxHits", 2, 1, 10); + public final Setting idPredict = bool("IdPredict", false); + public final Setting predictions = num("Predictions", 4, 1, 20); + public final Setting offset = num("Offset", 0, 0, 2); + public final Setting predictSwing = mode("PredictSwing", PredictSwingMode.Normal); + public final Setting fast = bool("Fast", false); + public final Setting antiKick = bool("AntiKick", false); + public final Setting kickThreshold = num("KickThreshold", 5, 1, 10); + public final Setting breakSelect = mode("BreakSelect", CrystalSelectMode.Score); + public final Setting ticksExisted = num("TicksExisted", 0, 0, 10); + public final Setting setDead = mode("SetDead", SetDeadMode.None); + + //swap + public final Setting autoSwitch = mode("Switch", SwitchMode.None); + public final Setting antiWeakness = mode("AntiWeakness", AntiWeaknessMode.None); + public final Setting swapDelay = num("SwapDelay", 0, 0, 500); + public final Setting multitask = mode("MultiTask", WhileEatingMode.None); + + //baseplace + public final Setting basePlace = bool("BasePlace", true); + public final Setting basePlaceExtend = bool("BasePlaceExtend", false); + public final Setting basePlaceSpeed = num("BasePlaceSpeed", 20f, 0.1f, 40f); + public final Setting basePlaceRange = num("BasePlaceRange", 5.0, 1.0, 6.0); + public final Setting baseMinDamage = num("BaseMinDamage", 6.0, 0.0, 36.0); + + //smartness + public final Setting enemyRange = num("EnemyRange", 16.0, 0.0, 24.0); + public final Setting raytrace = bool("Raytrace", false); + public final Setting antiNaked = bool("AntiNaked", false); + public final Setting chestBreak = bool("ChestBreak", true); + public final Setting antiStuck = bool("AntiStuck", false); + public final Setting lethalMultiplier = num("LethalMultiplier", 1.5f, 0f, 4f); + public final Setting antiSuicide = bool("AntiSuicide", true); + public final Setting suicide = bool("Suicide", false); + public final Setting lethalCrystals = num("LethalCrystals", 1, 0, 5); + public final Setting resistanceCalc = bool("ResistanceCalc", true); + public final Setting selfDamageBuffer = num("SelfDamageBuffer", 2.0, 0.0, 10.0); + public final Setting bestRatio = bool("BestRatio", true); + public final Setting ratioBias = num("RatioBias", 0.5, 0.1, 4.0); + + //prediction + public final Setting predictionTicks = num("PredictionTicks", 1, 0, 8); + + + //sticky / misc placement + public final Setting worldBorder = bool("WorldBorder", true); + public final Setting motionSticky = bool("MotionSticky", true); + public final Setting motionStickyDistance = num("MotionStickyDistance", 0.25, 0.0, 2.0); + public final Setting targetMode = mode("TargetMode", TargetMode.Closest); + public final Setting onlyGround = bool("OnlyGround", false); + public final Setting distanceBias = bool("DistanceBias", false); + public final Setting distanceBiasWeight = num("DistanceBiasWeight", 0.5, 0.0, 5.0); + public final Setting targetProximityBias = bool("TargetProximityBias", false); + public final Setting targetProximityWeight = num("TargetProximityWeight", 1.0, 0.0, 5.0); + + //rotations + public final Setting strictDirection = bool("StrictDirection", true); + + //other + public final Setting oldVersion = bool("1.12", false); + public final Setting blockDestruction = bool("BlockDestruction", true); + public final Setting swing = mode("Swing", SwingMode.Default); + public final Setting asynchronous = bool("Multithread", true); + + //render + public final Setting renderMode = mode("RenderMode", RenderMode.Both); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting renderLineWidth = num("RenderLineWidth", 1.0f, 0.1f, 5.0f); + public final Setting renderAnimation = mode("RenderAnimation", RenderAnimationMode.EaseOut); + public final Setting renderAnimationTime = num("RenderAnimTime", 150, 0, 1000); + + //timings and shit + private final Timer swapTimer = new Timer(); + private final Timer facePlaceTimer = new Timer(); + private final Timer basePlaceTimer = new Timer(); + private final Timer attackDelayTimer = new Timer(); + private final Timer placeDelayTimer = new Timer(); + private int sinceAttackTick = 0; + private int sincePlaceTick = 0; + private BlockPos renderPos = null; + private BlockPos baseRenderPos = null; + + private final RenderAnimState crystalRenderAnim = new RenderAnimState(); + private final RenderAnimState baseRenderAnim = new RenderAnimState(); + private Player target = null; + private int oldSlot = -1; + private boolean lastActionWasAttack = false; + private final Set attackedThisTick = new HashSet<>(); + private int kickTicks = 0; + private final LinkedList brokeCrystals = new LinkedList<>(); + private int crystalsPerSecond = 0; + private String lastTargetName = null; + private double lastRenderDamage = 0.0; + private final Map pendingPlacePositions = new ConcurrentHashMap<>(); + private final Map confirmedPlacePositions = new ConcurrentHashMap<>(); + private final Map inhibitedCrystals = new ConcurrentHashMap<>(); + private final Map crystalHitCount = new ConcurrentHashMap<>(); + private BlockPos lastPlacePos = null; + private Vec3 lastTargetMotionPos = null; + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private final AtomicBoolean calcRunning = new AtomicBoolean(false); + private volatile BlockPos asyncPlacePos = null; + private volatile double asyncPlaceDamage = 0.0; + private final Random random = new Random(); + private long nextAttackDelay = 0L; + private long nextPlaceDelay = 0L; + private final Map> motionHistory = new ConcurrentHashMap<>(); + private int trackedHighestId = Integer.MIN_VALUE; + + public AutoCrystal() { + super("AutoCrystal", "Crystal aura", Category.COMBAT); + } + + public int getCrystalsPerSecond() { + return crystalsPerSecond; + } + + @Override + public void onDisable() { + clearAutoCrystalRotations(); + renderPos = null; + baseRenderPos = null; + crystalRenderAnim.reset(); + baseRenderAnim.reset(); + target = null; + oldSlot = -1; + lastActionWasAttack = false; + attackedThisTick.clear(); + trackedHighestId = Integer.MIN_VALUE; + kickTicks = 0; + brokeCrystals.clear(); + crystalsPerSecond = 0; + lastTargetName = null; + lastRenderDamage = 0.0; + lastPlacePos = null; + lastTargetMotionPos = null; + asyncPlacePos = null; + asyncPlaceDamage = 0.0; + sinceAttackTick = 0; + sincePlaceTick = 0; + pendingPlacePositions.clear(); + confirmedPlacePositions.clear(); + inhibitedCrystals.clear(); + crystalHitCount.clear(); + nextAttackDelay = 0L; + nextPlaceDelay = 0L; + motionHistory.clear(); + CombatPositionCoordinator.clearSource(CombatPositionCoordinator.Source.AUTO_CRYSTAL); + } + + @Override + public void onTick() { + if (nullCheck()) return; + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return; + attackedThisTick.clear(); + sinceAttackTick++; + sincePlaceTick++; + updateIdTracker(); + long now = System.currentTimeMillis(); + brokeCrystals.removeIf(t -> now - t > 1000L); + crystalsPerSecond = brokeCrystals.size(); + confirmPlacements(); + expireMaps(); + updateMotionHistory(getTargets()); + if (player.isUsingItem() && multitask.getValue() == WhileEatingMode.None) return; + target = getTarget(); + if (target == null) { + renderPos = null; + baseRenderPos = null; + crystalRenderAnim.reset(); + baseRenderAnim.reset(); + kickTicks = 0; + lastRenderDamage = 0.0; + lastPlacePos = null; + lastTargetMotionPos = null; + asyncPlacePos = null; + clearAutoCrystalRotations(); + return; + } + lastTargetName = target.getName().getString(); + if (asynchronous.getValue()) { + if (calcRunning.compareAndSet(false, true)) { + executor.submit(() -> { + try { + computeAsync(); + } catch (Exception ignored) { + } finally { + calcRunning.set(false); + } + }); + } + } + int attackEvery = instant.getValue() ? 1 : Math.max(1, Math.round(20f / breakSpeed.getValue())); + int placeEvery = Math.max(1, Math.round(20f / placeSpeed.getValue())); + boolean canAttack = attack.getValue() && sinceAttackTick >= attackEvery; + boolean canPlace = place.getValue() && sincePlaceTick >= placeEvery; + if (player.isUsingItem()) { + if (multitask.getValue() == WhileEatingMode.Place) canAttack = false; + if (multitask.getValue() == WhileEatingMode.Attack) canPlace = false; + } + if (attackDelay.getValue() > 0 && !attackDelayTimer.passedMs(nextAttackDelay)) canAttack = false; + if (placeDelay.getValue() > 0 && !placeDelayTimer.passedMs(nextPlaceDelay)) canPlace = false; + switch (sequential.getValue()) { + case Strict -> { + if (lastActionWasAttack) { + if (canPlace) doPlace(); + } else { + if (canAttack) doBreak(); + } + } + case Strong -> { + if (canAttack) doBreak(); + boolean justBroke = sinceAttackTick == 0; + if (canPlace || justBroke) doPlace(); + } + case None -> { + if (canAttack) doBreak(); + if (canPlace) doPlace(); + } + } + if (basePlace.getValue() && basePlaceTimer.passedMs((long) (1000 / basePlaceSpeed.getValue()))) { + doBasePlace(); + } + } + + private void updateIdTracker() { + ClientLevel level = mc.level; + if (level == null) return; + for (Entity entity : level.entitiesForRendering()) { + if (entity.getId() > trackedHighestId) trackedHighestId = entity.getId(); + } + } + + private long computeDelay(int base, int randomPct) { + if (base <= 0) return 0L; + if (randomPct <= 0) return (long) base; + double spread = (random.nextDouble() * 2.0 - 1.0) * (randomPct / 100.0); + return Math.max(0L, Math.round(base * (1.0 + spread))); + } + + private void attackCrystal(EndCrystal crystal) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || crystal == null) { + return; + } + + CrystalCircles.spawn(crystal); + + if (breakMode.getValue() == BreakMode.Packet) { + player.connection.send(ServerboundInteractPacket.createAttackPacket(crystal, player.isShiftKeyDown())); + } else if (gameMode != null) { + gameMode.attack(player, crystal); + } + } + + private void computeAsync() { + PlacePlan plan = findBestPlacement(); + if (plan != null && plan.pos != null) { + asyncPlacePos = plan.pos; + asyncPlaceDamage = plan.damage; + } else { + asyncPlacePos = null; + asyncPlaceDamage = 0.0; + } + } + + private List getPlaceCandidates(LocalPlayer player, List targets) { + List candidates = getSphere( + player.blockPosition(), + placeRange.getValue().floatValue(), + placeRange.getValue().intValue(), + false, + true, + 0 + ); + + if (onlyGround.getValue()) { + int playerY = player.blockPosition().getY(); + candidates.removeIf(pos -> pos.getY() > playerY); + } + + return candidates; + } + + private double placeScore(BlockPos pos, double targetDamage, double selfDamage, + LocalPlayer player, List targets) { + double base = scoreCandidate(targetDamage, selfDamage); + if (base <= 0) return base; + Vec3 crystal = new Vec3(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5); + if (distanceBias.getValue()) { + double selfDist = player.getEyePosition().distanceTo(crystal); + base *= 1.0 + distanceBiasWeight.getValue() / (1.0 + selfDist); + } + if (targetProximityBias.getValue() && targets != null && !targets.isEmpty()) { + double nearest = Double.MAX_VALUE; + for (Player t : targets) { + nearest = Math.min(nearest, t.position().distanceTo(crystal)); + } + base *= 1.0 + targetProximityWeight.getValue() / (1.0 + nearest); + } + return base; + } + + private void updateMotionHistory(List targets) { + Set live = new HashSet<>(); + + for (Player t : targets) { + live.add(t.getId()); + } + + motionHistory.keySet().removeIf(id -> !live.contains(id)); + + int cap = Math.max(3, DEFAULT_STRAFE_SAMPLES); + + for (Player t : targets) { + Deque hist = motionHistory.computeIfAbsent(t.getId(), k -> new ArrayDeque<>()); + hist.addLast(t.position()); + + while (hist.size() > cap) { + hist.removeFirst(); + } + } + } + + private PredictionState buildPredictionState(Entity entity) { + Vec3 currentMotion = entity.getDeltaMovement(); + + double vx = currentMotion.x; + double vy = currentMotion.y; + double vz = currentMotion.z; + + double ax = 0.0; + double ay = 0.0; + double az = 0.0; + + double avgVx = vx; + double avgVy = vy; + double avgVz = vz; + + Deque hist = motionHistory.get(entity.getId()); + + if (hist != null && hist.size() >= 2) { + Vec3[] arr = hist.toArray(new Vec3[0]); + + Vec3 lastVelocity = arr[arr.length - 1].subtract(arr[arr.length - 2]); + + double weightedVx = 0.0; + double weightedVy = 0.0; + double weightedVz = 0.0; + double totalWeight = 0.0; + + for (int i = 1; i < arr.length; i++) { + Vec3 vel = arr[i].subtract(arr[i - 1]); + double weight = i; + + weightedVx += vel.x * weight; + weightedVy += vel.y * weight; + weightedVz += vel.z * weight; + totalWeight += weight; + } + + if (totalWeight > 0.0) { + avgVx = weightedVx / totalWeight; + avgVy = weightedVy / totalWeight; + avgVz = weightedVz / totalWeight; + } + + if (DEFAULT_STRAFE_USE_HISTORY_VELOCITY) { + vx = blend(currentMotion.x, lastVelocity.x, 0.65); + vy = blend(currentMotion.y, lastVelocity.y, 0.35); + vz = blend(currentMotion.z, lastVelocity.z, 0.65); + } + + if (arr.length >= 3) { + Vec3 previousVelocity = arr[arr.length - 2].subtract(arr[arr.length - 3]); + Vec3 acceleration = lastVelocity.subtract(previousVelocity); + + ax = acceleration.x; + ay = acceleration.y; + az = acceleration.z; + } + } + + double sensitivity = Mth.clamp(DEFAULT_PREDICT_SENSITIVITY / 10.0, 0.0, 1.0); + + vx = blend(vx, avgVx, sensitivity); + vy = blend(vy, avgVy, sensitivity * 0.5); + vz = blend(vz, avgVz, sensitivity); + + return new PredictionState( + new Vec3(vx, vy, vz), + new Vec3(ax, ay, az), + averageTurn(entity.getId()) + ); + } + + private double averageTurn(int id) { + Deque hist = motionHistory.get(id); + + if (hist == null || hist.size() < 3) { + return 0.0; + } + + Vec3[] arr = hist.toArray(new Vec3[0]); + + double weightedTurn = 0.0; + double totalWeight = 0.0; + + for (int i = 2; i < arr.length; i++) { + Vec3 previous = arr[i - 1].subtract(arr[i - 2]); + Vec3 current = arr[i].subtract(arr[i - 1]); + + double previousSpeed = Math.hypot(previous.x, previous.z); + double currentSpeed = Math.hypot(current.x, current.z); + + if (previousSpeed < 1.0E-4 || currentSpeed < 1.0E-4) { + continue; + } + + double previousAngle = Math.toDegrees(Math.atan2(previous.z, previous.x)); + double currentAngle = Math.toDegrees(Math.atan2(current.z, current.x)); + double delta = Mth.wrapDegrees((float) (currentAngle - previousAngle)); + + double weight = i; + weightedTurn += delta * weight; + totalWeight += weight; + } + + if (totalWeight <= 0.0) { + return 0.0; + } + + return weightedTurn / totalWeight; + } + + private Vec3 predictLinear(Vec3 motion, int ticks) { + double px = 0.0; + double py = 0.0; + double pz = 0.0; + + double vx = motion.x; + double vy = motion.y; + double vz = motion.z; + + for (int i = 0; i < ticks; i++) { + px += vx; + pz += vz; + + if (DEFAULT_PREDICT_VERTICAL) { + py += vy; + } + } + + return new Vec3(px, DEFAULT_PREDICT_VERTICAL ? py : 0.0, pz); + } + + private Vec3 predictAdaptive(PredictionState state, int ticks) { + Vec3 velocity = state.velocity(); + Vec3 acceleration = state.acceleration(); + + double vx = velocity.x; + double vy = velocity.y; + double vz = velocity.z; + + double ax = acceleration.x; + double ay = acceleration.y; + double az = acceleration.z; + + double px = 0.0; + double py = 0.0; + double pz = 0.0; + + double drag = DEFAULT_PREDICT_DRAG; + double gravity = DEFAULT_PREDICT_GRAVITY; + + double accelerationScale = Mth.clamp(DEFAULT_PREDICT_SENSITIVITY / 5.0, 0.0, 2.0); + + for (int i = 0; i < ticks; i++) { + vx += ax * accelerationScale; + vz += az * accelerationScale; + + px += vx; + pz += vz; + + vx *= drag; + vz *= drag; + + if (DEFAULT_PREDICT_VERTICAL) { + vy += ay * accelerationScale; + py += vy; + vy = (vy - gravity) * 0.98; + } + } + + return new Vec3(px, DEFAULT_PREDICT_VERTICAL ? py : 0.0, pz); + } + + private Vec3 predictStrafe(Entity entity, int ticks) { + PredictionState state = buildPredictionState(entity); + + Vec3 velocity = state.velocity(); + + double vx = velocity.x; + double vy = velocity.y; + double vz = velocity.z; + + double horizontalSpeed = Math.hypot(vx, vz); + + double turn = horizontalSpeed < DEFAULT_STRAFE_MIN_SPEED + ? 0.0 + : Math.toRadians(Mth.clamp( + (float) state.turn(), + -DEFAULT_STRAFE_MAX_TURN, + DEFAULT_STRAFE_MAX_TURN + )); + + double drag = DEFAULT_PREDICT_DRAG; + double gravity = DEFAULT_PREDICT_GRAVITY; + double decay = DEFAULT_STRAFE_DECAY ? DEFAULT_STRAFE_DECAY_RATE : 1.0; + + double px = 0.0; + double py = 0.0; + double pz = 0.0; + + for (int i = 0; i < ticks; i++) { + px += vx; + pz += vz; + + if (DEFAULT_PREDICT_VERTICAL) { + py += vy; + } + + double cos = Math.cos(turn); + double sin = Math.sin(turn); + + double nextVx = vx * cos - vz * sin; + double nextVz = vx * sin + vz * cos; + + vx = nextVx * drag; + vz = nextVz * drag; + + if (DEFAULT_PREDICT_VERTICAL) { + vy = (vy - gravity) * 0.98; + } + + turn *= decay; + } + + return new Vec3(px, DEFAULT_PREDICT_VERTICAL ? py : 0.0, pz); + } + + private void confirmPlacements() { + ClientLevel level = mc.level; + if (level == null) return; + long now = System.currentTimeMillis(); + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof EndCrystal crystal)) continue; + BlockPos cpos = crystal.blockPosition(); + if (pendingPlacePositions.remove(cpos) != null) { + confirmedPlacePositions.put(cpos, now); + } + } + } + + private void expireMaps() { + long now = System.currentTimeMillis(); + long expire = getExpireFactor(); + pendingPlacePositions.entrySet().removeIf(e -> now - e.getValue() > 1000L); + confirmedPlacePositions.entrySet().removeIf(e -> now - e.getValue() > 1000L); + inhibitedCrystals.entrySet().removeIf(e -> now - e.getValue() > expire); + crystalHitCount.keySet().removeIf(id -> !inhibitedCrystals.containsKey(id)); + } + + private long getExpireFactor() { + return Math.max(250L, inhibitTime.getValue().longValue() + 100L); + } + + private boolean isValidCrystalTarget(int id, long now) { + Integer h = crystalHitCount.get(id); + Long last = inhibitedCrystals.get(id); + if (h == null || last == null) return true; + return h < maxHits.getValue() || (now - last) >= 250L; + } + + private boolean blockedByUnknownCrystal(BlockPos base) { + if (!antiStuck.getValue()) return false; + ClientLevel level = mc.level; + if (level == null) return false; + AABB box = new AABB(base.above()); + for (EndCrystal c : level.getEntitiesOfClass(EndCrystal.class, box)) { + BlockPos cp = c.blockPosition(); + if (!confirmedPlacePositions.containsKey(cp) && !pendingPlacePositions.containsKey(cp)) { + return true; + } + } + return false; + } + + private boolean selfDamageUnsafe(double selfDamage, double selfHealth) { + if (suicide.getValue()) return false; + if (selfDamage > maximumSelfDamage.getValue()) return true; + if (antiSuicide.getValue() && selfDamage + selfDamageBuffer.getValue() >= selfHealth) return true; + return false; + } + + private int getItemHotbarSlot(Item item) { + LocalPlayer player = mc.player; + if (player == null) return -1; + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).getItem() == item) return i; + } + return -1; + } + + private void switchSlot(int slot) { + LocalPlayer player = mc.player; + if (player == null || slot < 0 || slot > 8) return; + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private void serverSwap(int hotbarSlot) { + LocalPlayer player = mc.player; + if (player == null || hotbarSlot < 0 || hotbarSlot > 8) return; + player.connection.send(new ServerboundSetCarriedItemPacket(hotbarSlot)); + } + + private void doBreak() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + if (player == null || level == null || gameMode == null) return; + List crystals = collectAttackableCrystals(); + if (crystals.isEmpty()) return; + int selected = player.getInventory().getSelectedSlot(); + boolean weaknessVisibleSwap = false; + boolean weaknessAltSwap = false; + int weaknessBackSlot = -1; + if (antiWeakness.getValue() != AntiWeaknessMode.None && player.hasEffect(MobEffects.WEAKNESS)) { + int toolSlot = findToolSlot(); + if (toolSlot != -1 && selected != toolSlot) { + switch (antiWeakness.getValue()) { + case Normal, Silent -> { + oldSlot = selected; + switchSlot(toolSlot); + swapTimer.reset(); + weaknessVisibleSwap = true; + } + case AltSwap -> { + weaknessAltSwap = true; + weaknessBackSlot = selected; + serverSwap(toolSlot); + } + default -> { } + } + } + } + if (weaknessVisibleSwap && swapDelay.getValue() > 0 && !swapTimer.passedMs(swapDelay.getValue().longValue())) { + if (oldSlot != -1 && antiWeakness.getValue() == AntiWeaknessMode.Silent) { + switchSlot(oldSlot); + oldSlot = -1; + } + return; + } + int limit = multiBreak.getValue() ? maxBreaksPerTick.getValue() : 1; + int broken = 0; + boolean rotatedOnce = false; + long now = System.currentTimeMillis(); + long expire = getExpireFactor(); + int hitCount = Math.max(1, hits.getValue()); + for (EndCrystal crystal : crystals) { + if (broken >= limit) break; + if (attackedThisTick.contains(crystal.getId())) continue; + if (!crystal.isAlive()) continue; + if (!rotatedOnce) { + if (!applyRotations(crystal.position())) { + if (weaknessAltSwap) serverSwap(weaknessBackSlot); + return; + } + rotatedOnce = true; + } + int id = crystal.getId(); + for (int h = 0; h < hitCount; h++) { + attackCrystal(crystal); + swingHand(InteractionHand.MAIN_HAND); + } + attackedThisTick.add(id); + Long last = inhibitedCrystals.get(id); + int prev = (last == null || now - last > expire) ? 0 : crystalHitCount.getOrDefault(id, 0); + crystalHitCount.put(id, prev + hitCount); + inhibitedCrystals.put(id, now); + if (setDead.getValue() == SetDeadMode.Ghost) { + try { + crystal.remove(Entity.RemovalReason.KILLED); + } catch (Exception ignored) { } + } + brokeCrystals.add(System.currentTimeMillis()); + broken++; + } + if (weaknessAltSwap) serverSwap(weaknessBackSlot); + if (oldSlot != -1 && antiWeakness.getValue() == AntiWeaknessMode.Silent) { + switchSlot(oldSlot); + oldSlot = -1; + } + if (broken == 0) return; + lastActionWasAttack = true; + sinceAttackTick = 0; + if (attackDelay.getValue() > 0) { + attackDelayTimer.reset(); + nextAttackDelay = computeDelay(attackDelay.getValue(), breakRandom.getValue()); + } + } + + private List collectAttackableCrystals() { + List result = new ArrayList<>(); + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return result; + List targets = getTargets(); + if (targets.isEmpty()) return result; + double selfHealth = player.getHealth() + player.getAbsorptionAmount(); + Map scores = new HashMap<>(); + Map dmgMap = new HashMap<>(); + Map distMap = new HashMap<>(); + double bestDamage = 0.0; + long now = System.currentTimeMillis(); + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof EndCrystal crystal)) continue; + int id = crystal.getId(); + if (attackedThisTick.contains(id)) continue; + if (!crystal.isAlive()) continue; + if (ticksExisted.getValue() > 0 && crystal.tickCount < ticksExisted.getValue()) continue; + if (worldBorder.getValue() && !level.getWorldBorder().isWithinBounds(crystal.blockPosition())) continue; + if (inhibit.getValue() && !isValidCrystalTarget(id, now)) continue; + Vec3 eyePos = player.getEyePosition(); + Vec3 crystalCenter = new Vec3(crystal.getX(), crystal.getY() + 1.0, crystal.getZ()); + double dist = eyePos.distanceTo(crystal.position()); + boolean hasLos = level.clip(new ClipContext( + eyePos, crystalCenter, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + if (raytrace.getValue() && !hasLos) continue; + double range = hasLos ? attackRange.getValue() : attackWallsRange.getValue(); + if (dist > range) continue; + double selfDamage = calculateDamage(crystal.getX(), crystal.getY(), crystal.getZ(), player); + if (selfDamageUnsafe(selfDamage, selfHealth)) continue; + boolean ours = confirmedPlacePositions.containsKey(crystal.blockPosition()); + double best = -1.0; + double crystalBestTargetDamage = 0.0; + for (Player t : targets) { + double damage = calculateDamage(crystal.getX(), crystal.getY(), crystal.getZ(), t, extrapolationOffset(t)); + double targetHealth = t.getHealth() + t.getAbsorptionAmount(); + boolean lethal = damage * (1.0 + lethalMultiplier.getValue()) >= targetHealth; + boolean countLethal = lethalCrystals.getValue() > 0 && damage * lethalCrystals.getValue() >= targetHealth; + if (!ours && damage < getMinDamage(t) && damage < targetHealth && !lethal && !countLethal) continue; + double score = damage >= targetHealth ? Double.MAX_VALUE / 4.0 : scoreCandidate(damage, selfDamage); + if (score > best) best = score; + if (damage > crystalBestTargetDamage) crystalBestTargetDamage = damage; + if (damage > bestDamage) bestDamage = damage; + } + if (best < 0 && !ours) continue; + if (ours) best = Double.MAX_VALUE / 2.0; + scores.put(id, best); + dmgMap.put(id, ours ? Double.MAX_VALUE / 2.0 : crystalBestTargetDamage); + distMap.put(id, dist); + result.add(crystal); + } + switch (breakSelect.getValue()) { + case HighestDamage -> result.sort((a, b) -> Double.compare( + dmgMap.getOrDefault(b.getId(), 0.0), + dmgMap.getOrDefault(a.getId(), 0.0) + )); + case Closest -> result.sort((a, b) -> Double.compare( + distMap.getOrDefault(a.getId(), Double.MAX_VALUE), + distMap.getOrDefault(b.getId(), Double.MAX_VALUE) + )); + default -> result.sort((a, b) -> Double.compare( + scores.getOrDefault(b.getId(), 0.0), + scores.getOrDefault(a.getId(), 0.0) + )); + } + if (!result.isEmpty()) lastRenderDamage = bestDamage; + return result; + } + + private void doPlace() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + if (player == null || level == null || gameMode == null) return; + PlacePlan plan = asynchronous.getValue() + ? (asyncPlacePos != null ? new PlacePlan(asyncPlacePos, asyncPlaceDamage) : null) + : findBestPlacement(); + if (plan == null || plan.pos == null) { + renderPos = null; + return; + } + BlockPos bestPos = plan.pos; + + if (CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CRYSTAL, + bestPos + )) { + renderPos = null; + return; + } + + if (cannotPlaceCrystal(bestPos)) { + renderPos = null; + return; + } + if (blockedByUnknownCrystal(bestPos)) { + renderPos = null; + return; + } + Vec3 crystalPos = new Vec3(bestPos.getX() + 0.5, bestPos.getY() + 1.0, bestPos.getZ() + 0.5); + Vec3 eyePos = player.getEyePosition(); + double dist = eyePos.distanceTo(crystalPos); + boolean hasLos = level.clip(new ClipContext( + eyePos, crystalPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + if (raytrace.getValue() && !hasLos) return; + if (dist > placeRange.getValue()) return; + if (!hasLos && dist > placeWallsRange.getValue()) return; renderPos = bestPos; + lastRenderDamage = plan.damage; + int selected = player.getInventory().getSelectedSlot(); + int crystalSlot = getItemHotbarSlot(Items.END_CRYSTAL); + boolean hasCrystalMain = player.getMainHandItem().getItem() == Items.END_CRYSTAL; + boolean hasCrystalOff = player.getOffhandItem().getItem() == Items.END_CRYSTAL; + InteractionHand hand = InteractionHand.MAIN_HAND; + boolean useAltSwap = false; + int altBackSlot = -1; + boolean visibleSwap = false; + if (hasCrystalOff) { + hand = InteractionHand.OFF_HAND; + } else if (hasCrystalMain) { + } else if (crystalSlot != -1) { + switch (autoSwitch.getValue()) { + case None -> { return; } + case Normal -> { + switchSlot(crystalSlot); + swapTimer.reset(); + visibleSwap = true; + } + case Silent -> { + oldSlot = selected; + switchSlot(crystalSlot); + visibleSwap = true; + } + case AltSwap -> { + useAltSwap = true; + altBackSlot = selected; + serverSwap(crystalSlot); + } + } + } else { + return; + } + if (visibleSwap && autoSwitch.getValue() == SwitchMode.Normal + && swapDelay.getValue() > 0 + && !swapTimer.passedMs(swapDelay.getValue().longValue())) { + return; + } + if (!applyRotations(crystalPos)) { + if (useAltSwap) serverSwap(altBackSlot); + return; + } + BlockHitResult hitResult = placementsMode.getValue() == PlacementMode.NCP + ? buildNcpHitResult(bestPos) + : new BlockHitResult(crystalPos, Direction.UP, bestPos, false); + gameMode.useItemOn(player, hand, hitResult); + swingHand(hand); + pendingPlacePositions.put(bestPos.above(), System.currentTimeMillis()); + CombatPositionCoordinator.reserveCrystalBase( + CombatPositionCoordinator.Source.AUTO_CRYSTAL, + bestPos + ); + if (useAltSwap) serverSwap(altBackSlot); + if (oldSlot != -1 && autoSwitch.getValue() == SwitchMode.Silent) { + switchSlot(oldSlot); + oldSlot = -1; + } + if (facePlaceDelay.getValue() > 0) facePlaceTimer.reset(); + lastActionWasAttack = false; + sincePlaceTick = 0; + if (placeDelay.getValue() > 0) { + placeDelayTimer.reset(); + nextPlaceDelay = computeDelay(placeDelay.getValue(), placeRandom.getValue()); + } + runIdPredict(); + } + + private PlacePlan findBestPlacement() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return null; + List targets = getTargets(); + if (targets.isEmpty()) return null; + double selfHealth = player.getHealth() + player.getAbsorptionAmount(); + if (motionSticky.getValue() && target != null && lastPlacePos != null && lastTargetMotionPos != null) { + double moved = target.position().distanceTo(lastTargetMotionPos); + if (moved <= motionStickyDistance.getValue()) { + Double keepScore = evaluatePlacement(lastPlacePos, targets, player, level, selfHealth); + if (keepScore != null) { + double keepDamage = 0.0; + for (Player t : targets) { + keepDamage = Math.max(keepDamage, calculateDamage( + lastPlacePos.getX() + 0.5, lastPlacePos.getY() + 1.0, lastPlacePos.getZ() + 0.5, + t, extrapolationOffset(t) + )); + } + return new PlacePlan(lastPlacePos, keepDamage); + } + } + } + BlockPos bestPos = null; + double bestScore = -1.0; + double bestDamage = 0.0; + boolean override = false; + if (antiSurround.getValue()) { + BlockPos surroundPos = getAntiSurroundPos(targets, player, level); + if (surroundPos != null) { + double dmg = 0.0; + for (Player t : targets) { + dmg = Math.max(dmg, calculateDamage( + surroundPos.getX() + 0.5, surroundPos.getY() + 1.0, surroundPos.getZ() + 0.5, + t, extrapolationOffset(t) + )); + } + double selfDmg = calculateDamage( + surroundPos.getX() + 0.5, surroundPos.getY() + 1.0, surroundPos.getZ() + 0.5, + player + ); + bestPos = surroundPos; + bestDamage = dmg; + bestScore = scoreCandidate(dmg, selfDmg); + } + } + if (bestPos == null) { + List blocks = getPlaceCandidates(player, targets); + for (BlockPos pos : blocks) { + if (CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CRYSTAL, + pos + )) { + continue; + } + + if (cannotPlaceCrystal(pos)) continue; + if (blockedByUnknownCrystal(pos)) continue; + Vec3 crystalPos = new Vec3(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5); + Vec3 eyePos = player.getEyePosition(); + double dist = eyePos.distanceTo(crystalPos); + boolean hasLos = level.clip(new ClipContext( + eyePos, crystalPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + if (raytrace.getValue() && !hasLos) continue; + if (dist > placeRange.getValue()) continue; + if (!hasLos && dist > placeWallsRange.getValue()) continue; + double selfDamage = calculateDamage(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5, player); + if (selfDamageUnsafe(selfDamage, selfHealth)) continue; + for (Player t : targets) { + double damage = calculateDamage( + pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5, + t, extrapolationOffset(t) + ); + double targetHealth = t.getHealth() + t.getAbsorptionAmount(); + boolean lethal = damage * (1.0 + lethalMultiplier.getValue()) >= targetHealth; + boolean countLethal = lethalCrystals.getValue() > 0 && damage * lethalCrystals.getValue() >= targetHealth; + if (damage < getMinDamage(t) && damage < targetHealth && !lethal && !countLethal) continue; + if (damage >= targetHealth) { + bestPos = pos; + bestDamage = damage; + override = true; + break; + } + double score = placeScore(pos, damage, selfDamage, player, targets); + if (score > bestScore) { + bestScore = score; + bestPos = pos; + bestDamage = damage; + } + } + if (override) break; + } + } + if (bestPos == null) return null; + lastPlacePos = bestPos; + if (target != null) lastTargetMotionPos = target.position(); + return new PlacePlan(bestPos, bestDamage); + } + + private Double evaluatePlacement(BlockPos pos, List targets, LocalPlayer player, ClientLevel level, double selfHealth) { + if (CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CRYSTAL, + pos + )) { + return null; + } + + if (cannotPlaceCrystal(pos)) return null; + if (blockedByUnknownCrystal(pos)) return null; + Vec3 crystalPos = new Vec3(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5); + Vec3 eyePos = player.getEyePosition(); + double dist = eyePos.distanceTo(crystalPos); + boolean hasLos = level.clip(new ClipContext( + eyePos, crystalPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + if (raytrace.getValue() && !hasLos) return null; + if (dist > placeRange.getValue()) return null; + if (!hasLos && dist > placeWallsRange.getValue()) return null; + double selfDamage = calculateDamage(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5, player); + if (selfDamageUnsafe(selfDamage, selfHealth)) return null; + double best = -1.0; + for (Player t : targets) { + double damage = calculateDamage(pos.getX() + 0.5, pos.getY() + 1.0, pos.getZ() + 0.5, t, extrapolationOffset(t)); + double targetHealth = t.getHealth() + t.getAbsorptionAmount(); + boolean lethal = damage * (1.0 + lethalMultiplier.getValue()) >= targetHealth; + boolean countLethal = lethalCrystals.getValue() > 0 && damage * lethalCrystals.getValue() >= targetHealth; + if (damage < getMinDamage(t) && damage < targetHealth && !lethal && !countLethal) continue; + best = Math.max(best, scoreCandidate(damage, selfDamage)); + } + return best < 0 ? null : best; + } + + private void doBasePlace() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + if (player == null || level == null || gameMode == null || target == null) return; + int obbySlot = getItemHotbarSlot(Items.OBSIDIAN); + boolean holdingObby = player.getMainHandItem().getItem() == Items.OBSIDIAN; + if (obbySlot == -1 && !holdingObby) { + baseRenderPos = null; + return; + } + BasePlan plan = findBestBasePosition(); + if (plan == null || plan.pos == null || plan.hitResult == null) { + baseRenderPos = null; + return; + } + + baseRenderPos = plan.pos; + if (!applyRotations(plan.hitResult.getLocation())) { + return; + } + int previousSlot = -1; + if (!holdingObby) { + previousSlot = player.getInventory().getSelectedSlot(); + switchSlot(obbySlot); + } + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, plan.hitResult); + swingHand(InteractionHand.MAIN_HAND); + if (previousSlot != -1) { + switchSlot(previousSlot); + } + basePlaceTimer.reset(); + } + + private BasePlan findBestBasePosition() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) return null; + + List targets = getTargets(); + + if (targets.isEmpty()) return null; + + double selfHealth = player.getHealth() + player.getAbsorptionAmount(); + double range = basePlaceRange.getValue(); + + BlockPos bestPos = null; + BlockHitResult bestHit = null; + double bestDamage = 0.0; + double bestScore = -1.0; + + List blocks = getSphere( + player.blockPosition(), + (float) range, + (int) range, + false, + true, + 0 + ); + + for (BlockPos pos : blocks) { + if (!level.getBlockState(pos).isAir()) continue; + if (!level.getBlockState(pos.above()).isAir()) continue; + if (oldVersion.getValue() && !level.getBlockState(pos.above(2)).isAir()) continue; + if (worldBorder.getValue() && !level.getWorldBorder().isWithinBounds(pos)) continue; + if (isBaseBlockedByEntity(pos)) continue; + + PlaceResult placeResult = computePlaceResult(pos, strictDirection.getValue()); + + if (placeResult == null) continue; + + Vec3 eyePos = player.getEyePosition(); + double dist = eyePos.distanceTo(placeResult.hitVec()); + + if (dist > range) continue; + + if (raytrace.getValue()) { + boolean hasLos = level.clip(new ClipContext( + eyePos, + placeResult.hitVec(), + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() != HitResult.Type.BLOCK; + + if (!hasLos) continue; + } + + double cx = pos.getX() + 0.5; + double cy = pos.getY() + 1.0; + double cz = pos.getZ() + 0.5; + + double selfDamage = calculateDamage(cx, cy, cz, player); + + if (selfDamageUnsafe(selfDamage, selfHealth)) continue; + + for (Player t : targets) { + if (!isValidBasePlaceHeight(pos, t)) continue; + + double damage = calculateDamage(cx, cy, cz, t, extrapolationOffset(t)); + + if (damage < baseMinDamage.getValue()) continue; + + double score = scoreCandidate(damage, selfDamage); + + if (isPreferredBaseHeight(pos, t)) { + score *= 1.25; + } + + if (score > bestScore) { + bestScore = score; + bestPos = pos; + bestDamage = damage; + bestHit = new BlockHitResult( + placeResult.hitVec(), + placeResult.direction(), + placeResult.neighbor(), + false + ); + } + } + } + + if (bestPos == null) return null; + + return new BasePlan(bestPos, bestHit, bestDamage); + } + + private boolean isValidBasePlaceHeight(BlockPos pos, Player target) { + AABB box = target.getBoundingBox(); + + int lowerY = Mth.floor(box.minY); + int headY = Mth.floor(box.maxY); + + if (pos.getY() >= headY) return false; + if (pos.getY() < lowerY) return true; + + return basePlaceExtend.getValue() && pos.getY() == lowerY; + } + + private boolean isPreferredBaseHeight(BlockPos pos, Player target) { + return pos.getY() < Mth.floor(target.getBoundingBox().minY); + } + + private boolean isBaseBlockedByEntity(BlockPos pos) { + ClientLevel level = mc.level; + if (level == null) return true; + AABB box = new AABB(pos); + return !level.getEntitiesOfClass(Entity.class, box, e -> !(e instanceof ItemEntity) && !(e instanceof EndCrystal)).isEmpty(); + } + + private double scoreCandidate(double targetDamage, double selfDamage) { + if (!bestRatio.getValue()) return targetDamage; + double bias = Math.max(0.1, ratioBias.getValue()); + return targetDamage * (targetDamage + bias) / (selfDamage + bias); + } + + private BlockPos getAntiSurroundPos(List targets, LocalPlayer player, ClientLevel level) { + double threshold = antiSurroundBreak.getValue(); + double selfHealth = player.getHealth() + player.getAbsorptionAmount(); + Vec3 eyePos = player.getEyePosition(); + BlockPos best = null; + double bestPercent = threshold; + for (Player t : targets) { + BlockPos feet = t.blockPosition(); + BlockPos[] surround = { feet.north(), feet.south(), feet.east(), feet.west(), feet.below() }; + for (BlockPos s : surround) { + double percent = getBreakPercent(s); + if (percent < threshold) continue; + + if (CombatPositionCoordinator.isCrystalBaseReservedByOther( + CombatPositionCoordinator.Source.AUTO_CRYSTAL, + s + )) { + continue; + } + + if (cannotPlaceCrystal(s)) continue; + if (blockedByUnknownCrystal(s)) continue; + Vec3 crystalPos = new Vec3(s.getX() + 0.5, s.getY() + 1.0, s.getZ() + 0.5); + double dist = eyePos.distanceTo(crystalPos); + boolean hasLos = level.clip(new ClipContext( + eyePos, crystalPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )).getType() == HitResult.Type.MISS; + if (raytrace.getValue() && !hasLos) continue; + if (dist > placeRange.getValue()) continue; + if (!hasLos && dist > placeWallsRange.getValue()) continue; + double selfDamage = calculateDamage(s.getX() + 0.5, s.getY() + 1.0, s.getZ() + 0.5, player); + if (selfDamageUnsafe(selfDamage, selfHealth)) continue; + if (percent >= bestPercent) { + bestPercent = percent; + best = s; + } + } + } + return best; + } + + private double getBreakPercent(BlockPos pos) { + double percent = 0.0; + try { + Object lr = mc.levelRenderer; + if (LEVEL_RENDERER_DESTROY_FIELD != null) { + Object mapObj = LEVEL_RENDERER_DESTROY_FIELD.get(lr); + if (mapObj instanceof Map map) { + for (Object value : map.values()) { + if (value instanceof Collection col) { + for (Object o : col) { + if (o instanceof BlockDestructionProgress bdp && bdp.getPos().equals(pos)) { + percent = Math.max(percent, (bdp.getProgress() / 9.0) * 100.0); + } + } + } + } + } + } + } catch (Exception ignored) { } + try { + MultiPlayerGameMode gm = mc.gameMode; + if (gm != null && GM_DESTROY_POS_FIELD != null && GM_DESTROY_PROGRESS_FIELD != null) { + Object p = GM_DESTROY_POS_FIELD.get(gm); + if (p instanceof BlockPos bp && bp.equals(pos)) { + float prog = GM_DESTROY_PROGRESS_FIELD.getFloat(gm); + if (prog > 0f) percent = Math.max(percent, prog * 100.0); + } + } + } catch (Exception ignored) { } + return percent; + } + + private void runIdPredict() { + if (!idPredict.getValue()) return; + if (ENTITY_ID_FIELD == null) return; + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return; + boolean holdingXp = player.getMainHandItem().getItem() == Items.EXPERIENCE_BOTTLE + || player.getOffhandItem().getItem() == Items.EXPERIENCE_BOTTLE; + if (antiKick.getValue() && (holdingXp || kickTicks <= kickThreshold.getValue())) { + kickTicks++; + return; + } + int base = trackedHighestId; + if (base == Integer.MIN_VALUE) { + kickTicks++; + return; + } + for (int i = 1 - offset.getValue(); i < predictions.getValue(); i++) { + int id = base + i; + if (attackedThisTick.contains(id)) continue; + Entity occupant = level.getEntity(id); + if (occupant != null && !(occupant instanceof EndCrystal)) continue; + try { + ServerboundInteractPacket packet = ServerboundInteractPacket.createAttackPacket(player, player.isShiftKeyDown()); + ENTITY_ID_FIELD.setInt(packet, id); + player.connection.send(packet); + } catch (Exception ignored) { + continue; + } + if (predictSwing.getValue() == PredictSwingMode.Strict) { + player.connection.send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND)); + } + attackedThisTick.add(id); + } + if (predictSwing.getValue() == PredictSwingMode.Normal) { + player.connection.send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND)); + } + if (fast.getValue()) { + trackedHighestId += Math.max(1, predictions.getValue()); + } + kickTicks++; + } + + private BlockHitResult buildNcpHitResult(BlockPos pos) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + PlaceResult placeResult = computePlaceResult(pos, strictDirection.getValue()); + if (placeResult != null) { + return new BlockHitResult(placeResult.hitVec(), placeResult.direction(), placeResult.neighbor(), false); + } + Direction bestDir = Direction.UP; + if (player != null && level != null) { + Vec3 eyePos = player.getEyePosition(); + Vec3 blockCenter = new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); + Vec3 toEye = eyePos.subtract(blockCenter).normalize(); + double bestDot = Double.NEGATIVE_INFINITY; + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + if (!level.getBlockState(neighbor).isAir()) continue; + Vec3 dirVec = new Vec3(dir.getStepX(), dir.getStepY(), dir.getStepZ()); + double dot = toEye.dot(dirVec); + if (dot > bestDot) { + bestDot = dot; + bestDir = dir; + } + } + } + Vec3 faceHit = new Vec3( + pos.getX() + 0.5 + bestDir.getStepX() * 0.5, + pos.getY() + 0.5 + bestDir.getStepY() * 0.5, + pos.getZ() + 0.5 + bestDir.getStepZ() * 0.5 + ); + return new BlockHitResult(faceHit, bestDir, pos, false); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + if (rm == null) return true; + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void clearAutoCrystalRotations() { + RotationManager rm = nolongerhuman.rotationManager; + if (rm == null) { + return; + } + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void swingHand(InteractionHand hand) { + LocalPlayer player = mc.player; + if (player == null) return; + switch (swing.getValue()) { + case Default -> player.swing(hand); + case Mainhand -> player.swing(InteractionHand.MAIN_HAND); + case Offhand -> player.swing(InteractionHand.OFF_HAND); + case Both -> { + player.swing(InteractionHand.MAIN_HAND); + player.swing(InteractionHand.OFF_HAND); + } + case Packet -> player.connection.send(new ServerboundSwingPacket(hand)); + case None -> { } + } + } + + private double getMinDamage(Player t) { + LocalPlayer player = mc.player; + if (chestBreak.getValue() && hasObsidianDrop(t) && (player == null || !hasObsidianDrop(player))) return 2.0; + if (facePlaceMode.getValue() == FacePlaceMode.None) return minimumDamage.getValue(); + boolean faceReady = facePlaceDelay.getValue() <= 0 + || facePlaceTimer.passedMs(facePlaceDelay.getValue().longValue() * 50L); + if (facePlaceMode.getValue() == FacePlaceMode.Always && faceReady) return 1.5; + if (facePlaceMode.getValue() == FacePlaceMode.Dynamic && faceReady) { + if (healthPlace.getValue() && t.getHealth() + t.getAbsorptionAmount() <= health.getValue()) return 1.5; + if (armorPlace.getValue()) { + for (EquipmentSlot slot : ARMOR_SLOTS) { + ItemStack stack = t.getItemBySlot(slot); + if (stack.isEmpty()) continue; + float pct = ((float) (stack.getMaxDamage() - stack.getDamageValue()) / (float) stack.getMaxDamage()) * 100f; + if (pct <= percentage.getValue()) return 1.5; + } + } + } + return minimumDamage.getValue(); + } + + private boolean hasObsidianDrop(Player player) { + ClientLevel level = mc.level; + + if (level == null || player == null) { + return false; + } + + AABB box = new AABB(player.blockPosition()).inflate(1.0D); + + List entities = new ArrayList<>(); + + for (Entity entity : level.entitiesForRendering()) { + entities.add(entity); + } + + for (Entity entity : entities) { + if (!(entity instanceof ItemEntity item)) { + continue; + } + + if (!item.isAlive()) { + continue; + } + + if (!box.intersects(item.getBoundingBox())) { + continue; + } + + ItemStack stack = item.getItem(); + + if (stack.getItem() == Items.OBSIDIAN && stack.getCount() >= 8 && item.tickCount <= 4) { + return true; + } + } + + return false; + } + private Vec3 extrapolationOffset(Entity entity) { + int ticks = predictionTicks.getValue(); + + if (ticks <= 0) { + return Vec3.ZERO; + } + + PredictionState state = buildPredictionState(entity); + Vec3 velocity = state.velocity(); + + double horizontalSpeed = Math.hypot(velocity.x, velocity.z); + + if (DEFAULT_PREDICT_ONLY_MOVING && horizontalSpeed < DEFAULT_PREDICT_MOVE_THRESHOLD) { + return Vec3.ZERO; + } + + double linearWeight = DEFAULT_PREDICT_LINEAR_WEIGHT; + double adaptiveWeight = DEFAULT_PREDICT_ADAPTIVE_WEIGHT; + double strafeWeight = DEFAULT_PREDICT_STRAFE_WEIGHT; + + double totalWeight = linearWeight + adaptiveWeight + strafeWeight; + + if (totalWeight <= 0.0) { + return Vec3.ZERO; + } + + Vec3 linear = predictLinear(velocity, ticks); + Vec3 adaptive = predictAdaptive(state, ticks); + Vec3 strafe = predictStrafe(entity, ticks); + + double x = ( + linear.x * linearWeight + + adaptive.x * adaptiveWeight + + strafe.x * strafeWeight + ) / totalWeight; + + double y = ( + linear.y * linearWeight + + adaptive.y * adaptiveWeight + + strafe.y * strafeWeight + ) / totalWeight; + + double z = ( + linear.z * linearWeight + + adaptive.z * adaptiveWeight + + strafe.z * strafeWeight + ) / totalWeight; + + return new Vec3(x, DEFAULT_PREDICT_VERTICAL ? y : 0.0, z); + } + + private double blend(double current, double history, double factor) { + factor = Mth.clamp(factor, 0.0, 1.0); + return current * (1.0 - factor) + history * factor; + } + + private int findToolSlot() { + LocalPlayer player = mc.player; + if (player == null) return -1; + for (int i = 0; i < 9; i++) { + Item item = player.getInventory().getItem(i).getItem(); + if (isSword(item) || item instanceof AxeItem) return i; + } + return -1; + } + + private boolean isSword(Item item) { + return item == Items.WOODEN_SWORD || item == Items.STONE_SWORD + || item == Items.IRON_SWORD || item == Items.GOLDEN_SWORD + || item == Items.DIAMOND_SWORD || item == Items.NETHERITE_SWORD; + } + + private boolean cannotPlaceCrystal(BlockPos pos) { + ClientLevel level = mc.level; + if (level == null) return true; + if (worldBorder.getValue() && !level.getWorldBorder().isWithinBounds(pos)) return true; + BlockState state = level.getBlockState(pos); + var block = state.getBlock(); + if (block != Blocks.OBSIDIAN && block != Blocks.BEDROCK) return true; + if (blockDestruction.getValue()) { + if (state.getCollisionShape(level, pos).isEmpty()) return true; + } + if (!level.getBlockState(pos.above()).isAir()) return true; + if (oldVersion.getValue() && !level.getBlockState(pos.above(2)).isAir()) return true; + int height = oldVersion.getValue() ? 2 : 1; + AABB crystalBB = new AABB( + pos.getX(), pos.getY() + 1, pos.getZ(), + pos.getX() + 1, pos.getY() + 1 + height, pos.getZ() + 1 + ); + return !level.getEntitiesOfClass(Entity.class, crystalBB, e -> !(e instanceof EndCrystal)).isEmpty(); + } + + private List getTargets() { + List targets = new ArrayList<>(); + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return targets; + for (Player p : level.players()) { + if (p == player || !p.isAlive()) continue; + if (nolongerhuman.friendManager.isFriend(p)) continue; + if (player.distanceTo(p) > enemyRange.getValue()) continue; + if (antiNaked.getValue() && isNaked(p)) continue; + targets.add(p); + } + return targets; + } + + private Player getTarget() { + LocalPlayer player = mc.player; + if (player == null) return null; + List targets = getTargets(); + if (targets.isEmpty()) return null; + switch (targetMode.getValue()) { + case LowestHealth -> { + Player best = null; + double min = Double.MAX_VALUE; + for (Player p : targets) { + double hp = p.getHealth() + p.getAbsorptionAmount(); + if (hp < min) { + min = hp; + best = p; + } + } + return best; + } + case HighestDamage -> { + Player best = null; + double max = -1; + for (Player p : targets) { + double d = bestPossibleDamage(p); + if (d > max) { + max = d; + best = p; + } + } + return best != null ? best : targets.get(0); + } + default -> { + Player nearest = null; + double minDist = Double.MAX_VALUE; + for (Player p : targets) { + double dist = player.distanceTo(p); + if (dist < minDist) { + minDist = dist; + nearest = p; + } + } + return nearest; + } + } + } + + private double bestPossibleDamage(Player t) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return 0; + double max = 0; + double maxRange = Math.max(attackRange.getValue(), placeRange.getValue()); + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof EndCrystal crystal)) continue; + if (player.distanceTo(crystal) > maxRange) continue; + double d = calculateDamage(crystal.getX(), crystal.getY(), crystal.getZ(), t, extrapolationOffset(t)); + if (d > max) max = d; + } + return max; + } + + private boolean isNaked(Player player) { + for (EquipmentSlot slot : ARMOR_SLOTS) { + if (!player.getItemBySlot(slot).isEmpty()) return false; + } + return true; + } + + public double calculateDamage(double x, double y, double z, Entity entity) { + return calculateDamage(x, y, z, entity, Vec3.ZERO); + } + + public double calculateDamage(double x, double y, double z, Entity entity, Vec3 offset) { + float explosionSize = 12.0f; + Vec3 entityPos = entity.position().add(offset); + double dist = entityPos.distanceTo(new Vec3(x, y, z)) / explosionSize; + if (dist > 1.0) return 0; + double exposure = getExposure(new Vec3(x, y, z), entity, offset); + double impact = (1.0 - dist) * exposure; + double damage = (impact * impact + impact) / 2.0 * 7.0 * explosionSize + 1.0; + damage = getDamageMultipliedByDifficulty(damage); + if (entity instanceof LivingEntity living) { + damage = getDamageLeft( + (float) damage, + (float) living.getArmorValue(), + (float) living.getAttributeValue(Attributes.ARMOR_TOUGHNESS) + ); + int epas = getBlastProtectionLevel(living); + if (epas > 0) { + damage *= (1.0f - Math.min(20.0f, (float) epas) / 25.0f); + } + if (resistanceCalc.getValue()) { + int levelRes = getResistanceLevel(living); + if (levelRes > 0) { + int reduction = levelRes * 5; + damage = damage * (25.0 - reduction) / 25.0; + if (damage < 0) damage = 0; + } + } + } + return damage; + } + + private int getBlastProtectionLevel(LivingEntity living) { + int total = 0; + for (EquipmentSlot slot : ARMOR_SLOTS) { + total += EnchantmentUtil.getLevel(Enchantments.BLAST_PROTECTION, slot, living); + } + return total; + } + + private int getResistanceLevel(LivingEntity living) { + try { + for (MobEffectInstance inst : living.getActiveEffects()) { + String id = inst.getDescriptionId().toLowerCase(Locale.ROOT); + if (id.contains("resistance") && !id.contains("fire")) { + return inst.getAmplifier() + 1; + } + } + } catch (Exception ignored) { } + return 0; + } + + public float getExposure(Vec3 source, Entity entity, Vec3 offset) { + ClientLevel level = mc.level; + if (level == null) return 0.0f; + AABB box = entity.getBoundingBox().move(offset); + double d0 = 1.0 / ((box.maxX - box.minX) * 2.0 + 1.0); + double d1 = 1.0 / ((box.maxY - box.minY) * 2.0 + 1.0); + double d2 = 1.0 / ((box.maxZ - box.minZ) * 2.0 + 1.0); + double d3 = (1.0 - Math.floor(1.0 / d0) * d0) / 2.0; + double d4 = (1.0 - Math.floor(1.0 / d2) * d2) / 2.0; + if (d0 < 0.0 || d1 < 0.0 || d2 < 0.0) return 0.0f; + int hit = 0, total = 0; + for (float f = 0.0f; f <= 1.0f; f += (float) d0) { + for (float f1 = 0.0f; f1 <= 1.0f; f1 += (float) d1) { + for (float f2 = 0.0f; f2 <= 1.0f; f2 += (float) d2) { + Vec3 point = new Vec3( + Mth.lerp(f, box.minX, box.maxX) + d3, + Mth.lerp(f1, box.minY, box.maxY), + Mth.lerp(f2, box.minZ, box.maxZ) + d4 + ); + if (level.clip(new ClipContext( + point, source, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + entity + )).getType() == HitResult.Type.MISS) hit++; + total++; + } + } + } + return total == 0 ? 0.0f : (float) hit / (float) total; + } + + private double getDamageMultipliedByDifficulty(double damage) { + ClientLevel level = mc.level; + if (level == null) return damage; + return switch (level.getDifficulty()) { + case PEACEFUL -> 0; + case EASY -> Math.min(damage / 2.0 + 1.0, damage); + case HARD -> damage * 1.5; + default -> damage; + }; + } + + private float getDamageLeft(float damage, float armor, float armorToughness) { + float f = 2.0f + armorToughness / 4.0f; + float f1 = Mth.clamp(armor - damage / f, armor * 0.2f, 20.0f); + return damage * (1.0f - f1 / 25.0f); + } + + public List getSphere(BlockPos pos, float r, int h, boolean hollow, boolean sphere, int plusY) { + List circleBlocks = new ArrayList<>(); + int cx = pos.getX(); + int cy = pos.getY(); + int cz = pos.getZ(); + int radius = (int) Math.ceil(r); + for (int x = cx - radius; x <= cx + radius; x++) { + for (int z = cz - radius; z <= cz + radius; z++) { + int yStart = sphere ? cy - radius : cy; + int yEnd = sphere ? cy + radius : cy + h; + for (int y = yStart; y <= yEnd; y++) { + double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + + (sphere ? (cy - y) * (cy - y) : 0); + if (dist < r * r && !(hollow && dist < (r - 1) * (r - 1))) { + circleBlocks.add(new BlockPos(x, y + plusY, z)); + } + } + } + } + return circleBlocks; + } + + + + @Override + public void onRender3D(Render3DEvent event) { + if (nullCheck()) return; + + if (renderMode.getValue() == RenderMode.None) { + crystalRenderAnim.reset(); + baseRenderAnim.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + renderAnimatedBox(stack, crystalRenderAnim, renderPos); + renderAnimatedBox(stack, baseRenderAnim, baseRenderPos); + } + + private record PlaceResult(BlockPos neighbor, Direction direction, Vec3 hitVec) {} + + private record PredictionState(Vec3 velocity, Vec3 acceleration, double turn) { + } private void renderAnimatedBox(PoseStack stack, RenderAnimState state, BlockPos pos) { + if (pos == null) { + state.reset(); + return; + } + + AABB target = new AABB(pos); + + updateRenderAnimation(state, pos, target); + + if (renderAnimation.getValue() == RenderAnimationMode.Fade) { + renderFadeBox(stack, state); + return; + } + + AABB box = getMovingRenderBox(state); + + if (box == null) { + return; + } + + drawRenderBox(stack, box, fillColor.getValue(), outlineColor.getValue()); + } + + private void updateRenderAnimation(RenderAnimState state, BlockPos pos, AABB newTarget) { + RenderAnimationMode mode = renderAnimation.getValue(); + + if (mode == RenderAnimationMode.None || renderAnimationTime.getValue() <= 0) { + state.startBox = newTarget; + state.currentBox = newTarget; + state.targetBox = newTarget; + state.fadeOutBox = null; + state.fadeInBox = newTarget; + state.lastPos = pos; + state.animationStart = System.currentTimeMillis(); + return; + } + + if (state.targetBox == null || state.lastPos == null || !state.lastPos.equals(pos)) { + if (mode == RenderAnimationMode.Fade) { + state.fadeOutBox = state.targetBox; + state.fadeInBox = newTarget; + + state.startBox = newTarget; + state.currentBox = newTarget; + state.targetBox = newTarget; + } else { + state.startBox = state.currentBox == null ? newTarget : state.currentBox; + state.targetBox = newTarget; + + state.fadeOutBox = null; + state.fadeInBox = null; + } + + state.lastPos = pos; + state.animationStart = System.currentTimeMillis(); + } + } + + private AABB getMovingRenderBox(RenderAnimState state) { + if (state.targetBox == null) { + return null; + } + + if (renderAnimation.getValue() == RenderAnimationMode.None || renderAnimationTime.getValue() <= 0) { + state.currentBox = state.targetBox; + return state.currentBox; + } + + if (state.startBox == null) { + state.startBox = state.targetBox; + } + + long now = System.currentTimeMillis(); + + double progress = (double) (now - state.animationStart) / (double) renderAnimationTime.getValue(); + progress = clamp(progress, 0.0, 1.0); + + double eased = ease(progress, renderAnimation.getValue()); + + state.currentBox = lerp(state.startBox, state.targetBox, eased); + + if (progress >= 1.0) { + state.currentBox = state.targetBox; + state.startBox = state.targetBox; + } + + return state.currentBox; + } + + private void renderFadeBox(PoseStack stack, RenderAnimState state) { + if (state.targetBox == null) { + return; + } + + if (renderAnimationTime.getValue() <= 0) { + drawRenderBox(stack, state.targetBox, fillColor.getValue(), outlineColor.getValue()); + + state.fadeOutBox = null; + state.fadeInBox = state.targetBox; + state.currentBox = state.targetBox; + + return; + } + + long now = System.currentTimeMillis(); + + double progress = (double) (now - state.animationStart) / (double) renderAnimationTime.getValue(); + progress = clamp(progress, 0.0, 1.0); + + double eased = ease(progress, RenderAnimationMode.EaseOut); + double fadeOutAlpha = 1.0 - eased; + + if (state.fadeOutBox != null && fadeOutAlpha > 0.01) { + drawRenderBox( + stack, + state.fadeOutBox, + withAlphaMultiplier(fillColor.getValue(), fadeOutAlpha), + withAlphaMultiplier(outlineColor.getValue(), fadeOutAlpha) + ); + } + + if (state.fadeInBox != null && eased > 0.01) { + drawRenderBox( + stack, + state.fadeInBox, + withAlphaMultiplier(fillColor.getValue(), eased), + withAlphaMultiplier(outlineColor.getValue(), eased) + ); + } + + if (progress >= 1.0) { + state.fadeOutBox = null; + state.fadeInBox = state.targetBox; + state.currentBox = state.targetBox; + } + } + + private void drawRenderBox(PoseStack stack, AABB box, Color fill, Color outline) { + if (renderMode.getValue() == RenderMode.Fill || renderMode.getValue() == RenderMode.Both) { + RenderUtil.drawBoxFilled(stack, box, fill); + } + + if (renderMode.getValue() == RenderMode.Outline || renderMode.getValue() == RenderMode.Both) { + RenderUtil.drawBox(stack, box, outline, renderLineWidth.getValue()); + } + } + + private AABB lerp(AABB from, AABB to, double progress) { + return new AABB( + lerp(from.minX, to.minX, progress), + lerp(from.minY, to.minY, progress), + lerp(from.minZ, to.minZ, progress), + lerp(from.maxX, to.maxX, progress), + lerp(from.maxY, to.maxY, progress), + lerp(from.maxZ, to.maxZ, progress) + ); + } + + private double lerp(double from, double to, double progress) { + return from + (to - from) * progress; + } + + private double ease(double progress, RenderAnimationMode mode) { + progress = clamp(progress, 0.0, 1.0); + + return switch (mode) { + case None, Linear, Fade -> progress; + + case EaseIn -> progress * progress * progress; + + case EaseOut -> { + double inverse = 1.0 - progress; + yield 1.0 - inverse * inverse * inverse; + } + + case EaseInOut -> { + if (progress < 0.5) { + yield 4.0 * progress * progress * progress; + } + + double value = -2.0 * progress + 2.0; + yield 1.0 - (value * value * value) / 2.0; + } + + case Elastic -> { + if (progress == 0.0 || progress == 1.0) { + yield progress; + } + + double c4 = (2.0 * Math.PI) / 3.0; + yield Math.pow(2.0, -10.0 * progress) * Math.sin((progress * 10.0 - 0.75) * c4) + 1.0; + } + }; + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = clamp(multiplier, 0.0, 1.0); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + private double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private static class RenderAnimState { + private AABB startBox = null; + private AABB currentBox = null; + private AABB targetBox = null; + + private AABB fadeOutBox = null; + private AABB fadeInBox = null; + + private BlockPos lastPos = null; + private long animationStart = 0L; + + private void reset() { + startBox = null; + currentBox = null; + targetBox = null; + + fadeOutBox = null; + fadeInBox = null; + + lastPos = null; + animationStart = 0L; + } + } + + private PlaceResult computePlaceResult(BlockPos pos, boolean strictDirection) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + if (level == null || player == null) return null; + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = null; + Vec3 bestHit = null; + double bestDist = Double.MAX_VALUE; + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState ns = level.getBlockState(neighbor); + if (ns.isAir() || ns.canBeReplaced()) continue; + if (ns.getCollisionShape(level, neighbor).isEmpty()) continue; + Direction side = dir.getOpposite(); + Vec3 hit = Vec3.atCenterOf(neighbor) + .add(side.getStepX() * 0.5, side.getStepY() * 0.5, side.getStepZ() * 0.5); + double dist = eye.distanceTo(hit); + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + if (!strictDirection && bestSide != null) break; + } + if (bestSide == null) return null; + return new PlaceResult(bestNeighbor, bestSide, bestHit); + } + + private static class PlacePlan { + final BlockPos pos; + final double damage; + + PlacePlan(BlockPos pos, double damage) { + this.pos = pos; + this.damage = damage; + } + } + + private static class BasePlan { + final BlockPos pos; + final BlockHitResult hitResult; + final double damage; + + BasePlan(BlockPos pos, BlockHitResult hitResult, double damage) { + this.pos = pos; + this.hitResult = hitResult; + this.damage = damage; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoMace.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoMace.java new file mode 100644 index 0000000..e7fe36f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoMace.java @@ -0,0 +1,876 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.render.AuraCircles; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +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.animal.Animal; +import net.minecraft.world.entity.monster.Monster; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class AutoMace extends Module { + public enum Sorting { + Distance, + FOV + } + + public enum SwitchMode { + None, + Normal, + Silent, + AltSwap + } + + public enum RotateType { + Auto, + Head, + Torso, + Feet, + Closest + } + + private enum Phase { + Acquire, + EquipElytra, + StartFlying, + Retreat, + Dive, + Attack + } + + private static final String ROT_ID = "automace"; + private static final int ROT_PRIORITY = 6; + + private static final double PREDICTION_MS = 120.0; + private static final double ELYTRA_PREDICTION_SCALE = 1.45; + private static final double AIM_Y_OFFSET = -0.2; + + private static final double MIN_DIRECTION_LENGTH = 0.001; + private static final double ELYTRA_STEER_BLEND = 0.38; + private static final double GROUND_STEER_BLEND = 0.55; + + public final Setting targetRange = num("TargetRange", 32.0, 4.0, 80.0); + public final Setting attackRange = num("AttackRange", 5.0, 1.0, 6.0); + public final Setting wallsRange = num("WallsRange", 3.5, 1.0, 6.0); + public final Setting retreatDistance = num("RetreatDistance", 13.0, 4.0, 40.0); + public final Setting diveStartDistance = num("DiveStartDistance", 10.0, 3.0, 40.0); + public final Setting minHeightAbove = num("MinHeightAbove", 5.0, 0.0, 30.0); + public final Setting retreatHeight = num("RetreatHeight", 8.0, 1.0, 30.0); + public final Setting fireworkDelay = num("FireworkDelay", 900, 100, 5000); + public final Setting attackCooldown = num("AttackCooldown", 250, 0, 2000); + private final Setting sorting = mode("Sorting", Sorting.Distance); + private final Setting switchMode = mode("Switch", SwitchMode.Silent); + private final Setting rotateType = mode("RotateType", RotateType.Closest); + private final Setting players = bool("Players", true); + private final Setting mobs = bool("Mobs", false); + private final Setting animals = bool("Animals", false); + private final Setting vehicles = bool("Vehicles", false); + private final Setting targetFriends = bool("TargetFriends", false); + private final Setting rotate = bool("Rotate", true); + private final Setting useFireworks = bool("Fireworks", true); + private final Setting autoElytra = bool("AutoElytra", true); + private final Setting packetAttack = bool("PacketAttack", true); + private final Setting swing = bool("Swing", true); + private final Setting requireFall = bool("RequireFall", true); + private final Setting minFallDistance = num("MinFall", 1.5f, 0.0f, 12.0f); + private final Setting axeFallback = bool("AxeFallback", false); + private final Setting autoMove = bool("AutoMove", true); + private final Setting takeoffSpeed = num("TakeoffSpeed", 0.42, 0.1, 2.0); + private final Setting retreatSpeed = num("RetreatSpeed", 1.35, 0.1, 3.0); + private final Setting diveSpeed = num("DiveSpeed", 1.75, 0.1, 4.0); + private final Setting approachSpeed = num("ApproachSpeed", 1.45, 0.1, 4.0); + private final Setting verticalSpeed = num("VerticalSpeed", 1.15, 0.1, 3.0); + private final Setting autoSprint = bool("AutoSprint", true); + + private Entity target = null; + private Phase phase = Phase.Acquire; + + private long lastFireworkMs = 0L; + private long lastAttackMs = 0L; + + private int invSwapSlot = -1; + + public AutoMace() { + super("AutoMace", "Uses elytra and fireworks to mace targets", Category.COMBAT); + } + + @Override + public void onDisable() { + target = null; + phase = Phase.Acquire; + lastFireworkMs = 0L; + lastAttackMs = 0L; + invSwapSlot = -1; + clearRotations(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!player.isAlive() || player.isSpectator()) { + resetState(); + return; + } + + if (autoSprint.getValue()) { + player.setSprinting(true); + } + + int weaponSlot = findWeaponSlot(); + + if (weaponSlot == -1) { + resetState(); + return; + } + + target = findTarget(player, level); + + if (target == null || !target.isAlive()) { + resetState(); + return; + } + + if (autoElytra.getValue() && !isWearingElytra(player)) { + phase = Phase.EquipElytra; + equipElytra(player, gameMode); + return; + } + + if (!player.isFallFlying()) { + phase = Phase.StartFlying; + startElytraFlight(player, target); + return; + } + + double distance = distanceToTarget(player, target); + double heightAbove = player.getY() - target.getY(); + + if (distance < retreatDistance.getValue() || heightAbove < minHeightAbove.getValue()) { + phase = Phase.Retreat; + doRetreat(player, gameMode, target); + return; + } + + if (distance > diveStartDistance.getValue()) { + phase = Phase.Dive; + doDive(player, gameMode, target); + return; + } + + phase = Phase.Attack; + doAttackPhase(player, gameMode, target, weaponSlot); + } + + private void resetState() { + target = null; + phase = Phase.Acquire; + clearRotations(); + } + + private Entity findTarget(LocalPlayer self, ClientLevel level) { + List entities = new ArrayList<>(); + Vec3 eyes = self.getEyePosition(); + + for (Entity entity : level.entitiesForRendering()) { + if (entity == self) { + continue; + } + + if (!entity.isAlive() || entity.isSpectator()) { + continue; + } + + if (!isValidType(entity)) { + continue; + } + + if (entity instanceof Player player) { + if (!targetFriends.getValue() && nolongerhuman.friendManager.isFriend(player)) { + continue; + } + } + + double distance = eyes.distanceTo(getClosestPointOnBox(entity.getBoundingBox(), eyes)); + + if (distance > targetRange.getValue()) { + continue; + } + + entities.add(entity); + } + + entities.sort(getComparator(self)); + + return entities.isEmpty() ? null : entities.get(0); + } + + private Comparator getComparator(LocalPlayer self) { + Vec3 eyes = self.getEyePosition(); + + if (sorting.getValue() == Sorting.FOV) { + return Comparator.comparingDouble(entity -> angleTo(self, entity)); + } + + return Comparator.comparingDouble(entity -> + eyes.distanceToSqr(getClosestPointOnBox(entity.getBoundingBox(), eyes)) + ); + } + + private boolean isValidType(Entity entity) { + if (entity instanceof Player) { + return players.getValue(); + } + + if (entity instanceof Monster) { + return mobs.getValue(); + } + + if (entity instanceof Animal) { + return animals.getValue(); + } + + return vehicles.getValue() && isVehicle(entity); + } + + private boolean isVehicle(Entity entity) { + String type = entity.getType().toString().toLowerCase(); + + return type.contains("boat") || type.contains("minecart"); + } + + private void equipElytra(LocalPlayer player, MultiPlayerGameMode gameMode) { + int elytraSlot = findItemSlot(Items.ELYTRA); + + if (elytraSlot == -1) { + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + SwitchData switchData = doSwitch(player, elytraSlot, oldSlot); + + if (!switchData.success()) { + return; + } + + gameMode.useItem(player, InteractionHand.MAIN_HAND); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(player, switchData); + } + + private void startElytraFlight(LocalPlayer player, Entity target) { + if (player.onGround()) { + if (autoMove.getValue() && target != null) { + Vec3 takeoffPoint = getRetreatPoint(player, target); + steerToward(player, takeoffPoint, takeoffSpeed.getValue(), verticalSpeed.getValue()); + } + + player.jumpFromGround(); + return; + } + + if (autoMove.getValue() && target != null) { + Vec3 takeoffPoint = getRetreatPoint(player, target); + steerToward(player, takeoffPoint, takeoffSpeed.getValue(), verticalSpeed.getValue()); + } + + player.connection.send(new ServerboundPlayerCommandPacket( + player, + ServerboundPlayerCommandPacket.Action.START_FALL_FLYING + )); + } + + private void doRetreat(LocalPlayer player, MultiPlayerGameMode gameMode, Entity target) { + Vec3 retreatPoint = getRetreatPoint(player, target); + + if (rotationFailed(retreatPoint)) { + return; + } + + if (autoMove.getValue()) { + steerToward(player, retreatPoint, retreatSpeed.getValue(), verticalSpeed.getValue()); + } + + useFireworkIfReady(player, gameMode); + } + + private void doDive(LocalPlayer player, MultiPlayerGameMode gameMode, Entity target) { + Vec3 divePoint = getDivePoint(player, target); + + if (rotationFailed(divePoint)) { + return; + } + + if (autoMove.getValue()) { + steerToward(player, divePoint, diveSpeed.getValue(), verticalSpeed.getValue()); + } + + useFireworkIfReady(player, gameMode); + } + + private void doAttackPhase( + LocalPlayer player, + MultiPlayerGameMode gameMode, + Entity target, + int weaponSlot + ) { + Vec3 aim = predictedAimPoint(target, player.getEyePosition()); + + if (rotationFailed(aim)) { + return; + } + + if (autoMove.getValue()) { + Vec3 attackMovePoint = getAttackMovePoint(player, target); + steerToward(player, attackMovePoint, approachSpeed.getValue(), verticalSpeed.getValue()); + } + + if (!isInAttackRange(player, target)) { + useFireworkIfReady(player, gameMode); + return; + } + + if (!canMace(player, target)) { + useFireworkIfReady(player, gameMode); + return; + } + + if (!cooldownReady(player)) { + return; + } + + attackWithWeapon(player, gameMode, target, weaponSlot); + } + + private Vec3 getRetreatPoint(LocalPlayer player, Entity target) { + Vec3 playerPos = player.position(); + Vec3 targetPos = target.position(); + + Vec3 away = playerPos.subtract(targetPos); + + if (away.lengthSqr() <= 0.001) { + away = new Vec3(0.0, 0.0, 1.0); + } + + away = new Vec3(away.x, 0.0, away.z); + + if (away.lengthSqr() <= 0.001) { + away = new Vec3(0.0, 0.0, 1.0); + } + + away = away.normalize(); + + return playerPos + .add(away.scale(retreatDistance.getValue())) + .add(0.0, retreatHeight.getValue(), 0.0); + } + + private Vec3 getDivePoint(LocalPlayer player, Entity target) { + Vec3 aim = predictedAimPoint(target, player.getEyePosition()); + + double wantedY = target.getY() + Math.max(0.35, target.getBbHeight() * 0.55); + + return new Vec3( + aim.x, + wantedY, + aim.z + ); + } + + private Vec3 getAttackMovePoint(LocalPlayer player, Entity target) { + Vec3 aim = predictedAimPoint(target, player.getEyePosition()); + double heightAbove = player.getY() - target.getY(); + + if (heightAbove < minHeightAbove.getValue()) { + return getRetreatPoint(player, target); + } + + return new Vec3( + aim.x, + target.getY() + target.getBbHeight() * 0.35, + aim.z + ); + } + + private void steerToward( + LocalPlayer player, + Vec3 targetPoint, + double horizontalSpeed, + double maxVerticalSpeed + ) { + Vec3 currentPos = player.position(); + Vec3 currentVelocity = player.getDeltaMovement(); + Vec3 diff = targetPoint.subtract(currentPos); + + Vec3 horizontal = new Vec3(diff.x, 0.0, diff.z); + + double wantedX = currentVelocity.x; + double wantedZ = currentVelocity.z; + + if (horizontal.lengthSqr() > MIN_DIRECTION_LENGTH) { + Vec3 horizontalDir = horizontal.normalize(); + + wantedX = horizontalDir.x * horizontalSpeed; + wantedZ = horizontalDir.z * horizontalSpeed; + } else { + wantedX *= 0.65; + wantedZ *= 0.65; + } + + double wantedY = clamp(diff.y * 0.18, -maxVerticalSpeed, maxVerticalSpeed); + + double blend = player.isFallFlying() ? ELYTRA_STEER_BLEND : GROUND_STEER_BLEND; + + double newX = lerp(currentVelocity.x, wantedX, blend); + double newY = lerp(currentVelocity.y, wantedY, blend); + double newZ = lerp(currentVelocity.z, wantedZ, blend); + + player.setDeltaMovement(newX, newY, newZ); + } + + private void useFireworkIfReady(LocalPlayer player, MultiPlayerGameMode gameMode) { + if (!useFireworks.getValue()) { + return; + } + + if (!player.isFallFlying()) { + return; + } + + long now = System.currentTimeMillis(); + + if (now - lastFireworkMs < fireworkDelay.getValue()) { + return; + } + + if (useFirework(player, gameMode)) { + lastFireworkMs = now; + } + } + + private boolean useFirework(LocalPlayer player, MultiPlayerGameMode gameMode) { + if (player.getOffhandItem().is(Items.FIREWORK_ROCKET)) { + gameMode.useItem(player, InteractionHand.OFF_HAND); + + if (swing.getValue()) { + player.swing(InteractionHand.OFF_HAND); + } + + return true; + } + + int fireworkSlot = findItemSlot(Items.FIREWORK_ROCKET); + + if (fireworkSlot == -1) { + return false; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + SwitchData switchData = doSwitch(player, fireworkSlot, oldSlot); + + if (!switchData.success()) { + return false; + } + + gameMode.useItem(player, InteractionHand.MAIN_HAND); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(player, switchData); + + return true; + } + + private boolean isInAttackRange(LocalPlayer player, Entity entity) { + Vec3 eyes = player.getEyePosition(); + Vec3 closest = getClosestPointOnBox(entity.getBoundingBox(), eyes); + + double distance = eyes.distanceTo(closest); + + if (distance > attackRange.getValue()) { + return false; + } + + return hasLineOfSight(eyes, closest) || distance <= wallsRange.getValue(); + } + + private boolean canMace(LocalPlayer player, Entity entity) { + if (!requireFall.getValue()) { + return true; + } + + if (player.fallDistance >= minFallDistance.getValue()) { + return true; + } + + if (player.isFallFlying()) { + return player.getY() - entity.getY() >= minHeightAbove.getValue(); + } + + return false; + } + + private boolean cooldownReady(LocalPlayer player) { + long now = System.currentTimeMillis(); + + if (attackCooldown.getValue() > 0 && now - lastAttackMs < attackCooldown.getValue()) { + return false; + } + + return player.getAttackStrengthScale(0.0F) >= 1.0F; + } + + private void attackWithWeapon( + LocalPlayer player, + MultiPlayerGameMode gameMode, + Entity entity, + int weaponSlot + ) { + int oldSlot = player.getInventory().getSelectedSlot(); + SwitchData switchData = doSwitch(player, weaponSlot, oldSlot); + + if (!switchData.success()) { + return; + } + + AuraCircles.spawn(entity); + + if (packetAttack.getValue()) { + player.connection.send(ServerboundInteractPacket.createAttackPacket(entity, player.isShiftKeyDown())); + } + + gameMode.attack(player, entity); + + if (player.isSprinting()) { + player.connection.send(new ServerboundPlayerCommandPacket( + player, + ServerboundPlayerCommandPacket.Action.START_SPRINTING + )); + } + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(player, switchData); + + lastAttackMs = System.currentTimeMillis(); + phase = Phase.Retreat; + } + + private int findWeaponSlot() { + int mace = findItemSlot(Items.MACE); + + if (mace != -1) { + return mace; + } + + if (axeFallback.getValue()) { + return findItemSlot(Items.NETHERITE_AXE); + } + + return -1; + } + + private int findItemSlot(Item item) { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).is(item)) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(item)) { + return i; + } + } + + if (switchMode.getValue() == SwitchMode.Silent || switchMode.getValue() == SwitchMode.AltSwap) { + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).is(item)) { + return i; + } + } + } + + return -1; + } + + private SwitchData doSwitch(LocalPlayer player, int slot, int oldSlot) { + if (mc.gameMode == null) { + return SwitchData.failed(); + } + + if (slot < 0 || slot > 35) { + return SwitchData.failed(); + } + + if (switchMode.getValue() == SwitchMode.None) { + return player.getInventory().getSelectedSlot() == slot + ? new SwitchData(true, oldSlot, -1, false) + : SwitchData.failed(); + } + + if (slot == oldSlot) { + return new SwitchData(true, oldSlot, -1, false); + } + + if (slot <= 8) { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + + return new SwitchData(true, oldSlot, -1, true); + } + + if (switchMode.getValue() != SwitchMode.Silent && switchMode.getValue() != SwitchMode.AltSwap) { + return SwitchData.failed(); + } + + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + oldSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + + return new SwitchData(true, oldSlot, slot, true); + } + + private void switchBack(LocalPlayer player, SwitchData data) { + if (data == null || !data.success() || !data.switched() || mc.gameMode == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Normal) { + invSwapSlot = -1; + return; + } + + if (data.inventorySlot() != -1) { + if (invSwapSlot == data.inventorySlot()) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + data.oldSlot(), + ClickType.SWAP, + player + ); + + invSwapSlot = -1; + } + + return; + } + + player.getInventory().setSelectedSlot(data.oldSlot()); + player.connection.send(new ServerboundSetCarriedItemPacket(data.oldSlot())); + } + + private boolean isWearingElytra(LocalPlayer player) { + return player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA); + } + + private double distanceToTarget(LocalPlayer player, Entity entity) { + Vec3 eyes = player.getEyePosition(); + Vec3 closest = getClosestPointOnBox(entity.getBoundingBox(), eyes); + + return eyes.distanceTo(closest); + } + + private Vec3 predictedAimPoint(Entity entity, Vec3 eyes) { + Vec3 base = getAttackRotateVec(entity, eyes); + Vec3 velocity = entity.getDeltaMovement(); + + if (isEntityFlying(entity)) { + velocity = velocity.scale(ELYTRA_PREDICTION_SCALE); + } + + Vec3 lead = velocity.scale(PREDICTION_MS / 1000.0); + + return base.add(lead.x, lead.y + AIM_Y_OFFSET, lead.z); + } + + private Vec3 getAttackRotateVec(Entity entity, Vec3 eyes) { + return switch (rotateType.getValue()) { + case Feet -> entity.position(); + + case Torso -> entity.position().add(0.0, entity.getBbHeight() * 0.5, 0.0); + + case Head -> entity.getEyePosition(); + + case Closest -> getClosestPointOnBox(entity.getBoundingBox(), eyes); + + case Auto -> { + Vec3 feet = entity.position(); + Vec3 torso = entity.position().add(0.0, entity.getBbHeight() * 0.5, 0.0); + Vec3 head = entity.getEyePosition(); + Vec3 closest = getClosestPointOnBox(entity.getBoundingBox(), eyes); + + Vec3 best = closest; + double bestDistance = eyes.distanceToSqr(closest); + + double feetDistance = eyes.distanceToSqr(feet); + + if (feetDistance < bestDistance) { + bestDistance = feetDistance; + best = feet; + } + + double torsoDistance = eyes.distanceToSqr(torso); + + if (torsoDistance < bestDistance) { + bestDistance = torsoDistance; + best = torso; + } + + double headDistance = eyes.distanceToSqr(head); + + if (headDistance < bestDistance) { + best = head; + } + + yield best; + } + }; + } + + private boolean isEntityFlying(Entity entity) { + Vec3 velocity = entity.getDeltaMovement(); + + boolean movingVertically = velocity.y < -0.1 || velocity.y > 0.1; + boolean falling = entity.fallDistance > 1.5; + boolean fallFlying = entity instanceof LivingEntity living && living.isFallFlying(); + + return movingVertically || falling || fallFlying; + } + + private static Vec3 getClosestPointOnBox(AABB box, Vec3 point) { + double x = Math.max(box.minX, Math.min(point.x, box.maxX)); + double y = Math.max(box.minY, Math.min(point.y, box.maxY)); + double z = Math.max(box.minZ, Math.min(point.z, box.maxZ)); + + return new Vec3(x, y, z); + } + + private boolean hasLineOfSight(Vec3 from, Vec3 to) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return false; + } + + HitResult result = level.clip(new ClipContext( + from, + to, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.MISS; + } + + private double angleTo(LocalPlayer player, Entity entity) { + Vec3 diff = entity.position().subtract(player.position()); + + double yaw = Math.toDegrees(Math.atan2(diff.z, diff.x)) - 90.0; + + return Math.abs(net.minecraft.util.Mth.wrapDegrees((float) (yaw - player.getYRot()))); + } + + private boolean rotationFailed(Vec3 vec) { + if (!rotate.getValue()) { + return false; + } + + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return false; + } + + return !rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + private static double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private static double lerp(double from, double to, double progress) { + return from + (to - from) * progress; + } + + @Override + public String getDisplayInfo() { + if (target == null) { + return phase.name(); + } + + return target.getName().getString() + " " + phase.name(); + } + + private record SwitchData(boolean success, int oldSlot, int inventorySlot, boolean switched) { + private static SwitchData failed() { + return new SwitchData(false, -1, -1, false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoTrap.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoTrap.java new file mode 100644 index 0000000..2a9920f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/AutoTrap.java @@ -0,0 +1,640 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +public class AutoTrap extends Module { + + public static AutoTrap INSTANCE; + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private static final String ROT_ID = "autotrap"; + private static final int ROT_PRIORITY = 3; + + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting shiftTicks = num("ShiftTicks", 4, 1, 10); + public final Setting asynchronous = bool("Asynchronous", true); + public final Setting await = bool("Await", false); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting selfDisable = bool("SelfDisable", false); + public final Setting itemDisable = bool("ItemDisable", false); + public final Setting placeRange = num("PlaceRange", 5.0f, 0.0f, 12.0f); + public final Setting enemyRange = num("EnemyRange", 8.0f, 0.0f, 16.0f); + public final Setting multitask = bool("MultiTask", true); + public final Setting swing = bool("Swing", false); + public final Setting rotate = bool("Rotate", true); + public final Setting attack = bool("Attack", true); + public final Setting blocks = num("Blocks/Tick", 6, 1, 6); + public final Setting delay = num("Delay", 2, 0, 20); + public final Setting predict = bool("Predict", true); + public final Setting predictTicks = num("PredictTicks", 1, 1, 10); + public final Setting head = bool("Head", true); + public final Setting face = bool("Face", true); + public final Setting feet = bool("Feet", false); + public final Setting targetFriends = bool("TargetFriends", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.5f, 4f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private Player target; + private List placements = new ArrayList<>(); + private double prevY; + private int ticks = 0; + private int blocksPlaced = 0; + private int invSwapSlot = -1; + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + public AutoTrap() { + super("AutoTrap", "Traps enemy", Category.COMBAT); + INSTANCE = this; + } + + public Player getTarget() { + return target; + } + + @Override + public void onEnable() { + if (mc.player == null) { + return; + } + + prevY = mc.player.getY(); + invSwapSlot = -1; + renderFadeState.reset(); + } + + @Override + public void onDisable() { + placements = new ArrayList<>(); + target = null; + invSwapSlot = -1; + ticks = 0; + blocksPlaced = 0; + renderFadeState.reset(); + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + if (mc.player == null || mc.level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && mc.player.isUsingItem()) { + return; + } + + Runnable runnable = () -> { + if (mc.player == null || mc.level == null || mc.gameMode == null) { + return; + } + + target = findTarget(enemyRange.getValue()); + + if (target == null) { + placements = new ArrayList<>(); + resetSpoofIfNeeded(); + + if (selfDisable.getValue()) { + disable(); + } + + return; + } + + if (Math.abs(mc.player.getY() - prevY) > 0.5) { + disable(); + return; + } + + blocksPlaced = 0; + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + int slot = findResistantBlockSlot(); + + if (slot == -1) { + placements = new ArrayList<>(); + + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + placements = getTrapPositions(target); + + double placeRangeSq = placeRange.getValue() * placeRange.getValue(); + + List positions = placements.stream() + .filter(p -> mc.player.distanceToSqr(Vec3.atCenterOf(p)) <= placeRangeSq) + .filter(this::isPlaceable) + .toList(); + + if (positions.isEmpty()) { + if (selfDisable.getValue()) { + disable(); + } + + return; + } + + int oldSlot = mc.player.getInventory().getSelectedSlot(); + boolean switched = false; + int limit = Math.min(blocks.getValue(), shiftTicks.getValue()); + List placed = new ArrayList<>(); + + for (BlockPos pos : positions) { + if (blocksPlaced >= limit) { + break; + } + + if (!switched) { + if (!doSwitch(slot, oldSlot)) { + break; + } + + switched = true; + } + + Direction dir = findPlaceDirection(pos, placed, strictDirection.getValue()); + + if (dir == null) { + BlockPos support = pos.below(); + Direction supportDir = findPlaceDirection(support, placed, strictDirection.getValue()); + + if (!isPlaceable(support) || supportDir == null) { + continue; + } + + if (applyRotations(Vec3.atCenterOf(support))) { + continue; + } + + if (placeBlock(support)) { + placed.add(support); + blocksPlaced++; + + if (blocksPlaced >= limit) { + break; + } + } else { + continue; + } + + if (await.getValue()) { + continue; + } + + dir = findPlaceDirection(pos, placed, strictDirection.getValue()); + + if (dir == null) { + continue; + } + } + + if (applyRotations(Vec3.atCenterOf(pos))) { + continue; + } + + if (placeBlock(pos)) { + placed.add(pos); + blocksPlaced++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + ticks = 0; + }; + + if (asynchronous.getValue()) { + new Thread(runnable, "AutoTrap-Async").start(); + } else { + runnable.run(); + } + } + + private List getTrapPositions(Player enemy) { + List list = new ArrayList<>(); + BlockPos base; + + if (predict.getValue()) { + Vec3 predicted = enemy.position().add(enemy.getDeltaMovement().scale(predictTicks.getValue())); + base = BlockPos.containing(predicted); + } else { + base = enemy.blockPosition(); + } + + if (head.getValue()) { + list.add(base.above(2)); + } + + if (face.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + list.add(base.above().relative(dir)); + } + } + + if (feet.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + list.add(base.relative(dir)); + } + } + + return list; + } + + private Direction findPlaceDirection(BlockPos pos, List placed, boolean strictDir) { + if (mc.player == null || mc.level == null) { + return null; + } + + Direction best = null; + double bestDist = Double.MAX_VALUE; + Vec3 eye = mc.player.getEyePosition(); + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + + boolean solid = !mc.level.getBlockState(neighbor).canBeReplaced() + || placed.contains(neighbor); + + if (!solid) { + continue; + } + + if (strictDir) { + Vec3 faceCenter = Vec3.atCenterOf(neighbor) + .add(new Vec3(dir.getStepX(), dir.getStepY(), dir.getStepZ()).scale(0.5)); + + Vec3 toEye = eye.subtract(faceCenter).normalize(); + Vec3 faceNormal = new Vec3(dir.getStepX(), dir.getStepY(), dir.getStepZ()).normalize(); + + if (toEye.dot(faceNormal) <= 0.0) { + continue; + } + } + + double dist = eye.distanceTo(Vec3.atCenterOf(neighbor)); + + if (dist < bestDist) { + bestDist = dist; + best = dir; + } + } + + return best; + } + + private boolean applyRotations(Vec3 pos) { + if (!rotate.getValue()) { + return false; + } + + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return false; + } + + return !rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + if (mc.player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + mc.player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + mc.player.getInventory().setSelectedSlot(slot); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> mc.player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + if (mc.player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + mc.player.getInventory().setSelectedSlot(oldSlot); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + mc.player + ); + } + + invSwapSlot = -1; + } + } + + private boolean placeBlock(BlockPos pos) { + if (mc.player == null || mc.level == null || mc.gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + mc.gameMode.useItemOn(mc.player, InteractionHand.MAIN_HAND, hitResult); + + if (swing.getValue()) { + mc.player.swing(InteractionHand.MAIN_HAND); + } + + if (attack.getValue() && target != null) { + mc.gameMode.attack(mc.player, target); + + if (swing.getValue()) { + mc.player.swing(InteractionHand.MAIN_HAND); + } + } + + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + if (mc.player == null || mc.level == null) { + return null; + } + + boolean allowAir = airPlace.getValue() + || placeMode.getValue() == PlaceMode.NCP + || !strict.getValue(); + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = mc.player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = mc.level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(mc.level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + } + + if (bestSide == null) { + if (allowAir) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isPlaceable(BlockPos pos) { + if (mc.level == null) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + return buildHitResult(pos) != null; + } + + private int findResistantBlockSlot() { + if (mc.player == null) { + return -1; + } + + for (int i = 0; i < 9; i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (stack.getItem() instanceof BlockItem blockItem && isResistant(blockItem.getBlock())) { + return i; + } + } + + return -1; + } + + private boolean isResistant(Block block) { + return block == Blocks.OBSIDIAN + || block == Blocks.CRYING_OBSIDIAN + || block == Blocks.RESPAWN_ANCHOR + || block == Blocks.ENDER_CHEST + || block == Blocks.NETHERITE_BLOCK + || block == Blocks.ANCIENT_DEBRIS; + } + + private Player findTarget(float maxEnemyRange) { + if (mc.player == null || mc.level == null) { + return null; + } + + Player best = null; + double min = Double.MAX_VALUE; + + for (Player p : mc.level.players()) { + if (p == mc.player || !p.isAlive() || p.isSpectator()) { + continue; + } + + if (!targetFriends.getValue() && nolongerhuman.friendManager.isFriend(p)) { + continue; + } + + double dist = mc.player.distanceTo(p); + + if (dist > maxEnemyRange) { + continue; + } + + if (dist < min) { + min = dist; + best = p; + } + } + + return best; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (mc.player == null || mc.level == null) { + renderFadeState.reset(); + return; + } + + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + List visible = new ArrayList<>(); + + for (BlockPos pos : placements) { + if (!isPlaceable(pos)) { + continue; + } + + visible.add(pos); + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + visible, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Blocker.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Blocker.java new file mode 100644 index 0000000..af7b787 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Blocker.java @@ -0,0 +1,562 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundBlockDestructionPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Blocker extends Module { + + public static Blocker INSTANCE; + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private static final String ROT_ID = "blocker"; + private static final int ROT_PRIORITY = 3; + + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting multitask = bool("MultiTask", false); + public final Setting rotate = bool("Rotate", true); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting feet = bool("Feet", true); + public final Setting head = bool("Head", true); + public final Setting range = num("Range", 5.0f, 0.0f, 12.0f); + public final Setting blocksPerTick = num("ShiftTicks", 4, 1, 20); + public final Setting delay = num("Delay", 0, 0, 20); + public final Setting triggerStage = num("TriggerStage", 0, 0, 9); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 50, 50, 40)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 50, 50, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private int ticks = 0; + private int invSwapSlot = -1; + + private final Map mines = new HashMap<>(); + private final List queuedPlacements = new ArrayList<>(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private record MineInfo(int breakerId, int stage, long timeMs) { + } + + public Blocker() { + super("Blocker", "It is blocker", Category.COMBAT); + INSTANCE = this; + } + + @Override + public void onEnable() { + ticks = 0; + invSwapSlot = -1; + mines.clear(); + queuedPlacements.clear(); + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + ticks = 0; + invSwapSlot = -1; + mines.clear(); + queuedPlacements.clear(); + renderPositions.clear(); + renderFadeState.reset(); + clearRotations(); + } + + @SuppressWarnings("unused") + @Subscribe + public void onPacket(PacketEvent.Receive event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + Packet packet = event.getPacket(); + + if (!(packet instanceof ClientboundBlockDestructionPacket destruction)) { + return; + } + + BlockPos pos = destruction.getPos(); + int breakerId = destruction.getId(); + int stage = destruction.getProgress(); + + if (stage < 0) { + mines.remove(pos); + return; + } + + if (breakerId == player.getId()) { + return; + } + + double rangeSq = range.getValue() * range.getValue(); + + if (player.distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + return; + } + + Entity breaker = level.getEntity(breakerId); + + if (breaker instanceof Player breakerPlayer && nolongerhuman.friendManager.isFriend(breakerPlayer)) { + return; + } + + mines.put(pos.immutable(), new MineInfo(breakerId, stage, System.currentTimeMillis())); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + expireOldMines(); + + queuedPlacements.clear(); + renderPositions.clear(); + + double rangeSq = range.getValue() * range.getValue(); + + for (Map.Entry entry : mines.entrySet()) { + BlockPos minedPos = entry.getKey(); + MineInfo info = entry.getValue(); + + if (player.distanceToSqr(Vec3.atCenterOf(minedPos)) > rangeSq) { + continue; + } + + if (info.stage < triggerStage.getValue()) { + continue; + } + + if (feet.getValue()) { + queuedPlacements.add(minedPos.above()); + + for (Direction direction : Direction.Plane.HORIZONTAL) { + queuedPlacements.add(minedPos.relative(direction)); + } + } + + if (head.getValue()) { + queuedPlacements.add(minedPos.above()); + } + } + + List toPlace = new ArrayList<>(); + + for (BlockPos pos : queuedPlacements) { + if (player.distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + continue; + } + + if (!isPlaceable(level, pos)) { + continue; + } + + if (!toPlace.contains(pos)) { + toPlace.add(pos); + } + } + + renderPositions.addAll(toPlace); + + if (toPlace.isEmpty()) { + ticks = 0; + return; + } + + int slot = findResistantBlockSlot(player); + + if (slot == -1) { + ticks = 0; + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + int placed = 0; + + for (BlockPos pos : toPlace) { + if (placed >= blocksPerTick.getValue()) { + break; + } + + if (!airPlace.getValue() && findPlaceDirection(level, player, pos, strictDirection.getValue()) == null) { + continue; + } + + if (!switched) { + if (!doSwitch(player, slot, oldSlot)) { + break; + } + + switched = true; + } + + if (rotate.getValue()) { + applyRotations(Vec3.atCenterOf(pos)); + } + + if (placeBlock(player, gameMode, pos)) { + placed++; + } + } + + if (switched) { + switchBack(player, oldSlot); + } + + resetSpoofIfNeeded(); + ticks = 0; + } + + @Override + public void onRender3D(Render3DEvent event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (!render.getValue() || player == null || level == null) { + renderFadeState.reset(); + return; + } + + List visible = new ArrayList<>(); + + for (BlockPos pos : renderPositions) { + if (!isPlaceable(level, pos)) { + continue; + } + + visible.add(pos); + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + visible, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + private void expireOldMines() { + long now = System.currentTimeMillis(); + mines.entrySet().removeIf(entry -> now - entry.getValue().timeMs > 2500L); + } + + private boolean placeBlock(LocalPlayer player, MultiPlayerGameMode gameMode, BlockPos pos) { + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Direction directionToNeighbor = findPlaceDirection(level, player, pos, strictDirection.getValue()); + + if (directionToNeighbor == null) { + return null; + } + + BlockPos neighbor = pos.relative(directionToNeighbor); + Direction hitSide = directionToNeighbor.getOpposite(); + + Vec3 hitVec = Vec3.atCenterOf(neighbor).add( + hitSide.getStepX() * 0.5, + hitSide.getStepY() * 0.5, + hitSide.getStepZ() * 0.5 + ); + + return new BlockHitResult(hitVec, hitSide, neighbor, false); + } + + private Direction findPlaceDirection(ClientLevel level, LocalPlayer player, BlockPos pos, boolean strictDir) { + Direction bestDirection = null; + double bestDistance = Double.MAX_VALUE; + Vec3 eye = player.getEyePosition(); + + for (Direction direction : Direction.values()) { + BlockPos neighbor = pos.relative(direction); + BlockState neighborState = level.getBlockState(neighbor); + + if (neighborState.isAir() || neighborState.canBeReplaced()) { + continue; + } + + if (neighborState.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction hitSide = direction.getOpposite(); + + Vec3 faceCenter = Vec3.atCenterOf(neighbor).add( + hitSide.getStepX() * 0.5, + hitSide.getStepY() * 0.5, + hitSide.getStepZ() * 0.5 + ); + + if (strictDir) { + Vec3 toEye = eye.subtract(faceCenter).normalize(); + + Vec3 faceNormal = new Vec3( + hitSide.getStepX(), + hitSide.getStepY(), + hitSide.getStepZ() + ).normalize(); + + if (toEye.dot(faceNormal) <= 0.0) { + continue; + } + } + + double distance = eye.distanceTo(faceCenter); + + if (distance < bestDistance) { + bestDistance = distance; + bestDirection = direction; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + return bestDirection; + } + + private boolean isPlaceable(ClientLevel level, BlockPos pos) { + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + if (!level.getEntitiesOfClass(Entity.class, new AABB(pos), entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return airPlace.getValue() || buildHitResult(pos) != null; + } + + private int findResistantBlockSlot(LocalPlayer player) { + for (int i = 0; i < 9; i++) { + ItemStack stack = player.getInventory().getItem(i); + + if (stack.getItem() instanceof BlockItem blockItem && isResistant(blockItem.getBlock())) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + ItemStack stack = player.getInventory().getItem(i); + + if (stack.getItem() instanceof BlockItem blockItem && isResistant(blockItem.getBlock())) { + return i; + } + } + + return -1; + } + + private boolean isResistant(Block block) { + return block == Blocks.OBSIDIAN + || block == Blocks.CRYING_OBSIDIAN + || block == Blocks.RESPAWN_ANCHOR + || block == Blocks.ENDER_CHEST + || block == Blocks.NETHERITE_BLOCK + || block == Blocks.ANCIENT_DEBRIS; + } + + private boolean doSwitch(LocalPlayer player, int slot, int currentHotbarSlot) { + if (mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(LocalPlayer player, int oldSlot) { + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + } + + private void applyRotations(Vec3 vec) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + @Override + public String getDisplayInfo() { + return String.valueOf(renderPositions.size()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/BowBoost.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/BowBoost.java new file mode 100644 index 0000000..76467a5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/BowBoost.java @@ -0,0 +1,479 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.phys.Vec3; + +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.FULL_SCOPE; +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.HOTBAR_SCOPE; + +public class BowBoost extends Module { + public enum Swing { + Normal, + Packet, + Both, + None + } + + private static final String ROTATION_ID = "BowBoost"; + private static final int ROTATION_PRIORITY = 100; + private static final int FIRST_NON_HOTBAR_SLOT = 9; + private static final double ARROW_GRAVITY = 0.05D; + + private final Setting inventory = bool("Inventory", true); + private final Setting itemDisable = bool("ItemDisable", true); + private final Setting drawTicks = num("DrawTicks", 5, 1, 40); + private final Setting restoreSlot = bool("RestoreSlot", true); + private final Setting minMoveSpeed = num("MinMoveSpeed", 0.08f, 0.01f, 0.5f); + private final Setting swing = mode("Swing", Swing.Normal); + + private Result bowResult; + private int oldSlot = -1; + private int ticksDrawing = 0; + private int waitTicks = 0; + private boolean started = false; + private boolean shot = false; + private float calculatedYaw = 0.0f; + private float calculatedPitch = 45.0f; + + public BowBoost() { + super("BowBoost", "Automatically bow boosts while moving", Category.COMBAT); + } + + @Override + public void onEnable() { + bowResult = null; + oldSlot = InventoryUtil.selected(); + ticksDrawing = 0; + waitTicks = 0; + started = false; + shot = false; + calculatedYaw = 0.0f; + calculatedPitch = 45.0f; + + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + double horizontalSpeed = getHorizontalSpeed(); + + if (horizontalSpeed < minMoveSpeed.getValue()) { + disable(); + return; + } + + bowResult = InventoryUtil.find( + Items.BOW, + inventory.getValue() ? FULL_SCOPE : HOTBAR_SCOPE + ); + + if (bowResult == null || bowResult.type() == ResultType.NONE) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + if (!InventoryUtil.swap(bowResult)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + started = true; + } + + @Override + public void onDisable() { + releaseBowIfNeeded(); + + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager != null) { + rotationManager.endRotation(ROTATION_ID, ROTATION_PRIORITY); + } + + if (started && restoreSlot.getValue() && bowResult != null && oldSlot >= 0) { + InventoryUtil.swapBack(bowResult, oldSlot); + } + + bowResult = null; + oldSlot = -1; + ticksDrawing = 0; + waitTicks = 0; + started = false; + shot = false; + } + + @Override + public void onTick() { + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + double horizontalSpeed = getHorizontalSpeed(); + + if (horizontalSpeed < minMoveSpeed.getValue()) { + disable(); + return; + } + + calculateBoostRotations(horizontalSpeed); + rotateForBowBoost(); + + if (!isHoldingBow()) { + if (bowResult == null || !InventoryUtil.swap(bowResult)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + } + + if (shot) { + disable(); + return; + } + + if (waitTicks > 0) { + waitTicks--; + return; + } + + if (!mc.player.isUsingItem()) { + if (!moveArrowToFirstInventorySlot()) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + startUsingBow(); + ticksDrawing = 0; + return; + } + + ticksDrawing++; + + if (ticksDrawing >= Math.max(1, drawTicks.getValue())) { + releaseBow(); + doSwing(InteractionHand.MAIN_HAND); + + shot = true; + ticksDrawing = 0; + waitTicks = 2; + } + } + + private double getHorizontalSpeed() { + if (mc.player == null) { + return 0.0D; + } + + Vec3 motion = mc.player.getDeltaMovement(); + + return Math.sqrt(motion.x * motion.x + motion.z * motion.z); + } + + private void calculateBoostRotations(double horizontalSpeed) { + if (mc.player == null) { + return; + } + + Vec3 motion = mc.player.getDeltaMovement(); + + if (horizontalSpeed < 0.001D) { + calculatedYaw = mc.player.getYRot(); + calculatedPitch = 45.0f; + return; + } + + calculatedYaw = Mth.wrapDegrees( + (float) Math.toDegrees(Math.atan2(motion.z, motion.x)) - 90.0f + ); + + double arrowSpeed = getArrowVelocityFromDrawTicks(Math.max(1, drawTicks.getValue())); + double eyeY = mc.player.getEyePosition().y; + double targetY = mc.player.getY() + 0.9D; + double deltaY = targetY - eyeY; + + float bestPitch = 45.0f; + boolean foundPitch = false; + + for (int ticks = 2; ticks <= 10; ticks++) { + double verticalVelocity = (deltaY + 0.5D * ARROW_GRAVITY * ticks * ticks) / ticks; + double requiredSpeed = Math.sqrt( + horizontalSpeed * horizontalSpeed + verticalVelocity * verticalVelocity + ); + + if (requiredSpeed <= arrowSpeed) { + bestPitch = Mth.clamp( + (float) -Math.toDegrees(Math.atan2(verticalVelocity, horizontalSpeed)), + -90.0f, + 90.0f + ); + + foundPitch = true; + break; + } + } + + if (!foundPitch) { + bestPitch = 45.0f; + } + + calculatedPitch = bestPitch; + } + + private double getArrowVelocityFromDrawTicks(int ticks) { + float charge = ticks / 20.0f; + charge = (charge * charge + charge * 2.0f) / 3.0f; + + if (charge > 1.0f) { + charge = 1.0f; + } + + return charge * 3.0D; + } + + private void rotateForBowBoost() { + if (mc.player == null) { + return; + } + + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + mc.player.setYRot(calculatedYaw); + mc.player.setXRot(calculatedPitch); + return; + } + + rotationManager.applyRotation( + ROTATION_ID, + ROTATION_PRIORITY, + calculatedYaw, + calculatedPitch + ); + } + + private boolean isHoldingBow() { + if (mc.player == null) { + return false; + } + + return mc.player.getMainHandItem().is(Items.BOW); + } + + private void startUsingBow() { + if (mc.player == null || mc.gameMode == null) { + return; + } + + mc.gameMode.useItem(mc.player, InteractionHand.MAIN_HAND); + } + + private void releaseBowIfNeeded() { + if (mc.player == null) { + return; + } + + if (!mc.player.isUsingItem()) { + return; + } + + if (mc.player.getUseItem().is(Items.BOW) || mc.player.getMainHandItem().is(Items.BOW)) { + releaseBow(); + return; + } + + mc.player.stopUsingItem(); + } + + private void releaseBow() { + if (mc.player == null) { + return; + } + + if (!mc.player.isUsingItem()) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.releaseUsingItem(mc.player); + } + + if (mc.player.isUsingItem() && mc.player.connection != null) { + mc.player.connection.send( + new ServerboundPlayerActionPacket( + ServerboundPlayerActionPacket.Action.RELEASE_USE_ITEM, + BlockPos.ZERO, + Direction.DOWN + ) + ); + + mc.player.stopUsingItem(); + } + } + + private boolean moveArrowToFirstInventorySlot() { + if (mc.player == null || mc.gameMode == null) { + return false; + } + + ItemStack firstSlotStack = mc.player.getInventory().getItem(FIRST_NON_HOTBAR_SLOT); + + if (isBowBoostArrow(firstSlotStack)) { + return true; + } + + int arrowSlot = findArrowSlot(); + + if (arrowSlot == -1) { + return false; + } + + if (arrowSlot == FIRST_NON_HOTBAR_SLOT) { + return true; + } + + swapInventorySlots(arrowSlot, FIRST_NON_HOTBAR_SLOT); + + ItemStack newFirstSlotStack = mc.player.getInventory().getItem(FIRST_NON_HOTBAR_SLOT); + + return isBowBoostArrow(newFirstSlotStack); + } + + private int findArrowSlot() { + if (mc.player == null) { + return -1; + } + + for (int i = 0; i < 36; i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (isBowBoostArrow(stack)) { + return i; + } + } + + return -1; + } + + private boolean isBowBoostArrow(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return false; + } + + return stack.is(Items.ARROW) + || stack.is(Items.TIPPED_ARROW) + || stack.is(Items.SPECTRAL_ARROW); + } + + private void swapInventorySlots(int fromInventorySlot, int toInventorySlot) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + int fromContainerSlot = toContainerSlot(fromInventorySlot); + int targetContainerSlot = toContainerSlot(toInventorySlot); + + if (fromContainerSlot == -1 || targetContainerSlot == -1) { + return; + } + + if (fromContainerSlot == targetContainerSlot) { + return; + } + + mc.gameMode.handleInventoryMouseClick( + mc.player.inventoryMenu.containerId, + fromContainerSlot, + 0, + ClickType.PICKUP, + mc.player + ); + + mc.gameMode.handleInventoryMouseClick( + mc.player.inventoryMenu.containerId, + targetContainerSlot, + 0, + ClickType.PICKUP, + mc.player + ); + + mc.gameMode.handleInventoryMouseClick( + mc.player.inventoryMenu.containerId, + fromContainerSlot, + 0, + ClickType.PICKUP, + mc.player + ); + } + + private int toContainerSlot(int inventorySlot) { + if (inventorySlot < 0 || inventorySlot > 35) { + return -1; + } + + if (inventorySlot < 9) { + return 36 + inventorySlot; + } + + return inventorySlot; + } + + private void doSwing(InteractionHand hand) { + if (mc.player == null) { + return; + } + + switch (swing.getValue()) { + case Normal -> mc.player.swing(hand); + case Packet -> { + if (mc.player.connection != null) { + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + } + case Both -> { + mc.player.swing(hand); + + if (mc.player.connection != null) { + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + } + case None -> { + } + } + } + + @Override + public String getDisplayInfo() { + if (shot) { + return "Done"; + } + + return drawTicks.getValue() + "t " + Math.round(calculatedPitch) + "°"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CEV.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CEV.java new file mode 100644 index 0000000..acd3e9d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CEV.java @@ -0,0 +1,1112 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.Comparator; +import java.util.List; +import java.util.ArrayList; + +public class CEV extends Module { + public enum SwitchMode { + None, + Normal, + Silent, + AltSwap + } + + public enum PlaceMode { + Native, + NCP + } + + private enum Action { + None, + PlaceObsidian, + MineBlockingBlock, + PlaceCrystal, + MineObsidian, + AttackCrystal + } + + private static final String ROT_ID = "cev"; + private static final int ROT_PRIORITY = 5; + + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting targetRange = num("TargetRange", 8.0, 1.0, 16.0); + public final Setting placeRange = num("PlaceRange", 5.0, 1.0, 6.0); + public final Setting mineRange = num("MineRange", 5.0, 1.0, 6.0); + public final Setting delay = num("Delay", 1, 0, 20); + public final Setting rotate = bool("Rotate", true); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting swing = bool("Swing", true); + public final Setting packetAttack = bool("PacketAttack", true); + public final Setting targetFriends = bool("TargetFriends", false); + public final Setting mineWithPickaxe = bool("MinePickaxe", true); + public final Setting selfDisable = bool("SelfDisable", false); + + public final Setting render = bool("Render", true); + public final Setting obsidianFill = color("ObbyFill", new Color(255, 255, 255, 55)); + public final Setting obsidianOutline = color("ObbyOutline", new Color(255, 255, 255, 230)); + public final Setting mineFill = color("MineFill", new Color(255, 70, 70, 55)); + public final Setting mineOutline = color("MineOutline", new Color(255, 70, 70, 230)); + public final Setting crystalFill = color("CrystalFill", new Color(120, 180, 255, 55)); + public final Setting crystalOutline = color("CrystalOutline", new Color(120, 180, 255, 230)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private Player target = null; + private BlockPos renderObsidian = null; + private BlockPos renderMine = null; + private BlockPos renderCrystal = null; + + private int ticks = 0; + private int invSwapSlot = -1; + private Action lastAction = Action.None; + + private final FadeRenderUtil.FadeState obsidianFadeState = new FadeRenderUtil.FadeState(); + private final FadeRenderUtil.FadeState mineFadeState = new FadeRenderUtil.FadeState(); + private final FadeRenderUtil.FadeState crystalFadeState = new FadeRenderUtil.FadeState(); + + public CEV() { + super("CEV", "Automatically Does CEV On Players", Category.COMBAT); + } + + @Override + public void onEnable() { + target = null; + renderObsidian = null; + renderMine = null; + renderCrystal = null; + ticks = 0; + invSwapSlot = -1; + lastAction = Action.None; + obsidianFadeState.reset(); + mineFadeState.reset(); + crystalFadeState.reset(); + } + + @Override + public void onDisable() { + target = null; + renderObsidian = null; + renderMine = null; + renderCrystal = null; + ticks = 0; + invSwapSlot = -1; + lastAction = Action.None; + obsidianFadeState.reset(); + mineFadeState.reset(); + crystalFadeState.reset(); + clearRotations(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + ticks = 0; + target = findTarget(); + + if (target == null) { + clearRender(); + clearRotations(); + + if (selfDisable.getValue()) { + disable(); + } + + return; + } + + BlockPos base = target.blockPosition(); + BlockPos obbyPos = base.above(2); + BlockPos crystalAirPos = obbyPos.above(); + + renderObsidian = null; + renderMine = null; + renderCrystal = null; + + BlockState obbyState = level.getBlockState(obbyPos); + BlockState crystalAirState = level.getBlockState(crystalAirPos); + EndCrystal existingCrystal = getCrystalAt(crystalAirPos); + + if (isCrystalBase(obbyState)) { + handleCrystalBasePresent(obbyPos, crystalAirPos, crystalAirState, existingCrystal); + } else { + handleCrystalBaseMissing(obbyPos, obbyState); + } + } + + private void handleCrystalBaseMissing(BlockPos obbyPos, BlockState obbyState) { + if (!obbyState.isAir() && !obbyState.canBeReplaced()) { + renderMine = obbyPos; + lastAction = Action.MineBlockingBlock; + mineBlock(obbyPos); + return; + } + + renderObsidian = obbyPos; + lastAction = Action.PlaceObsidian; + placeObsidian(obbyPos); + } + + private void handleCrystalBasePresent( + BlockPos obbyPos, + BlockPos crystalAirPos, + BlockState crystalAirState, + EndCrystal existingCrystal + ) { + if (existingCrystal == null && !crystalAirState.isAir() && !crystalAirState.canBeReplaced()) { + renderMine = crystalAirPos; + lastAction = Action.MineBlockingBlock; + mineBlock(crystalAirPos); + return; + } + + if (existingCrystal == null) { + renderCrystal = crystalAirPos; + lastAction = Action.PlaceCrystal; + placeCrystal(obbyPos); + return; + } + + ClientLevel level = mc.level; + + if (level != null && !level.getBlockState(obbyPos).isAir()) { + renderMine = obbyPos; + renderCrystal = crystalAirPos; + lastAction = Action.MineObsidian; + mineBlock(obbyPos); + return; + } + + renderCrystal = crystalAirPos; + lastAction = Action.AttackCrystal; + attackCrystal(existingCrystal); + } + + private Player findTarget() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return null; + } + + return level.players() + .stream() + .filter(p -> p != player) + .filter(Player::isAlive) + .filter(p -> !p.isSpectator()) + .filter(p -> targetFriends.getValue() || !nolongerhuman.friendManager.isFriend(p)) + .filter(p -> player.distanceTo(p) <= targetRange.getValue()) + .min(Comparator.comparingDouble(player::distanceTo)) + .orElse(null); + } + + private void placeObsidian(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null) { + return; + } + + if (canReach(pos, placeRange.getValue())) { + if (!isPlaceable(pos)) { + return; + } + } else { + return; + } + + int slot = findObsidianSlot(); + + if (slot == -1) { + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + SwitchData switchData = doSwitch(slot, oldSlot); + + if (!switchData.success()) { + return; + } + + if (rotate.getValue()) { + if (applyRotations(Vec3.atCenterOf(pos))) { + BlockHitResult hitResult = buildBlockHitResult(pos); + + if (hitResult == null) { + switchBack(switchData); + return; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(switchData); + resetSpoofIfNeeded(); + return; + } + + switchBack(switchData); + return; + } + + BlockHitResult hitResult = buildBlockHitResult(pos); + + if (hitResult == null) { + switchBack(switchData); + return; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(switchData); + resetSpoofIfNeeded(); + } + + private void placeCrystal(BlockPos base) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + ClientLevel level = mc.level; + + if (player == null || gameMode == null || level == null) { + return; + } + + if (!canPlaceCrystal(base)) { + return; + } + + if (canReach(base.above(), placeRange.getValue())) { + InteractionHand hand = getCrystalHand(); + SwitchData switchData = null; + + if (hand == null) { + int crystalSlot = findCrystalSlot(); + + if (crystalSlot == -1) { + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + switchData = doSwitch(crystalSlot, oldSlot); + + if (!switchData.success()) { + return; + } + + hand = InteractionHand.MAIN_HAND; + } + + Vec3 crystalVec = Vec3.atCenterOf(base).add(0.0, 1.0, 0.0); + + if (rotate.getValue()) { + if (applyRotations(crystalVec)) { + BlockHitResult hitResult = buildCrystalHitResult(base); + gameMode.useItemOn(player, hand, hitResult); + + if (swing.getValue()) { + player.swing(hand); + } + + switchBack(switchData); + resetSpoofIfNeeded(); + return; + } + + switchBack(switchData); + return; + } + + BlockHitResult hitResult = buildCrystalHitResult(base); + gameMode.useItemOn(player, hand, hitResult); + + if (swing.getValue()) { + player.swing(hand); + } + + switchBack(switchData); + resetSpoofIfNeeded(); + } + } + + private void mineBlock(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + ClientLevel level = mc.level; + + if (player == null || gameMode == null || level == null) { + return; + } + + if (canReach(pos, mineRange.getValue())) { + BlockState state = level.getBlockState(pos); + + if (state.isAir()) { + return; + } + + if (state.is(Blocks.BEDROCK) || state.getDestroySpeed(level, pos) < 0.0f) { + return; + } + } else { + return; + } + + SwitchData switchData = null; + + if (mineWithPickaxe.getValue()) { + int pickaxeSlot = findPickaxeSlot(); + + if (pickaxeSlot != -1) { + int oldSlot = player.getInventory().getSelectedSlot(); + SwitchData pickaxeSwitch = doSwitch(pickaxeSlot, oldSlot); + + if (pickaxeSwitch.success()) { + switchData = pickaxeSwitch; + } + } + } + + Direction side = getMineSide(pos); + + if (side == null) { + side = Direction.UP; + } + + if (rotate.getValue()) { + if (applyRotations(Vec3.atCenterOf(pos))) { + gameMode.startDestroyBlock(pos, side); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(switchData); + resetSpoofIfNeeded(); + return; + } + + switchBack(switchData); + return; + } + + gameMode.startDestroyBlock(pos, side); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + switchBack(switchData); + resetSpoofIfNeeded(); + } + + private void attackCrystal(EndCrystal crystal) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null || crystal == null) { + return; + } + + if (!crystal.isAlive()) { + return; + } + + if (canReach(crystal.blockPosition(), mineRange.getValue())) { + if (rotate.getValue()) { + if (applyRotations(crystal.position())) { + doCrystalAttack(player, gameMode, crystal); + resetSpoofIfNeeded(); + } + + return; + } + + doCrystalAttack(player, gameMode, crystal); + resetSpoofIfNeeded(); + } + } + + private void doCrystalAttack(LocalPlayer player, MultiPlayerGameMode gameMode, EndCrystal crystal) { + if (packetAttack.getValue()) { + player.connection.send(ServerboundInteractPacket.createAttackPacket(crystal, player.isShiftKeyDown())); + } else { + gameMode.attack(player, crystal); + } + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + } + + private boolean canPlaceCrystal(BlockPos base) { + ClientLevel level = mc.level; + + if (level == null) { + return false; + } + + BlockState baseState = level.getBlockState(base); + + if (isCrystalBase(baseState)) { + BlockPos air = base.above(); + + if (!level.getBlockState(air).isAir()) { + return false; + } + + AABB box = new AABB(air); + + return level.getEntitiesOfClass( + Entity.class, + box, + entity -> !(entity instanceof ItemEntity) && !(entity instanceof EndCrystal) + ).isEmpty(); + } + + return false; + } + + private boolean isPlaceable(BlockPos pos) { + ClientLevel level = mc.level; + + if (level == null) { + return false; + } + + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return buildBlockHitResult(pos) != null; + } + + private boolean isCrystalBase(BlockState state) { + return state.is(Blocks.OBSIDIAN) || state.is(Blocks.BEDROCK); + } + + private EndCrystal getCrystalAt(BlockPos pos) { + ClientLevel level = mc.level; + + if (level == null) { + return null; + } + + AABB box = new AABB(pos).inflate(0.25); + + List crystals = level.getEntitiesOfClass( + EndCrystal.class, + box, + EndCrystal::isAlive + ); + + return crystals.isEmpty() ? null : crystals.get(0); + } + + private boolean canReach(BlockPos pos, double range) { + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + return player.getEyePosition().distanceTo(Vec3.atCenterOf(pos)) <= range; + } + + private BlockHitResult buildBlockHitResult(BlockPos pos) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return null; + } + + if (placeMode.getValue() == PlaceMode.Native) { + Direction direction = findPlaceDirection(pos, strictDirection.getValue()); + + if (direction == null) { + return null; + } + + BlockPos neighbor = pos.relative(direction); + Direction side = direction.getOpposite(); + + Vec3 hitVec = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + return new BlockHitResult(hitVec, side, neighbor, false); + } + + Direction direction = findPlaceDirection(pos, strictDirection.getValue()); + + if (direction != null) { + BlockPos neighbor = pos.relative(direction); + Direction side = direction.getOpposite(); + + Vec3 hitVec = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + return new BlockHitResult(hitVec, side, neighbor, false); + } + + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + private BlockHitResult buildCrystalHitResult(BlockPos base) { + if (placeMode.getValue() == PlaceMode.Native) { + return new BlockHitResult( + Vec3.atCenterOf(base).add(0.0, 0.5, 0.0), + Direction.UP, + base, + false + ); + } + + Direction direction = findPlaceDirection(base, strictDirection.getValue()); + + if (direction != null) { + BlockPos neighbor = base.relative(direction); + Direction side = direction.getOpposite(); + + Vec3 hitVec = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + return new BlockHitResult(hitVec, side, neighbor, false); + } + + return new BlockHitResult( + Vec3.atCenterOf(base).add(0.0, 0.5, 0.0), + Direction.UP, + base, + false + ); + } + + private Direction findPlaceDirection(BlockPos pos, boolean strictDir) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return null; + } + + Direction best = null; + double bestDist = Double.MAX_VALUE; + Vec3 eye = player.getEyePosition(); + + for (Direction direction : Direction.values()) { + BlockPos neighbor = pos.relative(direction); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = direction.getOpposite(); + + Vec3 faceCenter = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + if (strictDir) { + Vec3 toEye = eye.subtract(faceCenter).normalize(); + + Vec3 faceNormal = new Vec3( + side.getStepX(), + side.getStepY(), + side.getStepZ() + ).normalize(); + + if (toEye.dot(faceNormal) <= 0.0) { + continue; + } + } + + double dist = eye.distanceTo(faceCenter); + + if (dist < bestDist) { + bestDist = dist; + best = direction; + } + } + + return best; + } + + private Direction getMineSide(BlockPos pos) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return Direction.UP; + } + + Vec3 eye = player.getEyePosition(); + + Direction best = null; + double bestDistance = Double.MAX_VALUE; + + for (Direction direction : Direction.values()) { + Vec3 hit = Vec3.atCenterOf(pos).add( + direction.getStepX() * 0.5, + direction.getStepY() * 0.5, + direction.getStepZ() * 0.5 + ); + + double distance = eye.distanceTo(hit); + + if (distance >= bestDistance) { + continue; + } + + if (!strictDirection.getValue() || hasLineOfSight(eye, hit)) { + bestDistance = distance; + best = direction; + } + } + + return best; + } + + private boolean hasLineOfSight(Vec3 from, Vec3 to) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return false; + } + + HitResult result = level.clip(new ClipContext( + from, + to, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.MISS; + } + + private InteractionHand getCrystalHand() { + LocalPlayer player = mc.player; + + if (player == null) { + return null; + } + + if (player.getOffhandItem().is(Items.END_CRYSTAL)) { + return InteractionHand.OFF_HAND; + } + + if (player.getMainHandItem().is(Items.END_CRYSTAL)) { + return InteractionHand.MAIN_HAND; + } + + return null; + } + + private int findObsidianSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (isObsidian(player.getInventory().getItem(selected))) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (isObsidian(player.getInventory().getItem(i))) { + return i; + } + } + + if (switchMode.getValue() == SwitchMode.AltSwap || switchMode.getValue() == SwitchMode.Silent) { + for (int i = 9; i < 36; i++) { + if (isObsidian(player.getInventory().getItem(i))) { + return i; + } + } + } + + return -1; + } + + private int findCrystalSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).is(Items.END_CRYSTAL)) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(Items.END_CRYSTAL)) { + return i; + } + } + + if (switchMode.getValue() == SwitchMode.AltSwap || switchMode.getValue() == SwitchMode.Silent) { + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).is(Items.END_CRYSTAL)) { + return i; + } + } + } + + return -1; + } + + private int findPickaxeSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (isPickaxe(player.getInventory().getItem(selected))) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (isPickaxe(player.getInventory().getItem(i))) { + return i; + } + } + + if (switchMode.getValue() == SwitchMode.AltSwap || switchMode.getValue() == SwitchMode.Silent) { + for (int i = 9; i < 36; i++) { + if (isPickaxe(player.getInventory().getItem(i))) { + return i; + } + } + } + + return -1; + } + + private boolean isObsidian(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return false; + } + + if (!(stack.getItem() instanceof BlockItem blockItem)) { + return false; + } + + Block block = blockItem.getBlock(); + return block == Blocks.OBSIDIAN || block == Blocks.CRYING_OBSIDIAN; + } + + private boolean isPickaxe(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return false; + } + + Item item = stack.getItem(); + + return item == Items.WOODEN_PICKAXE + || item == Items.STONE_PICKAXE + || item == Items.IRON_PICKAXE + || item == Items.GOLDEN_PICKAXE + || item == Items.DIAMOND_PICKAXE + || item == Items.NETHERITE_PICKAXE; + } + + private SwitchData doSwitch(int slot, int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return SwitchData.failed(); + } + + if (switchMode.getValue() == SwitchMode.None) { + return player.getInventory().getSelectedSlot() == slot + ? new SwitchData(true, oldSlot, -1, false) + : SwitchData.failed(); + } + + if (slot < 0) { + return SwitchData.failed(); + } + + if (slot <= 8) { + if (slot == oldSlot) { + return new SwitchData(true, oldSlot, -1, false); + } + + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + + return new SwitchData(true, oldSlot, -1, true); + } + + if (slot > 35) { + return SwitchData.failed(); + } + + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + oldSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + + return new SwitchData(true, oldSlot, slot, true); + } + + private void switchBack(SwitchData data) { + LocalPlayer player = mc.player; + + if (data == null || !data.success() || !data.switched() || player == null || mc.gameMode == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Normal) { + if (invSwapSlot == data.inventorySlot()) { + invSwapSlot = -1; + } + + return; + } + + if (data.inventorySlot() != -1) { + if (invSwapSlot == data.inventorySlot()) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + data.oldSlot(), + ClickType.SWAP, + player + ); + + invSwapSlot = -1; + } + + return; + } + + player.getInventory().setSelectedSlot(data.oldSlot()); + player.connection.send(new ServerboundSetCarriedItemPacket(data.oldSlot())); + } + + private boolean applyRotations(Vec3 vec) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return true; + } + + return rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + private void clearRender() { + renderObsidian = null; + renderMine = null; + renderCrystal = null; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue() || mc.player == null || mc.level == null) { + obsidianFadeState.reset(); + mineFadeState.reset(); + crystalFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + obsidianFadeState, + single(renderObsidian), + obsidianFill.getValue(), + obsidianOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + + FadeRenderUtil.renderBlockPositions( + stack, + mineFadeState, + single(renderMine), + mineFill.getValue(), + mineOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + + FadeRenderUtil.renderBlockPositions( + stack, + crystalFadeState, + single(renderCrystal), + crystalFill.getValue(), + crystalOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + private List single(BlockPos pos) { + List list = new ArrayList<>(); + + if (pos != null) { + list.add(pos); + } + + return list; + } + + @Override + public String getDisplayInfo() { + if (target == null) { + return "None"; + } + + return target.getName().getString() + " " + lastAction.name(); + } + + private record SwitchData(boolean success, int oldSlot, int inventorySlot, boolean switched) { + private static SwitchData failed() { + return new SwitchData(false, -1, -1, false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CombatPlace.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CombatPlace.java new file mode 100644 index 0000000..3024ee1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CombatPlace.java @@ -0,0 +1,656 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class CombatPlace extends Module { + public enum TargetMode { + Closest, + LowestHealth + } + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private static final String ROT_ID = "combatplace"; + private static final int ROT_PRIORITY = 3; + private static final double STATIONARY_EPSILON = 1.0E-4D; + + public final Setting targetMode = mode("Priority", TargetMode.Closest); + public final Setting enemyRange = num("EnemyRange", 10.0, 0.0, 24.0); + public final Setting flatten = bool("Flatten", true); + public final Setting scaffold = bool("Scaffold", false); + public final Setting predict = bool("Predict", true); + public final Setting extrapolate = bool("Extrapolate", true); + public final Setting predictTicks = num("PredictTicks", 2, 1, 8); + public final Setting placeRange = num("PlaceRange", 5.0, 1.0, 6.0); + public final Setting placeSpeed = num("PlaceSpeed", 20f, 0.1f, 20f); + public final Setting maxPlacesPerTick = num("ShiftTicks", 4, 1, 10); + public final Setting attack = bool("Attack", true); + public final Setting support = bool("Support", false); + public final Setting strict = bool("StrictDirection", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting safety = bool("Safety", true); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + + public final Setting render = bool("Render", true); + public final Setting renderFill = color("RenderFill", new Color(255, 255, 255, 87)); + public final Setting renderOutline = color("RenderOutline", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.0f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final Timer placeTimer = new Timer(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private Player target = null; + private int invSwapSlot = -1; + + public CombatPlace() { + super("CombatPlace", "Places blocks on/under moving targets and predicts movement", Category.COMBAT); + } + + @Override + public void onDisable() { + clearRotations(); + renderPositions.clear(); + renderFadeState.reset(); + target = null; + invSwapSlot = -1; + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + renderPositions.clear(); + target = getTarget(); + + if (target == null) { + clearRotations(); + return; + } + + if (isStationary(target)) { + clearRotations(); + return; + } + + long delay = (long) (1000f / placeSpeed.getValue()); + + if (!placeTimer.passedMs(delay)) { + return; + } + + List positions = getPlacePositions(target); + + if (positions.isEmpty()) { + return; + } + + positions.sort(Comparator.comparingDouble(pos -> player.distanceToSqr(Vec3.atCenterOf(pos)))); + renderPositions.addAll(positions); + + placeBlocks(positions); + placeTimer.reset(); + } + + private List getPlacePositions(Player target) { + List positions = new ArrayList<>(); + + if (target == null || mc.level == null) { + return positions; + } + + if (isStationary(target)) { + return positions; + } + + if (flatten.getValue()) { + BlockPos under = target.blockPosition().below(); + + if (isValidSpot(under)) { + positions.add(under); + } + } + + Vec3 predictedPos = target.position(); + + if (extrapolate.getValue()) { + predictedPos = predictedPos.add(target.getDeltaMovement().scale(predictTicks.getValue())); + } + + BlockPos predictedFeet = BlockPos.containing(predictedPos.x, predictedPos.y, predictedPos.z); + + if (scaffold.getValue()) { + BlockPos floor = predictedFeet.below(); + + if (isValidSpot(floor) && !positions.contains(floor)) { + positions.add(floor); + } + } + + if (predict.getValue()) { + if (isValidSpot(predictedFeet) && !positions.contains(predictedFeet)) { + positions.add(predictedFeet); + } + + BlockPos head = predictedFeet.above(); + + if (isValidSpot(head) && !positions.contains(head)) { + positions.add(head); + } + } + + return positions; + } + + private boolean isValidSpot(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return false; + } + + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + if (safety.getValue() && player.getBoundingBox().intersects(new AABB(pos))) { + return false; + } + + if (!level.getEntitiesOfClass(Entity.class, new AABB(pos), entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + double rangeSq = placeRange.getValue() * placeRange.getValue(); + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + return false; + } + + return airPlace.getValue() || buildHitResult(pos) != null; + } + + private void placeBlocks(List positions) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return; + } + + int obbySlot = findObsidianSlot(); + + boolean holdingObby = player.getMainHandItem().getItem() == Items.OBSIDIAN + || player.getOffhandItem().getItem() == Items.OBSIDIAN; + + if (obbySlot == -1 && !holdingObby) { + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + int placed = 0; + + for (BlockPos pos : positions) { + if (placed >= maxPlacesPerTick.getValue()) { + break; + } + + if (attack.getValue()) { + attackBlockingCrystals(pos); + } + + if (!holdingObby && !switched) { + if (!doSwitch(obbySlot, oldSlot)) { + break; + } + + switched = true; + } + + if (!applyRotations(Vec3.atCenterOf(pos))) { + continue; + } + + boolean success = place(pos); + + if (!success && support.getValue()) { + BlockPos below = pos.below(); + + if (isValidSpot(below)) { + if (applyRotations(Vec3.atCenterOf(below)) && place(below)) { + placed++; + + if (applyRotations(Vec3.atCenterOf(pos))) { + success = place(pos); + } + } + } + } + + if (success) { + placed++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + } + + private boolean place(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + } + + private int findObsidianSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).getItem() == Items.OBSIDIAN) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).getItem() == Items.OBSIDIAN) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).getItem() == Items.OBSIDIAN) { + return i; + } + } + + return -1; + } + + private void attackBlockingCrystals(BlockPos pos) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + BlockPos[] checks = new BlockPos[]{ + pos, + pos.above() + }; + + for (BlockPos check : checks) { + AABB box = new AABB(check); + + Entity crystal = level.getEntitiesOfClass( + Entity.class, + box, + entity -> entity instanceof EndCrystal && entity.isAlive() + ).stream().findFirst().orElse(null); + + if (crystal == null) { + continue; + } + + player.connection.send(ServerboundInteractPacket.createAttackPacket(crystal, player.isShiftKeyDown())); + player.connection.send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND)); + return; + } + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private boolean isStationary(Player player) { + Vec3 velocity = player.getDeltaMovement(); + double horizontalSpeedSq = (velocity.x * velocity.x) + (velocity.z * velocity.z); + + return horizontalSpeedSq <= STATIONARY_EPSILON; + } + + private List getTargets() { + List targets = new ArrayList<>(); + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return targets; + } + + for (Player other : level.players()) { + if (other == player) { + continue; + } + + if (!other.isAlive()) { + continue; + } + + try { + if (nolongerhuman.friendManager.isFriend(other)) { + continue; + } + } catch (Exception ignored) { + } + + if (player.distanceTo(other) > enemyRange.getValue()) { + continue; + } + + targets.add(other); + } + + return targets; + } + + private Player getTarget() { + LocalPlayer player = mc.player; + + if (player == null) { + return null; + } + + List targets = getTargets(); + + if (targets.isEmpty()) { + return null; + } + + return switch (targetMode.getValue()) { + case LowestHealth -> { + Player best = null; + double minHealth = Double.MAX_VALUE; + + for (Player target : targets) { + double health = target.getHealth() + target.getAbsorptionAmount(); + + if (health < minHealth) { + minHealth = health; + best = target; + } + } + + yield best; + } + + case Closest -> { + Player nearest = null; + double nearestDistance = Double.MAX_VALUE; + + for (Player target : targets) { + double distance = player.distanceTo(target); + + if (distance < nearestDistance) { + nearestDistance = distance; + nearest = target; + } + } + + yield nearest; + } + }; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + renderFill.getValue(), + renderOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CrystalBlocker.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CrystalBlocker.java new file mode 100644 index 0000000..445daae --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/CrystalBlocker.java @@ -0,0 +1,869 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class CrystalBlocker extends Module { + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + public enum Priority { + HighestDamage, + Closest + } + + private static final String ROT_ID = "crystalblocker"; + private static final int ROT_PRIORITY = 3; + + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting priority = mode("Priority", Priority.HighestDamage); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting multitask = bool("MultiTask", true); + public final Setting rotate = bool("Rotate", true); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting crystalRange = num("CrystalRange", 8.0, 1.0, 16.0); + public final Setting placeRange = num("PlaceRange", 5.0f, 0.0f, 6.0f); + public final Setting wallsRange = num("WallsRange", 3.5f, 0.0f, 6.0f); + public final Setting minDamage = num("MinDamage", 6.0, 0.0, 36.0); + public final Setting explosionDamage = num("ExplosionDamage", 4.0, 0.0, 36.0); + public final Setting delay = num("Delay", 0, 0, 20); + public final Setting obsidian = bool("Obsidian", true); + public final Setting enderChest = bool("EnderChest", true); + public final Setting anchors = bool("Anchors", true); + public final Setting netherite = bool("Netherite", false); + public final Setting ancientDebris = bool("AncientDebris", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(80, 160, 255, 45)); + public final Setting outlineColor = color("OutlineColor", new Color(80, 160, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private int ticks = 0; + private int invSwapSlot = -1; + private double lastDamage = 0.0D; + private float lastHealth = -1.0F; + private int damageBypassTicks = 0; + private BlockPos lastPlacedBlock = null; + private BlockPos lastPlacementPlayerPos = null; + private int lastCrystalId = -1; + + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + public CrystalBlocker() { + super("CrystalBlocker", "Places blast-resistant blocks between you and dangerous end crystals.", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = 0; + invSwapSlot = -1; + lastDamage = 0.0D; + lastHealth = -1.0F; + damageBypassTicks = 0; + lastPlacedBlock = null; + lastPlacementPlayerPos = null; + lastCrystalId = -1; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + ticks = 0; + invSwapSlot = -1; + lastDamage = 0.0D; + lastHealth = -1.0F; + damageBypassTicks = 0; + lastPlacedBlock = null; + lastPlacementPlayerPos = null; + lastCrystalId = -1; + renderPositions.clear(); + renderFadeState.reset(); + clearRotations(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + boolean tookExplosionDamage = updateDamageBypass(player); + + if (tookExplosionDamage) { + ticks = delay.getValue(); + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + renderPositions.clear(); + + boolean allowBlockedRecheck = damageBypassTicks > 0; + CrystalPlan plan = getBestCrystalPlan(player, level, allowBlockedRecheck); + + if (plan == null) { + ticks = 0; + lastDamage = 0.0D; + decrementDamageBypass(); + return; + } + + lastDamage = plan.damage(); + + if (!allowBlockedRecheck && lastPlacedBlockStillUseful(player, level, plan.crystal())) { + renderPositions.add(lastPlacedBlock); + ticks = 0; + decrementDamageBypass(); + return; + } + + BlockPos currentPlayerPos = player.blockPosition(); + boolean playerMovedSinceLastPlacement = lastPlacementPlayerPos == null || !lastPlacementPlayerPos.equals(currentPlayerPos); + + if (!playerMovedSinceLastPlacement && !allowBlockedRecheck) { + ticks = 0; + decrementDamageBypass(); + return; + } + + BlockPos pos = plan.blockPos(); + + if (pos == null) { + ticks = 0; + decrementDamageBypass(); + return; + } + + if (cannotPlaceAt(level, player, pos)) { + ticks = 0; + decrementDamageBypass(); + return; + } + + if (!airPlace.getValue() && findPlaceDirection(level, player, pos, strictDirection.getValue()) == null) { + ticks = 0; + decrementDamageBypass(); + return; + } + + renderPositions.add(pos); + + int slot = findBlockSlot(player); + + if (slot == -1) { + ticks = 0; + decrementDamageBypass(); + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + + if (!doSwitch(player, slot, oldSlot)) { + ticks = 0; + decrementDamageBypass(); + return; + } + + if (rotate.getValue()) { + applyRotations(Vec3.atCenterOf(pos)); + } + + if (placeBlock(player, gameMode, pos)) { + lastPlacedBlock = pos.immutable(); + lastPlacementPlayerPos = currentPlayerPos.immutable(); + lastCrystalId = plan.crystal().getId(); + damageBypassTicks = 0; + } + + switchBack(player, oldSlot); + resetSpoofIfNeeded(); + ticks = 0; + } + + private boolean updateDamageBypass(LocalPlayer player) { + float currentHealth = player.getHealth() + player.getAbsorptionAmount(); + + if (lastHealth < 0.0F) { + lastHealth = currentHealth; + return false; + } + + float lost = lastHealth - currentHealth; + lastHealth = currentHealth; + + if (lost >= explosionDamage.getValue()) { + damageBypassTicks = 2; + return true; + } + + return false; + } + + private void decrementDamageBypass() { + if (damageBypassTicks > 0) { + damageBypassTicks--; + } + } + + private CrystalPlan getBestCrystalPlan(LocalPlayer player, ClientLevel level, boolean allowBlockedRecheck) { + List plans = new ArrayList<>(); + double rangeSq = crystalRange.getValue() * crystalRange.getValue(); + + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof EndCrystal crystal)) { + continue; + } + + if (!crystal.isAlive()) { + continue; + } + + if (player.distanceToSqr(crystal) > rangeSq) { + continue; + } + + double damage = getCrystalDamage(crystal, player); + + if (damage < minDamage.getValue()) { + continue; + } + + Vec3 crystalVec = getCrystalVec(crystal); + + if (hasBlockingBlockBetween(level, player, crystalVec) && !allowBlockedRecheck) { + continue; + } + + BlockPos blockPos = findBestBlockPosition(player, level, crystal); + + if (blockPos == null) { + continue; + } + + plans.add(new CrystalPlan(crystal, blockPos.immutable(), damage)); + } + + if (plans.isEmpty()) { + return null; + } + + sortPlans(player, plans); + return plans.get(0); + } + + private void sortPlans(LocalPlayer player, List plans) { + switch (priority.getValue()) { + case Closest -> plans.sort(Comparator.comparingDouble(plan -> player.distanceToSqr(plan.crystal()))); + case HighestDamage -> plans.sort((a, b) -> Double.compare(b.damage(), a.damage())); + } + } + + private double getCrystalDamage(EndCrystal crystal, LocalPlayer player) { + double distance = player.position().distanceTo(crystal.position()); + + if (distance > 12.0D) { + return 0.0D; + } + + double factor = 1.0D - distance / 12.0D; + return Math.max(0.0D, (factor * factor + factor) * 42.0D + 1.0D); + } + + private BlockPos findBestBlockPosition(LocalPlayer player, ClientLevel level, EndCrystal crystal) { + List candidates = getCrystalBlockCandidates(player, crystal); + + BlockPos best = null; + double bestScore = Double.NEGATIVE_INFINITY; + + Vec3 playerEye = player.getEyePosition(); + Vec3 crystalVec = getCrystalVec(crystal); + int crystalY = crystal.blockPosition().getY(); + + for (BlockPos pos : candidates) { + if (!isRequiredPlacementY(pos, crystalY)) { + continue; + } + + if (!isBetweenHorizontal(crystalVec, playerEye, pos)) { + continue; + } + + if (cannotPlaceAt(level, player, pos)) { + continue; + } + + if (!canReach(player, level, pos)) { + continue; + } + + double score = scoreBlockPosition(playerEye, crystalVec, pos, crystalY); + + if (score > bestScore) { + bestScore = score; + best = pos; + } + } + + return best; + } + + private List getCrystalBlockCandidates(LocalPlayer player, EndCrystal crystal) { + return getLineBlockCandidates(player, getCrystalVec(crystal), crystal.blockPosition().getY()); + } + + private List getLineBlockCandidates(LocalPlayer player, Vec3 targetVec, int targetY) { + List candidates = new ArrayList<>(); + + Vec3 playerEye = player.getEyePosition(); + + double dx = playerEye.x - targetVec.x; + double dz = playerEye.z - targetVec.z; + double horizontalDistance = Math.sqrt(dx * dx + dz * dz); + + if (horizontalDistance < 0.25D) { + return candidates; + } + + int samples = Math.max(2, (int) Math.ceil(horizontalDistance * 4.0D)); + + for (int i = 1; i < samples; i++) { + double t = i / (double) samples; + double x = targetVec.x + dx * t; + double z = targetVec.z + dz * t; + + addCandidate(candidates, new BlockPos((int) Math.floor(x), targetY, (int) Math.floor(z))); + addCandidate(candidates, new BlockPos((int) Math.floor(x), targetY - 1, (int) Math.floor(z))); + } + + return candidates; + } + + private void addCandidate(List candidates, BlockPos pos) { + if (!candidates.contains(pos)) { + candidates.add(pos); + } + } + + private boolean isRequiredPlacementY(BlockPos pos, int targetY) { + return pos.getY() == targetY || pos.getY() == targetY - 1; + } + + private boolean isBetweenHorizontal(Vec3 targetVec, Vec3 playerVec, BlockPos pos) { + Vec3 center = Vec3.atCenterOf(pos); + + double lineX = playerVec.x - targetVec.x; + double lineZ = playerVec.z - targetVec.z; + double lengthSq = lineX * lineX + lineZ * lineZ; + + if (lengthSq <= 0.0001D) { + return false; + } + + double pointX = center.x - targetVec.x; + double pointZ = center.z - targetVec.z; + double t = (pointX * lineX + pointZ * lineZ) / lengthSq; + + if (t <= 0.05D || t >= 0.95D) { + return false; + } + + return horizontalDistanceToSegment(center, targetVec, playerVec) <= 1.25D; + } + + private boolean hasBlockingBlockBetween(ClientLevel level, LocalPlayer player, Vec3 targetVec) { + Vec3 playerEye = player.getEyePosition(); + Vec3 delta = playerEye.subtract(targetVec); + + if (delta.lengthSqr() <= 0.0001D) { + return false; + } + + Vec3 start = targetVec.add(delta.normalize().scale(0.75D)); + + HitResult result = level.clip(new ClipContext( + start, + playerEye, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.BLOCK; + } + + private boolean lastPlacedBlockStillUseful(LocalPlayer player, ClientLevel level, EndCrystal crystal) { + if (lastPlacedBlock == null || lastCrystalId == -1) { + return false; + } + + if (lastCrystalId != crystal.getId()) { + return false; + } + + if (!crystal.isAlive()) { + return false; + } + + BlockState state = level.getBlockState(lastPlacedBlock); + + if (state.isAir() || state.canBeReplaced()) { + return false; + } + + int crystalY = crystal.blockPosition().getY(); + + if (!isRequiredPlacementY(lastPlacedBlock, crystalY)) { + return false; + } + + Vec3 crystalVec = getCrystalVec(crystal); + Vec3 playerEye = player.getEyePosition(); + Vec3 blockCenter = Vec3.atCenterOf(lastPlacedBlock); + + return isBetweenHorizontal(crystalVec, playerEye, lastPlacedBlock) + && horizontalDistanceToSegment(blockCenter, crystalVec, playerEye) <= 0.95D; + } + + private double scoreBlockPosition(Vec3 playerEye, Vec3 targetVec, BlockPos pos, int targetY) { + Vec3 center = Vec3.atCenterOf(pos); + + double distToLine = horizontalDistanceToSegment(center, targetVec, playerEye); + double distToTarget = horizontalDistance(center, targetVec); + double distToPlayer = horizontalDistance(center, playerEye); + double yPenalty = pos.getY() == targetY ? 0.0D : 0.5D; + + return -distToLine * 10.0D + - distToTarget * 1.0D + - distToPlayer * 0.15D + - yPenalty; + } + + private double horizontalDistance(Vec3 a, Vec3 b) { + double dx = a.x - b.x; + double dz = a.z - b.z; + + return Math.sqrt(dx * dx + dz * dz); + } + + private double horizontalDistanceToSegment(Vec3 point, Vec3 start, Vec3 end) { + double lineX = end.x - start.x; + double lineZ = end.z - start.z; + double lengthSq = lineX * lineX + lineZ * lineZ; + + if (lengthSq <= 0.0001D) { + return horizontalDistance(point, start); + } + + double pointX = point.x - start.x; + double pointZ = point.z - start.z; + double t = (pointX * lineX + pointZ * lineZ) / lengthSq; + + t = Math.max(0.0D, Math.min(1.0D, t)); + + double closestX = start.x + lineX * t; + double closestZ = start.z + lineZ * t; + + double dx = point.x - closestX; + double dz = point.z - closestZ; + + return Math.sqrt(dx * dx + dz * dz); + } + + private boolean canReach(LocalPlayer player, ClientLevel level, BlockPos pos) { + Vec3 eye = player.getEyePosition(); + Vec3 center = Vec3.atCenterOf(pos); + double distance = eye.distanceTo(center); + + if (distance <= placeRange.getValue() && hasLineOfSight(player, level, eye, center)) { + return true; + } + + return distance <= wallsRange.getValue(); + } + + private boolean hasLineOfSight(LocalPlayer player, ClientLevel level, Vec3 from, Vec3 to) { + HitResult result = level.clip(new ClipContext( + from, + to, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.MISS; + } + + private boolean placeBlock(LocalPlayer player, MultiPlayerGameMode gameMode, BlockPos pos) { + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Direction directionToNeighbor = findPlaceDirection(level, player, pos, strictDirection.getValue()); + + if (directionToNeighbor == null) { + return null; + } + + BlockPos neighbor = pos.relative(directionToNeighbor); + Direction hitSide = directionToNeighbor.getOpposite(); + + Vec3 hitVec = Vec3.atCenterOf(neighbor).add( + hitSide.getStepX() * 0.5D, + hitSide.getStepY() * 0.5D, + hitSide.getStepZ() * 0.5D + ); + + return new BlockHitResult(hitVec, hitSide, neighbor, false); + } + + private Direction findPlaceDirection(ClientLevel level, LocalPlayer player, BlockPos pos, boolean strictDir) { + Direction bestDirection = null; + double bestDistance = Double.MAX_VALUE; + Vec3 eye = player.getEyePosition(); + + for (Direction direction : Direction.values()) { + BlockPos neighbor = pos.relative(direction); + BlockState neighborState = level.getBlockState(neighbor); + + if (neighborState.isAir() || neighborState.canBeReplaced()) { + continue; + } + + if (neighborState.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction hitSide = direction.getOpposite(); + + Vec3 faceCenter = Vec3.atCenterOf(neighbor).add( + hitSide.getStepX() * 0.5D, + hitSide.getStepY() * 0.5D, + hitSide.getStepZ() * 0.5D + ); + + if (strictDir) { + Vec3 toEye = eye.subtract(faceCenter).normalize(); + + Vec3 faceNormal = new Vec3( + hitSide.getStepX(), + hitSide.getStepY(), + hitSide.getStepZ() + ).normalize(); + + if (toEye.dot(faceNormal) <= 0.0D) { + continue; + } + } + + double distance = eye.distanceTo(faceCenter); + + if (distance < bestDistance) { + bestDistance = distance; + bestDirection = direction; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + return bestDirection; + } + + private boolean cannotPlaceAt(ClientLevel level, LocalPlayer player, BlockPos pos) { + if (level.isOutsideBuildHeight(pos)) { + return true; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return true; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return true; + } + + if (player.getBoundingBox().intersects(box)) { + return true; + } + + return !airPlace.getValue() && buildHitResult(pos) == null; + } + + private int findBlockSlot(LocalPlayer player) { + int selected = player.getInventory().getSelectedSlot(); + + if (isValidBlock(player.getInventory().getItem(selected))) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (isValidBlock(player.getInventory().getItem(i))) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (isValidBlock(player.getInventory().getItem(i))) { + return i; + } + } + + return -1; + } + + private boolean isValidBlock(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return false; + } + + if (!(stack.getItem() instanceof BlockItem blockItem)) { + return false; + } + + return isResistant(blockItem.getBlock()); + } + + private boolean isResistant(Block block) { + if (obsidian.getValue() && (block == Blocks.OBSIDIAN || block == Blocks.CRYING_OBSIDIAN)) { + return true; + } + + if (enderChest.getValue() && block == Blocks.ENDER_CHEST) { + return true; + } + + if (anchors.getValue() && block == Blocks.RESPAWN_ANCHOR) { + return true; + } + + if (netherite.getValue() && block == Blocks.NETHERITE_BLOCK) { + return true; + } + + return ancientDebris.getValue() && block == Blocks.ANCIENT_DEBRIS; + } + + private boolean doSwitch(LocalPlayer player, int slot, int currentHotbarSlot) { + if (mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(LocalPlayer player, int oldSlot) { + boolean shouldRestoreSlot = switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1; + + if (shouldRestoreSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot == -1) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + + private Vec3 getCrystalVec(EndCrystal crystal) { + return new Vec3( + crystal.getX(), + crystal.getY() + 0.5D, + crystal.getZ() + ); + } + + private void applyRotations(Vec3 vec) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + @Override + public void onRender3D(Render3DEvent event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (!render.getValue() || player == null || level == null) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + @Override + public String getDisplayInfo() { + if (lastDamage <= 0.0D) { + return String.valueOf(renderPositions.size()); + } + + return String.format("%.1f", lastDamage); + } + + private record CrystalPlan(EndCrystal crystal, BlockPos blockPos, double damage) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/ElytraBlocker.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/ElytraBlocker.java new file mode 100644 index 0000000..c413810 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/ElytraBlocker.java @@ -0,0 +1,683 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +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.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class ElytraBlocker extends Module { + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + public enum BlockMode { + Trap, + Wall, + Both + } + + public enum TargetMode { + Equipped, + Flying, + Both + } + + private static final String ROT_ID = "elytra-blocker"; + private static final int ROT_PRIORITY = 4; + + public final Setting multitask = bool("MultiTask", true); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting blockMode = mode("BlockMode", BlockMode.Both); + public final Setting targetMode = mode("Target", TargetMode.Both); + public final Setting range = num("Range", 5.0f, 1.0f, 6.0f); + public final Setting blocksPerTick = num("ShiftTicks", 4, 1, 12); + public final Setting delay = num("Delay", 0, 0, 20); + public final Setting support = bool("Support", true); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting targetRange = num("TargetRange", 8.0, 2.0, 16.0); + public final Setting minFlySpeed = num("MinFlySpeed", 0.1, 0.0, 3.0); + public final Setting trapFeet = bool("TrapFeet", true); + public final Setting trapHead = bool("TrapHead", true); + public final Setting trapRoof = bool("TrapRoof", true); + public final Setting blockPath = bool("BlockPath", true); + public final Setting blockIncoming = bool("BlockIncoming", true); + public final Setting blockEscaping = bool("BlockEscaping", true); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 70)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.0f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final Timer timer = new Timer(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private int ticks; + private int invSwapSlot; + + public ElytraBlocker() { + super("ElytraBlocker", "Blocks elytra users with blocks", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = delay.getValue(); + invSwapSlot = -1; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + clearRotations(); + ticks = 0; + invSwapSlot = -1; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + if (!timer.passedMs(1L)) { + return; + } + + Player target = findTarget(player, level); + + if (target == null) { + renderPositions.clear(); + ticks = 0; + timer.reset(); + return; + } + + List positions = getBlockPositions(player, target); + positions.removeIf(this::canAttemptPlace); + positions.sort(Comparator.comparingDouble(pos -> player.distanceToSqr(Vec3.atCenterOf(pos)))); + + renderPositions.clear(); + renderPositions.addAll(positions); + + if (positions.isEmpty()) { + ticks = 0; + timer.reset(); + return; + } + + int blockSlot = findBlockSlot(); + + if (blockSlot == -1) { + ticks = 0; + timer.reset(); + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + int placed = 0; + + for (BlockPos pos : positions) { + if (placed >= blocksPerTick.getValue()) { + break; + } + + if (!switched) { + if (!doSwitch(blockSlot, oldSlot)) { + break; + } + + switched = true; + } + + if (placeWithSupport(pos)) { + placed++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + ticks = 0; + timer.reset(); + } + + private Player findTarget(LocalPlayer player, ClientLevel level) { + Player bestTarget = null; + double bestDistance = Double.MAX_VALUE; + + for (Player target : level.players()) { + if (!isValidTarget(player, target)) { + continue; + } + + double distance = player.distanceToSqr(target); + + if (distance < bestDistance) { + bestDistance = distance; + bestTarget = target; + } + } + + return bestTarget; + } + + private boolean isValidTarget(LocalPlayer player, Player target) { + if (target == player) { + return false; + } + + if (target.isDeadOrDying() || target.isSpectator() || target.isCreative()) { + return false; + } + + if (player.distanceTo(target) > targetRange.getValue()) { + return false; + } + + boolean equipped = isWearingElytra(target) || isHoldingElytra(target); + boolean flying = target.isFallFlying(); + boolean fastEnough = horizontalSpeed(target.getDeltaMovement()) >= minFlySpeed.getValue(); + + return switch (targetMode.getValue()) { + case Equipped -> equipped; + case Flying -> flying || fastEnough && equipped; + case Both -> equipped || flying || fastEnough; + }; + } + + private boolean isWearingElytra(Player player) { + return isElytra(player.getItemBySlot(EquipmentSlot.CHEST)); + } + + private boolean isHoldingElytra(Player player) { + return isElytra(player.getMainHandItem()) || isElytra(player.getOffhandItem()); + } + + private boolean isElytra(ItemStack stack) { + return stack.is(Items.ELYTRA); + } + + private List getBlockPositions(LocalPlayer player, Player target) { + Set positions = new LinkedHashSet<>(); + + if (blockMode.getValue() == BlockMode.Trap || blockMode.getValue() == BlockMode.Both) { + addTrapPositions(target, positions); + } + + if (blockMode.getValue() == BlockMode.Wall || blockMode.getValue() == BlockMode.Both) { + addWallPositions(player, target, positions); + } + + return new ArrayList<>(positions); + } + + private void addTrapPositions(Player target, Set positions) { + BlockPos base = target.blockPosition(); + + if (trapFeet.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.relative(dir)); + } + } + + if (trapHead.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.above().relative(dir)); + } + } + + if (trapRoof.getValue()) { + positions.add(base.above(2)); + } + } + + private void addWallPositions(LocalPlayer player, Player target, Set positions) { + Vec3 targetVelocity = target.getDeltaMovement(); + + if (blockPath.getValue() && targetVelocity.lengthSqr() > 0.01D) { + addPathWall(target, targetVelocity, positions); + } + + Vec3 playerToTarget = target.position().subtract(player.position()); + double closingDot = playerToTarget.dot(targetVelocity); + + if (blockIncoming.getValue() && closingDot < 0.0D) { + addBetweenWall(player.position(), target.position(), positions); + } + + if (blockEscaping.getValue() && closingDot > 0.0D) { + addEscapeWall(target, targetVelocity, positions); + } + } + + private void addPathWall(Player target, Vec3 velocity, Set positions) { + Vec3 direction = new Vec3(velocity.x, 0.0D, velocity.z); + + if (direction.lengthSqr() < 0.0001D) { + return; + } + + direction = direction.normalize(); + + Vec3 first = target.position().add(direction.scale(1.0D)); + Vec3 second = target.position().add(direction.scale(2.0D)); + + addColumn(toBlockPos(first), positions); + addColumn(toBlockPos(second), positions); + } + + private void addBetweenWall(Vec3 playerPos, Vec3 targetPos, Set positions) { + addLineColumn(playerPos, targetPos, 0.35D, positions); + addLineColumn(playerPos, targetPos, 0.50D, positions); + addLineColumn(playerPos, targetPos, 0.65D, positions); + } + + private void addEscapeWall(Player target, Vec3 velocity, Set positions) { + Vec3 direction = new Vec3(velocity.x, 0.0D, velocity.z); + + if (direction.lengthSqr() < 0.0001D) { + direction = getLookDirection(target); + } + + direction = direction.normalize(); + + addColumn(toBlockPos(target.position().add(direction.scale(1.0D))), positions); + addColumn(toBlockPos(target.position().add(direction.scale(2.0D))), positions); + } + + private Vec3 getLookDirection(Player player) { + double yaw = Math.toRadians(player.getYRot()); + return new Vec3(-Math.sin(yaw), 0.0D, Math.cos(yaw)); + } + + private void addLineColumn(Vec3 from, Vec3 to, double factor, Set positions) { + Vec3 pos = from.lerp(to, factor); + addColumn(toBlockPos(pos), positions); + } + + private void addColumn(BlockPos base, Set positions) { + positions.add(base); + positions.add(base.above()); + positions.add(base.above(2)); + } + + private BlockPos toBlockPos(Vec3 vec) { + return new BlockPos(Mth.floor(vec.x), Mth.floor(vec.y), Mth.floor(vec.z)); + } + + private boolean placeWithSupport(BlockPos pos) { + if (applyRotations(Vec3.atCenterOf(pos))) { + return false; + } + + if (place(pos)) { + return true; + } + + if (!support.getValue()) { + return false; + } + + BlockPos supportPos = pos.below(); + + if (canAttemptPlace(supportPos)) { + return false; + } + + if (applyRotations(Vec3.atCenterOf(supportPos))) { + return false; + } + + if (!place(supportPos)) { + return false; + } + + if (applyRotations(Vec3.atCenterOf(pos))) { + return false; + } + + return place(pos); + } + + private boolean place(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5D, + side.getStepY() * 0.5D, + side.getStepZ() * 0.5D + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean canAttemptPlace(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return true; + } + + if (level.isOutsideBuildHeight(pos)) { + return true; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return true; + } + + double rangeSq = range.getValue() * range.getValue(); + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + return true; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return true; + } + + return !airPlace.getValue() && buildHitResult(pos) == null && !support.getValue(); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return false; + } + + return !rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + int targetSlot = slot; + + if (targetSlot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + targetSlot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = targetSlot; + targetSlot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(targetSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(targetSlot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == targetSlot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + } + + private int findBlockSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (isBlockItem(player.getInventory().getItem(selected).getItem())) { + return selected; + } + + for (int slot = 0; slot < 9; slot++) { + if (isBlockItem(player.getInventory().getItem(slot).getItem())) { + return slot; + } + } + + for (int slot = 9; slot < 36; slot++) { + if (isBlockItem(player.getInventory().getItem(slot).getItem())) { + return slot; + } + } + + return -1; + } + + private boolean isBlockItem(Item item) { + return item == Items.OBSIDIAN + || item == Items.CRYING_OBSIDIAN + || item == Items.ENDER_CHEST; + } + + private double horizontalSpeed(Vec3 velocity) { + return Math.sqrt((velocity.x * velocity.x) + (velocity.z * velocity.z)); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleBuilder.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleBuilder.java new file mode 100644 index 0000000..fbbd11c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleBuilder.java @@ -0,0 +1,719 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HoleBuilder extends Module { + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + public enum Priority { + Distance, + ClosestToFeet, + HeadFirst + } + + private static final String ROT_ID = "holebuilder"; + private static final int ROT_PRIORITY = 500; + + public final Setting multitask = bool("MultiTask", false); + public final Setting onlyOnGround = bool("OnlyGround", true); + public final Setting enderChestFallback = bool("EnderChestFallback", true); + public final Setting cryingObsidian = bool("CryingObsidian", true); + public final Setting attack = bool("Attack", true); + public final Setting support = bool("Support", false); + public final Setting await = bool("Await", false); + public final Setting blocksPerTick = num("ShiftTicks", 4, 1, 12); + public final Setting shiftDelay = num("ShiftDelay", 0, 0, 5); + public final Setting delay = num("Delay", 0, 0, 500); + public final Setting range = num("Range", 5.0, 1.0, 6.0); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting priority = mode("Priority", Priority.ClosestToFeet); + + public final Setting render = bool("Render", true); + public final Setting renderFill = color("RenderFill", new Color(255, 255, 255, 87)); + public final Setting renderOutline = color("RenderOutline", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.0f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private int blocksPlaced; + private List placements = new ArrayList<>(); + private final Map packets = new HashMap<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private long lastPlaceTime = 0L; + private int invSwapSlot = -1; + + public HoleBuilder() { + super("HoleBuilder", "Completes the partial hole you are standing in", Category.COMBAT); + } + + @Override + public void onEnable() { + if (mc.player == null || mc.level == null) { + disable(); + return; + } + + invSwapSlot = -1; + lastPlaceTime = 0L; + packets.clear(); + placements.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + placements.clear(); + packets.clear(); + renderFadeState.reset(); + invSwapSlot = -1; + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (onlyOnGround.getValue() && !player.onGround()) { + return; + } + + blocksPlaced = 0; + + long now = System.currentTimeMillis(); + prunePackets(now); + + if (now - lastPlaceTime < delay.getValue()) { + return; + } + + int slot = findFillSlot(); + + if (slot == -1) { + return; + } + + placements = getCompletionPlacements(level, now); + + if (placements.isEmpty()) { + return; + } + + if (attack.getValue()) { + attackBlockingCrystals(placements); + } + + sortPlacements(); + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + + List placedThisTick = new ArrayList<>(); + int limit = blocksPerTick.getValue(); + + for (BlockPos targetPos : placements) { + if (blocksPlaced >= limit) { + break; + } + + if (!switched) { + if (!doSwitch(slot, oldSlot)) { + break; + } + + switched = true; + } + + if (!applyRotations(Vec3.atCenterOf(targetPos))) { + break; + } + + boolean placed = placeBlock(targetPos); + + if (!placed && support.getValue()) { + BlockPos below = targetPos.below(); + + boolean belowFree = level.getBlockState(below).isAir() + || level.getBlockState(below).canBeReplaced(); + + if (belowFree + && !placedThisTick.contains(below) + && !placements.contains(below) + && isInRange(below) + && (airPlace.getValue() || buildHitResult(below) != null)) { + if (applyRotations(Vec3.atCenterOf(below)) && placeBlock(below)) { + blocksPlaced++; + placedThisTick.add(below); + + if (blocksPlaced >= limit) { + break; + } + + if (await.getValue()) { + continue; + } + + if (applyRotations(Vec3.atCenterOf(targetPos))) { + placed = placeBlock(targetPos); + } + } + } + } + + if (placed) { + blocksPlaced++; + placedThisTick.add(targetPos); + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + } + + private List getCompletionPlacements(Level level, long now) { + List result = new ArrayList<>(); + + if (mc.player == null) { + return result; + } + + BlockPos hole = mc.player.blockPosition(); + + if (nolongerhuman.holeManager != null) { + if (!nolongerhuman.holeManager.isPartialHole(level, hole)) { + return result; + } + } else if (!isIncompleteHole(level, hole)) { + return result; + } + + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos side = hole.relative(dir); + + if (isSolid(level, side)) { + continue; + } + + if (result.contains(side)) { + continue; + } + + if (!isInRange(side)) { + continue; + } + + BlockState sideState = level.getBlockState(side); + boolean free = sideState.isAir() || sideState.canBeReplaced(); + + if (!free) { + continue; + } + + Long placed = packets.get(side); + + if (shiftDelay.getValue() > 0 + && placed != null + && now - placed < shiftDelay.getValue() * 50L) { + continue; + } + + BlockPos below = side.below(); + BlockState belowState = level.getBlockState(below); + boolean belowSolid = isSolid(level, below); + boolean belowFree = belowState.isAir() || belowState.canBeReplaced(); + + boolean directlyPlaceable = airPlace.getValue() || buildHitResult(side) != null; + + boolean supportable = support.getValue() + && belowFree + && isInRange(below) + && (airPlace.getValue() || buildHitResult(below) != null); + + if (!belowSolid && !supportable) { + continue; + } + + if (directlyPlaceable || supportable) { + result.add(side); + } + } + + return result; + } + + private boolean isIncompleteHole(Level level, BlockPos pos) { + if (!level.getBlockState(pos).isAir()) { + return false; + } + + if (nolongerhuman.holeManager != null && nolongerhuman.holeManager.isNormalHole(pos)) { + return false; + } + + if (!isSolid(level, pos.below())) { + return false; + } + + if (!level.getBlockState(pos.above()).isAir()) { + return false; + } + + if (!level.getBlockState(pos.above(2)).isAir()) { + return false; + } + + int solidSides = 0; + BlockPos openSide = null; + + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos neighbor = pos.relative(dir); + + if (isSolid(level, neighbor)) { + solidSides++; + } else { + openSide = neighbor; + } + } + + if (solidSides != 3) { + return false; + } + + return openSide != null && isSolid(level, openSide.below()); + } + + private boolean isSolid(Level level, BlockPos pos) { + BlockState state = level.getBlockState(pos); + return state.isCollisionShapeFullBlock(level, pos); + } + + private void prunePackets(long now) { + long maxAge = Math.max(1000L, shiftDelay.getValue() * 50L + 500L); + packets.entrySet().removeIf(entry -> now - entry.getValue() > maxAge); + } + + private void sortPlacements() { + if (mc.player == null) { + return; + } + + int feetY = mc.player.getBlockY(); + + placements.sort((a, b) -> { + switch (priority.getValue()) { + case HeadFirst -> { + int yComp = Integer.compare(b.getY(), a.getY()); + + if (yComp != 0) { + return yComp; + } + } + + case ClosestToFeet -> { + int aDist = Math.abs(a.getY() - feetY); + int bDist = Math.abs(b.getY() - feetY); + int yComp = Integer.compare(aDist, bDist); + + if (yComp != 0) { + return yComp; + } + } + + case Distance -> { + } + } + + return Double.compare(distSq(a), distSq(b)); + }); + } + + private double distSq(BlockPos pos) { + if (mc.player == null) { + return Double.MAX_VALUE; + } + + return mc.player.distanceToSqr(Vec3.atCenterOf(pos)); + } + + private boolean isInRange(BlockPos pos) { + if (mc.player == null) { + return false; + } + + return mc.player.distanceToSqr(Vec3.atCenterOf(pos)) <= range.getValue() * range.getValue(); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private int findFillSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (isFillBlock(player.getInventory().getItem(selected).getItem())) { + return selected; + } + + int obby = findItemSlot(Items.OBSIDIAN); + + if (obby != -1) { + return obby; + } + + if (cryingObsidian.getValue()) { + int crying = findItemSlot(Items.CRYING_OBSIDIAN); + + if (crying != -1) { + return crying; + } + } + + if (enderChestFallback.getValue()) { + return findItemSlot(Items.ENDER_CHEST); + } + + return -1; + } + + private int findItemSlot(Item item) { + if (mc.player == null) { + return -1; + } + + for (int i = 0; i < 9; i++) { + if (mc.player.getInventory().getItem(i).getItem() == item) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (mc.player.getInventory().getItem(i).getItem() == item) { + return i; + } + } + + return -1; + } + + private boolean isFillBlock(Item item) { + if (item == Items.OBSIDIAN) { + return true; + } + + if (cryingObsidian.getValue() && item == Items.CRYING_OBSIDIAN) { + return true; + } + + return enderChestFallback.getValue() && item == Items.ENDER_CHEST; + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + } + + private boolean placeBlock(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || mc.level == null || gameMode == null) { + return false; + } + + if (attack.getValue()) { + attackBlockingCrystals(Collections.singletonList(pos)); + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + + long now = System.currentTimeMillis(); + packets.put(pos, now); + lastPlaceTime = now; + + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private void attackBlockingCrystals(List posList) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + for (BlockPos pos : posList) { + for (BlockPos check : new BlockPos[]{pos, pos.above()}) { + AABB box = new AABB(check); + + Entity crystalEntity = level.getEntitiesOfClass( + Entity.class, + box, + entity -> entity instanceof EndCrystal && entity.isAlive() + ).stream().findFirst().orElse(null); + + if (crystalEntity == null) { + continue; + } + + player.connection.send(ServerboundInteractPacket.createAttackPacket( + crystalEntity, + player.isShiftKeyDown() + )); + + player.connection.send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND)); + return; + } + } + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + placements, + renderFill.getValue(), + renderOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleFill.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleFill.java new file mode 100644 index 0000000..a81434c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleFill.java @@ -0,0 +1,668 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.HoleManager; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class HoleFill extends Module { + + public enum BlockType { + OBSIDIAN(Items.OBSIDIAN); + + private final Item item; + + BlockType(Item item) { + this.item = item; + } + + public Item getItem() { + return item; + } + } + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private static final String ROT_ID = "holefill"; + private static final int ROT_PRIORITY = 8; + + public final Setting multitask = bool("MultiTask", false); + public final Setting type = mode("Type", BlockType.OBSIDIAN); + public final Setting webs = bool("Webs", false); + public final Setting range = num("Range", 5.0f, 1.0f, 6.0f); + public final Setting blocksPerTick = num("ShiftTicks", 6, 1, 10); + public final Setting delay = num("Delay", 2, 0, 20); + public final Setting smart = bool("Smart", true); + public final Setting smartRange = num("EnemyRange", 8.0f, 1.0f, 12.0f); + public final Setting safetyRange = num("SafetyRange", 3.0f, 1.0f, 6.0f); + public final Setting doubleHoles = bool("DoubleHoles", true); + public final Setting partial = bool("Partial", false); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final List placements = new ArrayList<>(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private int ticks = 0; + private int blocksPlaced = 0; + private int invSwapSlot = -1; + + public HoleFill() { + super("HoleFill", "Fills nearby holes with blocks", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = delay.getValue(); + blocksPlaced = 0; + invSwapSlot = -1; + renderFadeState.reset(); + } + + @Override + public void onDisable() { + placements.clear(); + renderPositions.clear(); + renderFadeState.reset(); + ticks = 0; + blocksPlaced = 0; + invSwapSlot = -1; + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + blocksPlaced = 0; + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + int slot = findFillItemSlot(); + + if (slot == -1) { + renderPositions.clear(); + ticks = 0; + return; + } + + Player smartTarget = smart.getValue() ? getTarget(player, level) : null; + + if (smart.getValue() && smartTarget == null) { + renderPositions.clear(); + ticks = 0; + return; + } + + placements.clear(); + placements.addAll(getPositions(player, level, smartTarget)); + + double rangeSq = range.getValue() * range.getValue(); + List toPlace = new ArrayList<>(); + + for (BlockPos pos : placements) { + if (player.distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + continue; + } + + if (!isPlaceable(pos)) { + continue; + } + + toPlace.add(pos); + } + + toPlace.sort(Comparator.comparingDouble(pos -> player.distanceToSqr(Vec3.atCenterOf(pos)))); + + renderPositions.clear(); + renderPositions.addAll(toPlace); + + if (toPlace.isEmpty()) { + ticks = 0; + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + + for (BlockPos pos : toPlace) { + if (blocksPlaced >= blocksPerTick.getValue()) { + break; + } + + if (!switched) { + if (!doSwitch(slot, oldSlot)) { + break; + } + + switched = true; + } + + if (!applyRotations(Vec3.atCenterOf(pos))) { + break; + } + + if (placeBlock(pos)) { + blocksPlaced++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + ticks = 0; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private boolean placeBlock(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || mc.level == null || gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isPlaceable(BlockPos pos) { + ClientLevel level = mc.level; + + if (level == null) { + return false; + } + + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return airPlace.getValue() || buildHitResult(pos) != null; + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + boolean shouldRestoreSlot = switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1; + + if (shouldRestoreSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot == -1) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + + private int findFillItemSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + Item wanted = webs.getValue() ? Items.COBWEB : type.getValue().getItem(); + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).getItem() == wanted) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).getItem() == wanted) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).getItem() == wanted) { + return i; + } + } + + return -1; + } + + private List getPositions(Player self, Level level, Player smartTarget) { + HoleManager holeManager = nolongerhuman.holeManager; + + if (holeManager == null) { + return List.of(); + } + + Set positions = new LinkedHashSet<>(); + + double rangeSq = range.getValue() * range.getValue(); + double smartSq = smartRange.getValue() * smartRange.getValue(); + double safetySq = safetyRange.getValue() * safetyRange.getValue(); + + boolean selfInHole = playerInManagedHole(level, self); + + List managedHoles = partial.getValue() + ? holeManager.getHoles() + : holeManager.getNormalHoles(); + + for (HoleManager.Hole hole : managedHoles) { + BlockPos pos = hole.pos(); + Vec3 center = Vec3.atCenterOf(pos); + + if (self.distanceToSqr(center) > rangeSq) { + continue; + } + + if (smart.getValue() && smartTarget != null && smartTarget.distanceToSqr(center) > smartSq) { + continue; + } + + if (!selfInHole && self.distanceToSqr(center) <= safetySq) { + continue; + } + + positions.add(pos.immutable()); + } + + if (doubleHoles.getValue()) { + addDoubleHolePositionsFromManager(holeManager, self, level, smartTarget, positions); + } + + return new ArrayList<>(positions); + } + + private void addDoubleHolePositionsFromManager( + HoleManager holeManager, + Player self, + Level level, + Player smartTarget, + Set positions + ) { + double rangeSq = range.getValue() * range.getValue(); + double smartSq = smartRange.getValue() * smartRange.getValue(); + double safetySq = safetyRange.getValue() * safetyRange.getValue(); + + boolean selfInHole = playerInManagedHole(level, self); + + int r = (int) Math.ceil(range.getValue()); + BlockPos base = self.blockPosition(); + + for (int x = -r; x <= r; x++) { + for (int y = -r; y <= r; y++) { + for (int z = -r; z <= r; z++) { + BlockPos first = base.offset(x, y, z); + + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos second = first.relative(dir); + + if (holeManager.getDoubleHoleType(level, first, second) == null) { + continue; + } + + addManagedDoubleCell(self, smartTarget, positions, first, rangeSq, smartSq, safetySq, selfInHole); + addManagedDoubleCell(self, smartTarget, positions, second, rangeSq, smartSq, safetySq, selfInHole); + } + } + } + } + } + + private void addManagedDoubleCell( + Player self, + Player smartTarget, + Set positions, + BlockPos pos, + double rangeSq, + double smartSq, + double safetySq, + boolean selfInHole + ) { + Vec3 center = Vec3.atCenterOf(pos); + + if (self.distanceToSqr(center) > rangeSq) { + return; + } + + if (smart.getValue() && smartTarget != null && smartTarget.distanceToSqr(center) > smartSq) { + return; + } + + if (!selfInHole && self.distanceToSqr(center) <= safetySq) { + return; + } + + positions.add(pos.immutable()); + } + + private Player getTarget(Player self, Level level) { + Player best = null; + double bestDist = Double.MAX_VALUE; + double smartSq = smartRange.getValue() * smartRange.getValue(); + + for (Player player : level.players()) { + if (player == self) { + continue; + } + + if (!player.isAlive()) { + continue; + } + + try { + if (nolongerhuman.friendManager.isFriend(player)) { + continue; + } + } catch (Exception ignored) { + } + + double dist = self.distanceToSqr(player); + + if (dist > smartSq) { + continue; + } + + if (!hasOpenSurround(level, player)) { + continue; + } + + if (dist < bestDist) { + bestDist = dist; + best = player; + } + } + + return best; + } + + private boolean hasOpenSurround(Level level, Player player) { + BlockPos feet = player.blockPosition(); + + if (level.getBlockState(feet.below()).canBeReplaced()) { + return true; + } + + for (Direction dir : Direction.Plane.HORIZONTAL) { + if (level.getBlockState(feet.relative(dir)).canBeReplaced()) { + return true; + } + } + + return false; + } + + private boolean playerInManagedHole(Level level, Player player) { + HoleManager holeManager = nolongerhuman.holeManager; + + if (holeManager == null) { + return false; + } + + BlockPos feet = player.blockPosition(); + + if (holeManager.getHole(feet) != null) { + return true; + } + + if (doubleHoles.getValue() && holeManager.isPartOfDoubleHole(level, feet)) { + return true; + } + + return partial.getValue() && holeManager.getPartialHole(feet) != null; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleRefill.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleRefill.java new file mode 100644 index 0000000..69d9c20 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/HoleRefill.java @@ -0,0 +1,561 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.HoleManager; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +public class HoleRefill extends Module { + + public enum BlockType { + OBSIDIAN(Items.OBSIDIAN); + + private final Item item; + + BlockType(Item item) { + this.item = item; + } + + public Item getItem() { + return item; + } + } + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private static final String ROT_ID = "holerefill"; + private static final int ROT_PRIORITY = 20; + + public final Setting multitask = bool("MultiTask", false); + public final Setting onlyOnGround = bool("OnlyGround", false); + public final Setting type = mode("Type", BlockType.OBSIDIAN); + public final Setting webs = bool("Webs", false); + public final Setting range = num("Range", 5.0f, 1.0f, 6.0f); + public final Setting blocksPerTick = num("ShiftTicks", 1, 1, 4); + public final Setting delay = num("Delay", 2, 0, 20); + public final Setting doubleHoles = bool("DoubleHoles", true); + public final Setting partial = bool("Partial", false); + public final Setting waitUntilExited = bool("WaitUntilExited", true); + public final Setting autoDisable = bool("AutoDisable", false); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private BlockPos lastHolePos = null; + private BlockPos refillPos = null; + private boolean wasInHole = false; + private int ticks = 0; + private int blocksPlaced = 0; + private int invSwapSlot = -1; + + public HoleRefill() { + super("HoleRefill", "Fills the hole you just exited", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = delay.getValue(); + blocksPlaced = 0; + invSwapSlot = -1; + lastHolePos = null; + refillPos = null; + wasInHole = false; + renderPositions.clear(); + renderFadeState.reset(); + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player != null && level != null && playerInManagedHole(level, player)) { + lastHolePos = player.blockPosition().immutable(); + wasInHole = true; + } + } + + @Override + public void onDisable() { + renderPositions.clear(); + renderFadeState.reset(); + ticks = 0; + blocksPlaced = 0; + invSwapSlot = -1; + lastHolePos = null; + refillPos = null; + wasInHole = false; + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (onlyOnGround.getValue() && !player.onGround()) { + return; + } + + updateExitedHole(player, level); + blocksPlaced = 0; + + if (ticks < delay.getValue()) { + ticks++; + updateRenderPositions(); + return; + } + + if (refillPos == null) { + updateRenderPositions(); + ticks = 0; + return; + } + + if (!isManagedHole(level, refillPos)) { + refillPos = null; + updateRenderPositions(); + ticks = 0; + + if (autoDisable.getValue()) { + disable(); + } + + return; + } + + if (waitUntilExited.getValue() && playerIntersects(refillPos, player)) { + updateRenderPositions(); + ticks = 0; + return; + } + + if (player.distanceToSqr(Vec3.atCenterOf(refillPos)) > range.getValue() * range.getValue()) { + updateRenderPositions(); + ticks = 0; + return; + } + + if (!isPlaceable(refillPos)) { + refillPos = null; + updateRenderPositions(); + ticks = 0; + + if (autoDisable.getValue()) { + disable(); + } + + return; + } + + int slot = findFillItemSlot(); + + if (slot == -1) { + updateRenderPositions(); + ticks = 0; + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + + if (doSwitch(slot, oldSlot)) { + if (applyRotations(Vec3.atCenterOf(refillPos)) && placeBlock(refillPos)) { + blocksPlaced++; + refillPos = null; + } + + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + updateRenderPositions(); + ticks = 0; + + if (autoDisable.getValue() && refillPos == null && blocksPlaced > 0) { + disable(); + } + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + private void updateExitedHole(LocalPlayer player, ClientLevel level) { + boolean inHole = playerInManagedHole(level, player); + BlockPos currentPos = player.blockPosition(); + + if (inHole) { + lastHolePos = currentPos.immutable(); + wasInHole = true; + return; + } + + if (!wasInHole || lastHolePos == null) { + wasInHole = false; + return; + } + + if (!currentPos.equals(lastHolePos)) { + refillPos = lastHolePos.immutable(); + } + + wasInHole = false; + } + + private boolean playerInManagedHole(Level level, LocalPlayer player) { + return isManagedHole(level, player.blockPosition()); + } + + private boolean isManagedHole(Level level, BlockPos pos) { + HoleManager holeManager = nolongerhuman.holeManager; + + if (holeManager == null) { + return false; + } + + if (holeManager.getHole(pos) != null) { + return true; + } + + if (doubleHoles.getValue() && holeManager.isPartOfDoubleHole(level, pos)) { + return true; + } + + return partial.getValue() && holeManager.getPartialHole(pos) != null; + } + + private void updateRenderPositions() { + renderPositions.clear(); + + if (refillPos != null) { + renderPositions.add(refillPos); + } + } + + private boolean playerIntersects(BlockPos pos, LocalPlayer player) { + return player.getBoundingBox().intersects(new AABB(pos)); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private boolean placeBlock(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || mc.level == null || gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isPlaceable(BlockPos pos) { + ClientLevel level = mc.level; + + if (level == null) { + return false; + } + + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return airPlace.getValue() || buildHitResult(pos) != null; + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + boolean shouldRestoreSlot = switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1; + + if (shouldRestoreSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot == -1) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + + private int findFillItemSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + Item wanted = webs.getValue() ? Items.COBWEB : type.getValue().getItem(); + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).getItem() == wanted) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).getItem() == wanted) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).getItem() == wanted) { + return i; + } + } + + return -1; + } + + @Override + public String getDisplayInfo() { + if (refillPos != null) { + return "Ready"; + } + + return wasInHole ? "Tracking" : "Idle"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/MaceBlocker.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/MaceBlocker.java new file mode 100644 index 0000000..bf66a4c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/MaceBlocker.java @@ -0,0 +1,763 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class MaceBlocker extends Module { + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + public enum BlockMode { + Between, + SelfTrap, + Both + } + + private enum ThreatType { + Normal, + Elytra, + WindCharge + } + + private static final String ROT_ID = "mace-blocker"; + private static final int ROT_PRIORITY = 20; + + public final Setting multitask = bool("MultiTask", true); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting blockMode = mode("BlockMode", BlockMode.Both); + public final Setting range = num("Range", 5.0f, 1.0f, 6.0f); + public final Setting blocksPerTick = num("Blocks/Tick", 4, 1, 12); + public final Setting delay = num("Delay", 0, 0, 20); + public final Setting support = bool("Support", true); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting detectRange = num("DetectRange", 8.0, 3.0, 16.0); + public final Setting attackRange = num("AttackRange", 3.25, 2.5, 6.0); + public final Setting preTicks = num("PreTicks", 8, 1, 20); + public final Setting minFallDistance = num("MinFallDistance", 1.5, 0.0, 8.0); + public final Setting roof = bool("Roof", true); + public final Setting feet = bool("Feet", false); + public final Setting antiFacePlace = bool("AntiFacePlace", true); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 70)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.0f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final Timer timer = new Timer(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private int ticks; + private int invSwapSlot; + + public MaceBlocker() { + super("MaceBlocker", "stop reading this", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = delay.getValue(); + invSwapSlot = -1; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + clearRotations(); + ticks = 0; + invSwapSlot = -1; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + if (!timer.passedMs(1L)) { + return; + } + + MaceThreat threat = findThreat(player, level); + + if (threat == null) { + renderPositions.clear(); + resetTickTimer(); + return; + } + + List positions = getBlockPositions(player, threat.attacker()); + + positions.removeIf(this::isInvalidPlacementSpot); + positions.sort(Comparator.comparingDouble(pos -> player.distanceToSqr(Vec3.atCenterOf(pos)))); + + renderPositions.clear(); + renderPositions.addAll(positions); + + if (positions.isEmpty()) { + resetTickTimer(); + return; + } + + int blockSlot = findBlockSlot(); + + if (blockSlot == -1) { + resetTickTimer(); + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + int placed = 0; + + for (BlockPos pos : positions) { + if (placed >= blocksPerTick.getValue()) { + break; + } + + if (!switched) { + if (!doSwitch(blockSlot, oldSlot)) { + break; + } + + switched = true; + } + + if (placeWithSupport(pos)) { + placed++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + resetTickTimer(); + } + + private void resetTickTimer() { + ticks = 0; + timer.reset(); + } + + private MaceThreat findThreat(LocalPlayer player, ClientLevel level) { + MaceThreat bestThreat = null; + double bestDistance = Double.MAX_VALUE; + + for (Player attacker : level.players()) { + if (!isValidAttacker(player, attacker)) { + continue; + } + + MaceThreat threat = getThreat(player, attacker); + + if (threat == null) { + continue; + } + + double distance = player.distanceToSqr(attacker); + + if (distance < bestDistance) { + bestDistance = distance; + bestThreat = threat; + } + } + + return bestThreat; + } + + private boolean isValidAttacker(LocalPlayer player, Player attacker) { + if (attacker == player) { + return false; + } + + if (attacker.isDeadOrDying() || attacker.isSpectator() || attacker.isCreative()) { + return false; + } + + if (!isHoldingMace(attacker)) { + return false; + } + + return player.distanceTo(attacker) <= detectRange.getValue(); + } + + private boolean isHoldingMace(Player player) { + return isMace(player.getMainHandItem()) || isMace(player.getOffhandItem()); + } + + private boolean isMace(ItemStack stack) { + return stack.is(Items.MACE); + } + + private MaceThreat getThreat(LocalPlayer player, Player attacker) { + ThreatType type = detectThreatType(player, attacker); + + if (type == null) { + return null; + } + + int ticksUntilHit = getTicksUntilHit(player, attacker, type); + + if (ticksUntilHit < 0 || ticksUntilHit > preTicks.getValue()) { + return null; + } + + return new MaceThreat(attacker); + } + + private ThreatType detectThreatType(LocalPlayer player, Player attacker) { + Vec3 attackerVelocity = attacker.getDeltaMovement(); + + boolean descending = attackerVelocity.y < -0.08D + || attacker.fallDistance >= minFallDistance.getValue().floatValue(); + + boolean abovePlayer = attacker.getY() > player.getY() + 0.75D; + boolean closeHorizontally = horizontalDistance(player.position(), attacker.position()) <= attackRange.getValue() + 1.0D; + boolean closing = isClosingDistance(player, attacker); + + if (attacker.isFallFlying() && closing && closeHorizontally) { + return ThreatType.Elytra; + } + + if (isLikelyWindChargeMace(player, attacker, descending, abovePlayer, closing)) { + return ThreatType.WindCharge; + } + + if (descending && abovePlayer && closing && closeHorizontally) { + return ThreatType.Normal; + } + + return null; + } + + private boolean isLikelyWindChargeMace( + LocalPlayer player, + Player attacker, + boolean descending, + boolean abovePlayer, + boolean closing + ) { + Vec3 velocity = attacker.getDeltaMovement(); + double horizontalSpeed = horizontalSpeed(velocity); + double verticalDifference = attacker.getY() - player.getY(); + + boolean launchedOrFallingFast = attacker.fallDistance >= minFallDistance.getValue().floatValue() + || velocity.y < -0.25D + || verticalDifference > 2.0D; + + boolean windChargeMovement = horizontalSpeed > 0.35D + || Math.abs(velocity.y) > 0.35D + || attacker.hurtMarked; + + return launchedOrFallingFast + && windChargeMovement + && descending + && abovePlayer + && closing; + } + + private int getTicksUntilHit(LocalPlayer player, Player attacker, ThreatType type) { + Vec3 playerPos = player.position(); + Vec3 attackerPos = attacker.position(); + Vec3 playerVelocity = player.getDeltaMovement(); + Vec3 attackerVelocity = attacker.getDeltaMovement(); + + int maxPredictionTicks = Math.max(preTicks.getValue(), 1); + + for (int tick = 0; tick <= maxPredictionTicks; tick++) { + double predictedRange = getPredictedAttackRange(type, tick); + double distance = playerPos.distanceTo(attackerPos); + double horizontal = horizontalDistance(playerPos, attackerPos); + boolean heightValid = attackerPos.y >= playerPos.y - 0.5D; + + if (distance <= predictedRange && horizontal <= predictedRange && heightValid) { + return tick; + } + + playerPos = playerPos.add(playerVelocity); + attackerPos = attackerPos.add(attackerVelocity); + playerVelocity = dampPlayerVelocity(playerVelocity); + attackerVelocity = dampAttackerVelocity(attackerVelocity, type); + } + + return -1; + } + + private double getPredictedAttackRange(ThreatType type, int tick) { + double baseRange = attackRange.getValue(); + + return switch (type) { + case Elytra -> baseRange + 0.55D + (tick * 0.08D); + case WindCharge -> baseRange + 0.35D + (tick * 0.06D); + case Normal -> baseRange + 0.15D; + }; + } + + private Vec3 dampPlayerVelocity(Vec3 velocity) { + return new Vec3(velocity.x * 0.91D, velocity.y * 0.98D, velocity.z * 0.91D); + } + + private Vec3 dampAttackerVelocity(Vec3 velocity, ThreatType type) { + double horizontalDrag = type == ThreatType.Elytra ? 0.99D : 0.91D; + double y = velocity.y - 0.08D; + + return new Vec3(velocity.x * horizontalDrag, y * 0.98D, velocity.z * horizontalDrag); + } + + private boolean isClosingDistance(LocalPlayer player, Player attacker) { + Vec3 playerToAttacker = attacker.position().subtract(player.position()); + Vec3 relativeVelocity = attacker.getDeltaMovement().subtract(player.getDeltaMovement()); + + return playerToAttacker.dot(relativeVelocity) < 0.0D; + } + + private List getBlockPositions(LocalPlayer player, Player attacker) { + Set positions = new LinkedHashSet<>(); + + if (blockMode.getValue() == BlockMode.SelfTrap || blockMode.getValue() == BlockMode.Both) { + addSelfTrapPositions(player, positions); + } + + if (blockMode.getValue() == BlockMode.Between || blockMode.getValue() == BlockMode.Both) { + addBetweenPositions(player, attacker, positions); + } + + return new ArrayList<>(positions); + } + + private void addSelfTrapPositions(LocalPlayer player, Set positions) { + BlockPos base = player.blockPosition(); + + if (feet.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.relative(dir)); + } + } + + if (antiFacePlace.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.above().relative(dir)); + } + } + + if (roof.getValue()) { + positions.add(base.above(2)); + } + } + + private void addBetweenPositions(LocalPlayer player, Player attacker, Set positions) { + Vec3 playerCenter = player.position().add(0.0D, 1.0D, 0.0D); + Vec3 attackerCenter = attacker.position().add(0.0D, 1.0D, 0.0D); + + addLinePosition(playerCenter, attackerCenter, 0.35D, positions); + addLinePosition(playerCenter, attackerCenter, 0.50D, positions); + addLinePosition(playerCenter, attackerCenter, 0.65D, positions); + + Vec3 attackerVelocity = attacker.getDeltaMovement(); + + if (attackerVelocity.lengthSqr() > 0.01D) { + Vec3 predicted = attacker.position().add(attackerVelocity); + + positions.add(toBlockPos(predicted)); + positions.add(toBlockPos(predicted.add(0.0D, 1.0D, 0.0D))); + } + } + + private void addLinePosition(Vec3 from, Vec3 to, double factor, Set positions) { + Vec3 pos = from.lerp(to, factor); + + positions.add(toBlockPos(pos)); + positions.add(toBlockPos(pos.add(0.0D, 1.0D, 0.0D))); + } + + private BlockPos toBlockPos(Vec3 vec) { + return new BlockPos(Mth.floor(vec.x), Mth.floor(vec.y), Mth.floor(vec.z)); + } + + private boolean placeWithSupport(BlockPos pos) { + if (rotateTo(pos)) { + if (place(pos)) { + return true; + } + } else { + return false; + } + + if (!support.getValue()) { + return false; + } + + BlockPos supportPos = pos.below(); + + if (isInvalidPlacementSpot(supportPos)) { + return false; + } + + if (rotateTo(supportPos)) { + if (!place(supportPos)) { + return false; + } + } else { + return false; + } + + if (rotateTo(pos)) { + return place(pos); + } + + return false; + } + + private boolean place(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5D, + side.getStepY() * 0.5D, + side.getStepZ() * 0.5D + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isInvalidPlacementSpot(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return true; + } + + if (level.isOutsideBuildHeight(pos)) { + return true; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return true; + } + + double rangeSq = range.getValue() * range.getValue(); + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) > rangeSq) { + return true; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return true; + } + + return !airPlace.getValue() && buildHitResult(pos) == null && !support.getValue(); + } + + private boolean rotateTo(BlockPos pos) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return true; + } + + return rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, Vec3.atCenterOf(pos)); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + int targetSlot = slot; + + if (targetSlot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + targetSlot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = targetSlot; + targetSlot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(targetSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(targetSlot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == targetSlot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + } + + private int findBlockSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (isBlockItem(player.getInventory().getItem(selected).getItem())) { + return selected; + } + + for (int slot = 0; slot < 9; slot++) { + if (isBlockItem(player.getInventory().getItem(slot).getItem())) { + return slot; + } + } + + for (int slot = 9; slot < 36; slot++) { + if (isBlockItem(player.getInventory().getItem(slot).getItem())) { + return slot; + } + } + + return -1; + } + + private boolean isBlockItem(Item item) { + return item == Items.OBSIDIAN + || item == Items.CRYING_OBSIDIAN + || item == Items.ENDER_CHEST; + } + + private double horizontalDistance(Vec3 first, Vec3 second) { + double x = first.x - second.x; + double z = first.z - second.z; + + return Math.sqrt((x * x) + (z * z)); + } + + private double horizontalSpeed(Vec3 velocity) { + return Math.sqrt((velocity.x * velocity.x) + (velocity.z * velocity.z)); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + private record MaceThreat(Player attacker) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/ObsidianFarmer.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/ObsidianFarmer.java new file mode 100644 index 0000000..038d4b3 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/ObsidianFarmer.java @@ -0,0 +1,737 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class ObsidianFarmer extends Module { + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private enum Phase { + Place, + Mine + } + + private static final String ROT_ID = "obsidianfarmer"; + private static final int ROT_PRIORITY = 4; + + public final Setting multitask = bool("MultiTask", true); + public final Setting onlyOnGround = bool("OnlyGround", false); + public final Setting ecSwitch = mode("ECSwap", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting placeRange = num("PlaceRange", 5.0, 1.0, 6.0); + public final Setting mineRange = num("MineRange", 5.0, 1.0, 8.0); + public final Setting wallsRange = num("WallsRange", 3.5, 1.0, 8.0); + public final Setting placeDelay = num("PlaceDelay", 2, 0, 20); + public final Setting mineDelay = num("MineDelay", 1, 0, 20); + public final Setting retryDelay = num("RetryDelay", 1, 1, 20); + public final Setting requirePacketMine = bool("RequirePacketMine", true); + public final Setting rotate = bool("Rotate", true); + public final Setting swing = bool("Swing", true); + public final Setting strict = bool("Strict", true); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting airPlace = bool("AirPlace", false); + public final Setting support = bool("Support", true); + + public final Setting render = bool("Render", true); + public final Setting placeFill = color("PlaceFill", new Color(90, 160, 255, 65)); + public final Setting placeOutline = color("PlaceOutline", new Color(90, 160, 255, 230)); + public final Setting mineFill = color("MineFill", new Color(255, 90, 90, 65)); + public final Setting mineOutline = color("MineOutline", new Color(255, 90, 90, 230)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final Timer placeTimer = new Timer(); + private final Timer mineTimer = new Timer(); + private final Timer retryTimer = new Timer(); + + private final FadeRenderUtil.FadeState placeFadeState = new FadeRenderUtil.FadeState(); + private final FadeRenderUtil.FadeState mineFadeState = new FadeRenderUtil.FadeState(); + + private BlockPos enderChestPos; + private BlockPos renderPlacePos; + private BlockPos renderMinePos; + private Phase phase = Phase.Place; + private int invSwapSlot = -1; + + public ObsidianFarmer() { + super("ObsidianFarmer", "Places and mines ender chests using PacketMine", Category.COMBAT); + } + + @Override + public void onEnable() { + enderChestPos = null; + renderPlacePos = null; + renderMinePos = null; + phase = Phase.Place; + invSwapSlot = -1; + placeFadeState.reset(); + mineFadeState.reset(); + placeTimer.reset(); + mineTimer.reset(); + retryTimer.reset(); + } + + @Override + public void onDisable() { + enderChestPos = null; + renderPlacePos = null; + renderMinePos = null; + phase = Phase.Place; + invSwapSlot = -1; + placeFadeState.reset(); + mineFadeState.reset(); + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (onlyOnGround.getValue() && !player.onGround()) { + return; + } + + updateCurrentEnderChest(player, level); + + if (enderChestPos != null && level.getBlockState(enderChestPos).is(Blocks.ENDER_CHEST)) { + phase = Phase.Mine; + renderPlacePos = null; + renderMinePos = enderChestPos; + + if (requirePacketMine.getValue() && !isPacketMineActive()) { + return; + } + + targetEnderChest(player, level, gameMode, enderChestPos); + return; + } + + phase = Phase.Place; + enderChestPos = null; + renderMinePos = null; + placeEnderChest(player, level, gameMode); + } + + private boolean isPacketMineActive() { + if (nolongerhuman.moduleManager == null) { + return false; + } + + PacketMine packetMine = nolongerhuman.moduleManager.getModuleByClass(PacketMine.class); + return packetMine != null && packetMine.isEnabled(); + } + + private void updateCurrentEnderChest(LocalPlayer player, ClientLevel level) { + if (enderChestPos != null) { + if (!level.getBlockState(enderChestPos).is(Blocks.ENDER_CHEST)) { + enderChestPos = null; + } + + return; + } + + enderChestPos = findExistingEnderChest(player, level); + } + + private BlockPos findExistingEnderChest(LocalPlayer player, ClientLevel level) { + double range = Math.max(placeRange.getValue(), mineRange.getValue()); + double rangeSq = range * range; + int radius = (int) Math.ceil(range); + + BlockPos base = player.blockPosition(); + BlockPos best = null; + double bestDistance = Double.MAX_VALUE; + + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= radius; y++) { + for (int z = -radius; z <= radius; z++) { + BlockPos pos = base.offset(x, y, z); + + if (!level.getBlockState(pos).is(Blocks.ENDER_CHEST)) { + continue; + } + + double distance = player.distanceToSqr(Vec3.atCenterOf(pos)); + + if (distance > rangeSq) { + continue; + } + + if (distance < bestDistance) { + bestDistance = distance; + best = pos.immutable(); + } + } + } + } + + return best; + } + + private void placeEnderChest(LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { + if (!placeTimer.passedMs(placeDelay.getValue().longValue() * 50L)) { + return; + } + + BlockPos placePos = findBestPlacePosition(player, level); + renderPlacePos = placePos; + + if (placePos == null) { + return; + } + + int enderChestSlot = findEnderChestSlot(player); + + if (enderChestSlot == -1) { + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + + if (!doSwitch(enderChestSlot, oldSlot)) { + return; + } + + boolean success = tryPlaceAt(player, level, gameMode, placePos); + + if (!success && support.getValue()) { + BlockPos supportPos = placePos.below(); + + if (isValidPlaceSpot(player, level, supportPos)) { + boolean supportPlaced = tryPlaceAt(player, level, gameMode, supportPos); + + if (supportPlaced && isValidPlaceSpot(player, level, placePos)) { + success = tryPlaceAt(player, level, gameMode, placePos); + } + } + } + + switchBack(oldSlot); + resetSpoofIfNeeded(); + placeTimer.reset(); + + if (!success) { + return; + } + + BlockPos placed = level.getBlockState(placePos).is(Blocks.ENDER_CHEST) + ? placePos.immutable() + : findExistingEnderChest(player, level); + + if (placed == null) { + return; + } + + enderChestPos = placed; + renderPlacePos = null; + renderMinePos = enderChestPos; + phase = Phase.Mine; + mineTimer.reset(); + retryTimer.reset(); + } + + private boolean tryPlaceAt(LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode, BlockPos pos) { + if (rotationFailed(Vec3.atCenterOf(pos))) { + return false; + } + + if (!placeBlock(player, gameMode, pos)) { + return false; + } + + return level.getBlockState(pos).is(Blocks.ENDER_CHEST); + } + + private void targetEnderChest(LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode, BlockPos pos) { + if (!mineTimer.passedMs(mineDelay.getValue().longValue() * 50L)) { + return; + } + + if (!retryTimer.passedMs(retryDelay.getValue().longValue() * 50L)) { + return; + } + + if (!canTargetEnderChest(player, level, pos)) { + enderChestPos = null; + renderMinePos = null; + phase = Phase.Place; + return; + } + + Direction side = getMineSide(player, level, pos); + + if (strictDirection.getValue() && side == null) { + return; + } + + Direction mineSide = side == null ? Direction.UP : side; + + if (rotationFailed(getHitVec(pos, mineSide))) { + return; + } + + gameMode.startDestroyBlock(pos, mineSide); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + resetSpoofIfNeeded(); + retryTimer.reset(); + mineTimer.reset(); + } + + private BlockPos findBestPlacePosition(LocalPlayer player, ClientLevel level) { + List positions = getPlaceCandidates(player); + + positions.removeIf(pos -> !isValidPlaceSpot(player, level, pos)); + positions.sort(Comparator.comparingDouble(pos -> player.distanceToSqr(Vec3.atCenterOf(pos)))); + + return positions.isEmpty() ? null : positions.getFirst().immutable(); + } + + private List getPlaceCandidates(LocalPlayer player) { + Set positions = new LinkedHashSet<>(); + BlockPos base = player.blockPosition(); + Direction facing = getHorizontalFacing(player); + + positions.add(base.relative(facing)); + positions.add(base.relative(facing).below()); + + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.relative(dir)); + } + + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.relative(dir).below()); + } + + positions.add(base.below()); + + return new ArrayList<>(positions); + } + + private Direction getHorizontalFacing(LocalPlayer player) { + double yaw = Math.toRadians(player.getYRot()); + double x = -Math.sin(yaw); + double z = Math.cos(yaw); + + if (Math.abs(x) > Math.abs(z)) { + return x > 0.0D ? Direction.EAST : Direction.WEST; + } + + return z > 0.0D ? Direction.SOUTH : Direction.NORTH; + } + + private boolean isValidPlaceSpot(LocalPlayer player, ClientLevel level, BlockPos pos) { + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) > placeRange.getValue() * placeRange.getValue()) { + return false; + } + + AABB box = new AABB(pos); + + if (player.getBoundingBox().intersects(box)) { + return false; + } + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return airPlace.getValue() || buildPlaceHitResult(pos) != null; + } + + private boolean placeBlock(LocalPlayer player, MultiPlayerGameMode gameMode, BlockPos pos) { + BlockHitResult hitResult = buildPlaceHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + return true; + } + + private BlockHitResult buildPlaceHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5D, + side.getStepY() * 0.5D, + side.getStepZ() * 0.5D + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean canTargetEnderChest(LocalPlayer player, ClientLevel level, BlockPos pos) { + if (!level.getBlockState(pos).is(Blocks.ENDER_CHEST)) { + return false; + } + + if (!canReach(player, level, pos, mineRange.getValue(), wallsRange.getValue())) { + return false; + } + + return !strictDirection.getValue() || getMineSide(player, level, pos) != null; + } + + private boolean canReach(LocalPlayer player, ClientLevel level, BlockPos pos, double visibleRange, double wallRange) { + Vec3 eye = player.getEyePosition(); + Vec3 hit = Vec3.atCenterOf(pos); + double distance = eye.distanceTo(hit); + + if (distance <= visibleRange && hasLineOfSight(player, level, eye, hit)) { + return true; + } + + return distance <= wallRange; + } + + private boolean hasLineOfSight(LocalPlayer player, ClientLevel level, Vec3 from, Vec3 to) { + HitResult result = level.clip(new ClipContext( + from, + to, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + return result.getType() == HitResult.Type.MISS; + } + + private Direction getMineSide(LocalPlayer player, ClientLevel level, BlockPos pos) { + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + double bestDistance = Double.MAX_VALUE; + + for (Direction direction : Direction.values()) { + Vec3 hit = getHitVec(pos, direction); + double distance = eye.distanceTo(hit); + + if (distance >= bestDistance) { + continue; + } + + if (!strictDirection.getValue() || hasLineOfSight(player, level, eye, hit)) { + bestDistance = distance; + bestSide = direction; + } + } + + return bestSide; + } + + private Vec3 getHitVec(BlockPos pos, Direction direction) { + return Vec3.atCenterOf(pos).add( + direction.getStepX() * 0.5D, + direction.getStepY() * 0.5D, + direction.getStepZ() * 0.5D + ); + } + + private int findEnderChestSlot(LocalPlayer player) { + int selected = player.getInventory().getSelectedSlot(); + + if (player.getInventory().getItem(selected).is(Items.ENDER_CHEST)) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(Items.ENDER_CHEST)) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (player.getInventory().getItem(i).is(Items.ENDER_CHEST)) { + return i; + } + } + + return -1; + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (ecSwitch.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + boolean shouldRestoreSlot = ecSwitch.getValue() == SwitchMode.Silent || invSwapSlot != -1; + + if (shouldRestoreSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot == -1) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + + private boolean rotationFailed(Vec3 pos) { + return rotate.getValue() && !applyRotations(pos); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + placeFadeState.reset(); + mineFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + placeFadeState, + single(renderPlacePos), + placeFill.getValue(), + placeOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + + FadeRenderUtil.renderBlockPositions( + stack, + mineFadeState, + single(renderMinePos), + mineFill.getValue(), + mineOutline.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + private List single(BlockPos pos) { + if (pos == null) { + return List.of(); + } + + return List.of(pos); + } + + @Override + public String getDisplayInfo() { + if (enderChestPos != null) { + return phase.name(); + } + + return "Place"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Offhand.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Offhand.java new file mode 100644 index 0000000..8e94328 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Offhand.java @@ -0,0 +1,311 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.models.Timer; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.AxeItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import java.lang.reflect.Field; + +public class Offhand extends Module { + public enum ItemMode { + Totem, + Crystal, + Gapple + } + + public final Setting item = mode("Item", ItemMode.Totem); + public final Setting health = num("Health", 16.5f, 0.0f, 36.0f); + public final Setting elytraCheck = bool("ElytraCheck", true); + public final Setting fallDistance = num("FallDistance", 20.0f, 0.0f, 80.0f); + public final Setting useGapple = bool("UseGapple", true); + public final Setting lethalOverride = bool("LethalOverride", false); + public final Setting tickAbort = bool("TickAbort", true); + public final Setting smartMine = bool("SmartMine", false); + public final Setting antiMace = bool("AntiMace", false); + public final Setting maceRange = num("MaceRange", 12.0f, 0.0f, 24.0f); + + private final Timer timer = new Timer(); + + private int totemCount = 0; + private int ticks = 0; + + public Offhand() { + super("Offhand", "Automatically puts a specified item in your offhand slot", Category.COMBAT); + } + + @Override + public void onEnable() { + ticks = 0; + totemCount = 0; + timer.reset(); + } + + @Override + public void onTick() { + if (nullCheck()) return; + if (mc.player == null || mc.level == null || mc.gameMode == null) return; + + totemCount = countTotems(); + + if (ticks > 0 && tickAbort.getValue()) { + ticks--; + return; + } + + + if (!(mc.screen instanceof InventoryScreen) && mc.screen instanceof AbstractContainerScreen) { + return; + } + + Item wantedItem = getItem(); + + if (wantedItem == null) { + return; + } + + if (mc.player.getOffhandItem().getItem() == wantedItem) { + return; + } + + int slot = findInventory(wantedItem); + + if (slot == -1) { + slot = findHotbar(wantedItem); + } + + + if (slot == -1) { + if (wantedItem == Items.TOTEM_OF_UNDYING) { + slot = findEmptySlot(); + + if (slot == -1 || mc.player.getOffhandItem().isEmpty()) { + return; + } + } else { + return; + } + } + + moveToOffhand(slot); + + ticks = 2; + timer.reset(); + } + + private Item getItem() { + if (mc.player == null || mc.level == null) return null; + + if (useGapple.getValue() + && mc.options.keyUse.isDown() + && (lethalOverride.getValue() || !needsTotem()) + && isHoldingSwordOrAxe() + && hasItem(Items.ENCHANTED_GOLDEN_APPLE)) { + return Items.ENCHANTED_GOLDEN_APPLE; + } + + if (hasItem(Items.TOTEM_OF_UNDYING)) { + if (needsTotem()) { + return Items.TOTEM_OF_UNDYING; + } + + if (item.getValue() == ItemMode.Crystal && smartMine.getValue()) { + if (!isPacketMining()) { + return Items.TOTEM_OF_UNDYING; + } + } + } + + return switch (item.getValue()) { + case Crystal -> hasItem(Items.END_CRYSTAL) ? Items.END_CRYSTAL : Items.TOTEM_OF_UNDYING; + case Gapple -> hasItem(Items.ENCHANTED_GOLDEN_APPLE) ? Items.ENCHANTED_GOLDEN_APPLE : Items.TOTEM_OF_UNDYING; + case Totem -> Items.TOTEM_OF_UNDYING; + }; + } + + private boolean needsTotem() { + if (mc.player == null || mc.level == null) return false; + + if (mc.player.getHealth() + mc.player.getAbsorptionAmount() <= health.getValue()) { + return true; + } + + if (mc.player.fallDistance > fallDistance.getValue()) { + return true; + } + + if (elytraCheck.getValue() + && mc.player.getItemBySlot(EquipmentSlot.CHEST).getItem() == Items.ELYTRA) { + return true; + } + + return antiMace.getValue() && isMaceDanger(); + } + + private boolean isMaceDanger() { + if (mc.player == null || mc.level == null) return false; + + double rangeSq = maceRange.getValue() * maceRange.getValue(); + + for (Player player : mc.level.players()) { + if (player == mc.player) continue; + if (!player.isAlive()) continue; + if (nolongerhuman.friendManager.isFriend(player)) continue; + if (mc.player.distanceToSqr(player) > rangeSq) continue; + if (player.fallDistance < 1.5f) continue; + + if (player.getMainHandItem().is(Items.MACE)) { + return true; + } + } + + return false; + } + + private boolean isPacketMining() { + if (nolongerhuman.moduleManager == null) return false; + + PacketMine packetMine = nolongerhuman.moduleManager.getModuleByClass(PacketMine.class); + + if (packetMine == null || !packetMine.isEnabled()) { + return false; + } + + try { + Field field = PacketMine.class.getDeclaredField("action"); + field.setAccessible(true); + + return field.get(packetMine) != null; + } catch (Throwable ignored) { + return false; + } + } + + private boolean isHoldingSwordOrAxe() { + if (mc.player == null) return false; + + Item item = mc.player.getMainHandItem().getItem(); + + return item instanceof AxeItem + || item == Items.WOODEN_SWORD + || item == Items.STONE_SWORD + || item == Items.IRON_SWORD + || item == Items.GOLDEN_SWORD + || item == Items.DIAMOND_SWORD + || item == Items.NETHERITE_SWORD; + } + + private boolean hasItem(Item itemToFind) { + if (mc.player == null) return false; + + return findItem(itemToFind) != -1 || mc.player.getOffhandItem().getItem() == itemToFind; + } + + private int findItem(Item itemToFind) { + int inventory = findInventory(itemToFind); + + if (inventory != -1) { + return inventory; + } + + return findHotbar(itemToFind); + } + + private int findInventory(Item itemToFind) { + if (mc.player == null) return -1; + + for (int i = 9; i <= 35; i++) { + if (mc.player.getInventory().getItem(i).getItem() == itemToFind) { + return i; + } + } + + return -1; + } + + private int findHotbar(Item itemToFind) { + if (mc.player == null) return -1; + + for (int i = 0; i <= 8; i++) { + if (mc.player.getInventory().getItem(i).getItem() == itemToFind) { + return i; + } + } + + return -1; + } + + private int findEmptySlot() { + if (mc.player == null) return -1; + + for (int i = 0; i <= 35; i++) { + if (mc.player.getInventory().getItem(i).isEmpty()) { + return i; + } + } + + return -1; + } + + private int countTotems() { + if (mc.player == null) return 0; + + int count = 0; + + for (int i = 0; i <= 35; i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (stack.getItem() == Items.TOTEM_OF_UNDYING) { + count += stack.getCount(); + } + } + + if (mc.player.getOffhandItem().getItem() == Items.TOTEM_OF_UNDYING) { + count += mc.player.getOffhandItem().getCount(); + } + + return count; + } + + private void moveToOffhand(int inventoryIndex) { + if (mc.player == null || mc.gameMode == null) return; + + int sourceSlot = inventoryIndexToContainerSlot(inventoryIndex); + + if (sourceSlot == -1) { + return; + } + + int syncId = mc.player.containerMenu.containerId; + + mc.gameMode.handleInventoryMouseClick(syncId, sourceSlot, 0, ClickType.PICKUP, mc.player); + mc.gameMode.handleInventoryMouseClick(syncId, 45, 0, ClickType.PICKUP, mc.player); + mc.gameMode.handleInventoryMouseClick(syncId, sourceSlot, 0, ClickType.PICKUP, mc.player); + } + + private int inventoryIndexToContainerSlot(int inventoryIndex) { + if (inventoryIndex >= 0 && inventoryIndex <= 8) { + return 36 + inventoryIndex; + } + + if (inventoryIndex >= 9 && inventoryIndex <= 35) { + return inventoryIndex; + } + + return -1; + } + + @Override + public String getDisplayInfo() { + return String.valueOf(totemCount); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PacketMine.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PacketMine.java new file mode 100644 index 0000000..e4a6121 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PacketMine.java @@ -0,0 +1,1617 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.impl.player.AttackBlockEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.EnchantmentUtil; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; + +public class PacketMine extends Module { + public enum SwitchMode { + None, + Normal, + Silent, + Alternative + } + + public enum RotateMode { + None, + Normal, + Packet + } + + public enum RenderMode { + Block, + Shrink, + Grow, + FadeIn, + FadeOut, + Pulse, + SlideUp, + SlideDown, + CenterGrow, + Pop, + GradientSolid, + VerticalShrink, + HorizontalGrow, + HorizontalShrink, + Flat, + FlatReverse, + CornerGrow, + CornerShrink, + Diamond, + Wave, + Breathe, + ExpandFade, + ContractFade, + OutlinePulse, + FillPulse, + Inverted + } + + public enum AnimationMode { + None, + Linear, + EaseIn, + EaseOut, + EaseInOut, + Elastic, + Fade + } + + private static final String ROT_ID = "packetmine"; + private static final int ROT_PRIORITY = 10; + private static final double MIN_RENDER_BOX_SIZE = 0.001D; + + public final Setting switchMode = mode("Switch", SwitchMode.Alternative); + public final Setting rotate = mode("Rotate", RotateMode.Packet); + + public final Setting range = num("Range", 5.0f, 1.0f, 8.0f); + public final Setting speed = num("Speed", 1.0f, 0.1f, 1.0f); + public final Setting swapDelay = num("SwapDelay", 50, 0, 1000); + public final Setting resetOnSwitch = bool("ResetOnSwitch", true); + public final Setting pauseEat = bool("PauseEat", false); + public final Setting clientRemove = bool("ClientRemove", true); + public final Setting onlyGround = bool("OnlyGround", false); + public final Setting strictSide = bool("StrictSide", false); + public final Setting farCancel = bool("FarCancel", true); + public final Setting preferWeb = bool("PreferWeb", true); + public final Setting preferHead = bool("PreferHead", false); + + public final Setting swing = bool("Swing", true); + public final Setting endSwing = bool("EndSwing", true); + + public final Setting stopPacket = bool("Stop", true); + public final Setting abortPacket = bool("Abort", false); + public final Setting startPacket = bool("Start", false); + public final Setting stop2Packet = bool("Stop2", false); + + public final Setting render = bool("Render", true); + public final Setting renderMode = mode("RenderMode", RenderMode.Shrink); + public final Setting blockAnimation = mode("BlockAnim", AnimationMode.EaseOut); + public final Setting blockAnimationTime = num("BlockAnimTime", 150, 0, 1000); + public final Setting smooth = bool("Smooth", true); + + public final Setting startFillColor = color("StartFill", new Color(255, 0, 0, 90)); + public final Setting endFillColor = color("EndFill", new Color(0, 255, 0, 90)); + public final Setting startOutlineColor = color("StartOutline", new Color(255, 0, 0, 220)); + public final Setting endOutlineColor = color("EndOutline", new Color(0, 255, 0, 220)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + + private MineAction action; + + private int pendingAltSlot = -1; + private int pendingAltButton = -1; + + private final Timer pendingSwapTimer = new Timer(); + + private boolean internalSwitching = false; + + private AABB animationStartBox = null; + private AABB animationCurrentBox = null; + private AABB animationTargetBox = null; + private AABB fadeOutBox = null; + private AABB fadeInBox = null; + private BlockPos lastRenderPos = null; + private long animationStartTime = 0L; + + public PacketMine() { + super("PacketMine", "Mines blocks faster using packets", Category.COMBAT); + } + + @Override + public void onEnable() { + clear(); + } + + @Override + public void onDisable() { + clear(); + clearRenderAnimation(); + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + clear(); + clearRenderAnimation(); + return; + } + + handlePendingAlternativeSwapBack(); + + if (action != null && action.update()) { + action = null; + clearRenderAnimation(); + } + } + + @SuppressWarnings("unused") + @Subscribe + public void onAttackBlock(AttackBlockEvent event) { + if (nullCheck()) { + return; + } + + if (mc.player == null) { + return; + } + + if (mc.player.getAbilities().instabuild) { + return; + } + + BlockPos pos = event.getPos(); + Direction direction = event.getDirection(); + + if (!canStartMining(pos, direction)) { + return; + } + + if (action != null && action.pos.equals(pos)) { + event.cancel(); + return; + } + + if (action != null) { + action.cancel(); + } + + action = new MineAction(pos, direction); + event.cancel(); + } + + @SuppressWarnings("unused") + @Subscribe + public void onPacketSend(PacketEvent.Send event) { + if (!resetOnSwitch.getValue()) { + return; + } + + if (internalSwitching) { + return; + } + + if (event.getPacket() instanceof ServerboundSetCarriedItemPacket) { + if (action != null) { + action.reset(); + } + } + } + + private boolean canStartMining(BlockPos pos, Direction direction) { + if (mc.player == null || mc.level == null) { + return false; + } + + if (pos == null) { + return false; + } + + if (isOutOfRange(pos)) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (state.isAir()) { + return false; + } + + if (state.is(Blocks.BEDROCK)) { + return false; + } + + if (state.is(Blocks.BARRIER)) { + return false; + } + + if (state.is(Blocks.END_PORTAL_FRAME)) { + return false; + } + + if (state.getDestroySpeed(mc.level, pos) < 0.0f) { + return false; + } + + if (strictSide.getValue() && direction == null) { + return false; + } + + if (preferWeb.getValue() && action != null && mc.level.getBlockState(action.pos).is(Blocks.COBWEB)) { + return state.is(Blocks.COBWEB); + } + + if (preferHead.getValue() && action != null && action.pos.equals(mc.player.blockPosition().above())) { + return pos.equals(mc.player.blockPosition().above()); + } + + return true; + } + + private boolean canContinueMining(BlockPos pos) { + if (mc.player == null || mc.level == null) { + return false; + } + + if (farCancel.getValue() && isOutOfRange(pos)) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (state.is(Blocks.BEDROCK)) { + return false; + } + + if (state.is(Blocks.BARRIER)) { + return false; + } + + if (state.is(Blocks.END_PORTAL_FRAME)) { + return false; + } + + return state.getDestroySpeed(mc.level, pos) >= 0.0f; + } + + private boolean isOutOfRange(BlockPos pos) { + if (mc.player == null) { + return true; + } + + return mc.player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) + > range.getValue() * range.getValue(); + } + + private int getBestTool(BlockPos pos) { + if (mc.player == null || mc.level == null) { + return -1; + } + + if (switchMode.getValue() == SwitchMode.None) { + return mc.player.getInventory().getSelectedSlot(); + } + + BlockState state = mc.level.getBlockState(pos); + + int selected = mc.player.getInventory().getSelectedSlot(); + int bestSlot = selected; + + float bestSpeed = getToolSpeed(state, mc.player.getInventory().getItem(selected)); + + int maxSlot = switchMode.getValue() == SwitchMode.Alternative ? 36 : 9; + + for (int i = 0; i < maxSlot; i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (stack.isEmpty()) { + continue; + } + + if (stack.isDamageableItem() && stack.getMaxDamage() - stack.getDamageValue() <= 10) { + continue; + } + + float toolSpeed = getToolSpeed(state, stack); + + if (toolSpeed > bestSpeed) { + bestSpeed = toolSpeed; + bestSlot = i; + } + } + + return bestSlot; + } + + private float getToolSpeed(BlockState state, ItemStack stack) { + if (stack.isEmpty()) { + return 1.0f; + } + + float speed = stack.getDestroySpeed(state); + int efficiency = EnchantmentUtil.getLevel(Enchantments.EFFICIENCY, stack); + + if (speed > 1.0f && efficiency > 0) { + speed += efficiency * efficiency + 1.0f; + } + + return speed; + } + + private float getBlockStrength(BlockPos pos, int slot) { + if (mc.player == null || mc.level == null) { + return 0.0f; + } + + BlockState state = mc.level.getBlockState(pos); + float hardness = state.getDestroySpeed(mc.level, pos); + + if (hardness < 0.0f) { + return 0.0f; + } + + ItemStack stack = slot >= 0 && slot < 36 + ? mc.player.getInventory().getItem(slot) + : mc.player.getMainHandItem(); + + float digSpeed = getDigSpeed(state, stack); + + return digSpeed / hardness / (canHarvest(pos, stack) ? 30.0f : 100.0f); + } + + private float getDigSpeed(BlockState state, ItemStack stack) { + if (mc.player == null) { + return 0.0f; + } + + float digSpeed = stack.isEmpty() ? 1.0f : stack.getDestroySpeed(state); + + if (digSpeed > 1.0f && !stack.isEmpty()) { + int efficiency = EnchantmentUtil.getLevel(Enchantments.EFFICIENCY, stack); + + if (efficiency > 0) { + digSpeed += efficiency * efficiency + 1.0f; + } + } + + MobEffectInstance haste = mc.player.getEffect(MobEffects.HASTE); + + if (haste != null) { + digSpeed *= 1.0f + (haste.getAmplifier() + 1) * 0.2f; + } + + MobEffectInstance miningFatigue = mc.player.getEffect(MobEffects.MINING_FATIGUE); + + if (miningFatigue != null) { + float multiplier = switch (miningFatigue.getAmplifier()) { + case 0 -> 0.3f; + case 1 -> 0.09f; + case 2 -> 0.0027f; + default -> 0.00081f; + }; + + digSpeed *= multiplier; + } + + if (mc.player.isUnderWater() + && !EnchantmentUtil.has(Enchantments.AQUA_AFFINITY, EquipmentSlot.HEAD, mc.player)) { + digSpeed /= 5.0f; + } + + if (!mc.player.onGround() && onlyGround.getValue()) { + digSpeed /= 5.0f; + } + + return Math.max(0.0f, digSpeed); + } + + private boolean canHarvest(BlockPos pos, ItemStack stack) { + if (mc.level == null) { + return false; + } + + if (stack.isEmpty()) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + try { + return stack.isCorrectToolForDrops(state); + } catch (Throwable ignored) { + return stack.getDestroySpeed(state) > 1.0f; + } + } + + private SwitchInfo switchTo(int slot) { + if (mc.player == null || mc.gameMode == null) { + return SwitchInfo.noSwitch(-1); + } + + int oldSlot = mc.player.getInventory().getSelectedSlot(); + + if (slot < 0 || slot >= 36) { + return SwitchInfo.noSwitch(oldSlot); + } + + if (switchMode.getValue() == SwitchMode.None) { + return SwitchInfo.noSwitch(oldSlot); + } + + if (slot == oldSlot) { + return new SwitchInfo( + oldSlot, + oldSlot, + -1, + oldSlot, + false, + false, + false, + false + ); + } + + if (isHotbarSlot(slot)) { + switch (switchMode.getValue()) { + case Normal -> { + setClientSlot(slot); + + return new SwitchInfo( + oldSlot, + slot, + -1, + slot, + true, + false, + false, + false + ); + } + + case Silent, Alternative -> { + serverSwap(slot); + + return new SwitchInfo( + oldSlot, + slot, + -1, + slot, + true, + false, + true, + false + ); + } + + default -> { + return SwitchInfo.noSwitch(oldSlot); + } + } + } + + if (isInventorySlot(slot) && switchMode.getValue() == SwitchMode.Alternative) { + internalSwitching = true; + + try { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + slot, + oldSlot, + ClickType.SWAP, + mc.player + ); + + serverSwap(oldSlot); + } finally { + internalSwitching = false; + } + + return new SwitchInfo( + oldSlot, + oldSlot, + slot, + oldSlot, + true, + true, + true, + false + ); + } + + return SwitchInfo.noSwitch(oldSlot); + } + + private void switchBack(SwitchInfo info) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + if (info == null || !info.switched() || info.switchedBack()) { + return; + } + + if (switchMode.getValue() == SwitchMode.Normal) { + return; + } + + if (info.inventorySwap()) { + if (swapDelay.getValue() <= 0) { + internalSwitching = true; + + try { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + info.inventorySlot(), + info.oldSlot(), + ClickType.SWAP, + mc.player + ); + } finally { + internalSwitching = false; + } + } else { + pendingAltSlot = info.inventorySlot(); + pendingAltButton = info.oldSlot(); + pendingSwapTimer.reset(); + } + + info.markSwitchedBack(); + return; + } + + if (info.serverSlotSwitch()) { + serverSwap(info.oldSlot()); + info.markSwitchedBack(); + } + } + + private void setClientSlot(int slot) { + if (mc.player == null) { + return; + } + + if (slot < 0 || slot > 8) { + return; + } + + internalSwitching = true; + + try { + mc.player.getInventory().setSelectedSlot(slot); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } finally { + internalSwitching = false; + } + } + + private void serverSwap(int hotbarSlot) { + if (mc.player == null) { + return; + } + + if (hotbarSlot < 0 || hotbarSlot > 8) { + return; + } + + internalSwitching = true; + + try { + mc.player.connection.send(new ServerboundSetCarriedItemPacket(hotbarSlot)); + } finally { + internalSwitching = false; + } + } + + private boolean isHotbarSlot(int slot) { + return slot >= 0 && slot <= 8; + } + + private boolean isInventorySlot(int slot) { + return slot >= 9 && slot < 36; + } + + private void handlePendingAlternativeSwapBack() { + if (pendingAltSlot == -1 || pendingAltButton == -1) { + return; + } + + if (mc.player == null || mc.gameMode == null) { + return; + } + + if (!pendingSwapTimer.passedMs(swapDelay.getValue().longValue())) { + return; + } + + internalSwitching = true; + + try { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + pendingAltSlot, + pendingAltButton, + ClickType.SWAP, + mc.player + ); + } finally { + internalSwitching = false; + } + + pendingAltSlot = -1; + pendingAltButton = -1; + } + + private boolean applyRotations(BlockPos pos, Direction direction) { + if (rotate.getValue() == RotateMode.None) { + return true; + } + + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + Vec3 hit = getHitVec(pos, direction); + + if (rotate.getValue() == RotateMode.Packet) { + rm.packetRotateTo(hit); + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, hit); + } + + private Vec3 getHitVec(BlockPos pos, Direction direction) { + if (direction == null) { + return Vec3.atCenterOf(pos); + } + + return Vec3.atCenterOf(pos).add( + direction.getStepX() * 0.5, + direction.getStepY() * 0.5, + direction.getStepZ() * 0.5 + ); + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private void sendAction(ServerboundPlayerActionPacket.Action action, BlockPos pos, Direction direction) { + if (mc.player == null || mc.getConnection() == null) { + return; + } + + BlockPos blockPos = pos instanceof BlockPos.MutableBlockPos + ? new BlockPos(pos) + : pos; + + mc.getConnection().send(new ServerboundPlayerActionPacket( + action, + blockPos, + direction == null ? Direction.UP : direction + )); + } + + private void clear() { + if (action != null) { + action.cancel(); + action = null; + } + + pendingAltSlot = -1; + pendingAltButton = -1; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + return; + } + + if (action == null) { + clearRenderAnimation(); + return; + } + + if (mc.level == null) { + clearRenderAnimation(); + return; + } + + action.render(event.getMatrix()); + } + + @Override + public String getDisplayInfo() { + if (action == null) { + return "Idle"; + } + + return Math.round(Mth.clamp(action.progress / speed.getValue(), 0.0f, 1.0f) * 100.0f) + "%"; + } + + private static boolean isInvalidRenderBox(AABB box) { + return box == null + || box.getXsize() <= MIN_RENDER_BOX_SIZE + || box.getYsize() <= MIN_RENDER_BOX_SIZE + || box.getZsize() <= MIN_RENDER_BOX_SIZE + || !Double.isFinite(box.minX) + || !Double.isFinite(box.minY) + || !Double.isFinite(box.minZ) + || !Double.isFinite(box.maxX) + || !Double.isFinite(box.maxY) + || !Double.isFinite(box.maxZ); + } + + private void updateBlockAnimation(BlockPos pos, AABB target) { + AnimationMode mode = blockAnimation.getValue(); + + if (mode == AnimationMode.None || blockAnimationTime.getValue() <= 0) { + animationStartBox = target; + animationCurrentBox = target; + animationTargetBox = target; + fadeOutBox = null; + fadeInBox = target; + lastRenderPos = pos; + animationStartTime = System.currentTimeMillis(); + return; + } + + if (animationTargetBox == null || lastRenderPos == null || !lastRenderPos.equals(pos)) { + if (mode == AnimationMode.Fade) { + fadeOutBox = animationCurrentBox == null ? animationTargetBox : animationCurrentBox; + fadeInBox = target; + animationStartBox = target; + animationCurrentBox = target; + animationTargetBox = target; + } else { + animationStartBox = animationCurrentBox == null ? target : animationCurrentBox; + animationTargetBox = target; + fadeOutBox = null; + fadeInBox = null; + } + + lastRenderPos = pos; + animationStartTime = System.currentTimeMillis(); + return; + } + + animationTargetBox = target; + + if (mode == AnimationMode.Fade) { + fadeInBox = target; + } + } + + private AABB getAnimatedRenderBox() { + if (animationTargetBox == null) { + return null; + } + + if (blockAnimation.getValue() == AnimationMode.None || blockAnimationTime.getValue() <= 0) { + animationCurrentBox = animationTargetBox; + return animationCurrentBox; + } + + if (animationStartBox == null) { + animationStartBox = animationTargetBox; + } + + long now = System.currentTimeMillis(); + + double progress = (double) (now - animationStartTime) / (double) blockAnimationTime.getValue(); + progress = clamp(progress, 0.0D, 1.0D); + + double eased = ease(progress, blockAnimation.getValue()); + + animationCurrentBox = lerp(animationStartBox, animationTargetBox, eased); + + if (progress >= 1.0D) { + animationCurrentBox = animationTargetBox; + animationStartBox = animationTargetBox; + } + + return animationCurrentBox; + } + + private void clearRenderAnimation() { + animationStartBox = null; + animationCurrentBox = null; + animationTargetBox = null; + fadeOutBox = null; + fadeInBox = null; + lastRenderPos = null; + animationStartTime = 0L; + } + + private AABB lerp(AABB from, AABB to, double progress) { + if (from == null) { + return to; + } + + if (to == null) { + return from; + } + + return new AABB( + lerp(from.minX, to.minX, progress), + lerp(from.minY, to.minY, progress), + lerp(from.minZ, to.minZ, progress), + lerp(from.maxX, to.maxX, progress), + lerp(from.maxY, to.maxY, progress), + lerp(from.maxZ, to.maxZ, progress) + ); + } + + private double lerp(double from, double to, double progress) { + return from + (to - from) * progress; + } + + private double ease(double progress, AnimationMode mode) { + progress = clamp(progress, 0.0D, 1.0D); + + return switch (mode) { + case None, Linear, Fade -> progress; + + case EaseIn -> progress * progress * progress; + + case EaseOut -> { + double inverse = 1.0D - progress; + yield 1.0D - inverse * inverse * inverse; + } + + case EaseInOut -> { + if (progress < 0.5D) { + yield 4.0D * progress * progress * progress; + } + + double value = -2.0D * progress + 2.0D; + + yield 1.0D - (value * value * value) / 2.0D; + } + + case Elastic -> { + if (progress == 0.0D || progress == 1.0D) { + yield progress; + } + + double c4 = (2.0D * Math.PI) / 3.0D; + + yield Math.pow(2.0D, -10.0D * progress) * Math.sin((progress * 10.0D - 0.75D) * c4) + 1.0D; + } + }; + } + + private double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private final class MineAction { + private final BlockPos pos; + private final Direction direction; + private final int originalToolSlot; + + private int miningSlot; + private SwitchInfo switchInfo; + + private float progress; + private float prevProgress; + + private MineAction(BlockPos pos, Direction direction) { + this.pos = pos; + this.direction = direction == null ? Direction.UP : direction; + this.originalToolSlot = getBestTool(pos); + this.miningSlot = originalToolSlot; + this.progress = 0.0f; + this.prevProgress = 0.0f; + + start(); + } + + private void start() { + if (mc.player == null) { + return; + } + + if (switchInfo != null) { + switchBack(switchInfo); + switchInfo = null; + } + + int toolSlot = originalToolSlot; + + if (toolSlot == -1) { + toolSlot = mc.player.getInventory().getSelectedSlot(); + } + + switchInfo = switchTo(toolSlot); + + int serverSelectedSlot = switchInfo.newSlot(); + + if (serverSelectedSlot >= 0 && serverSelectedSlot < 36) { + miningSlot = switchInfo.miningSlot(); + } else { + miningSlot = mc.player.getInventory().getSelectedSlot(); + } + + if (swing.getValue()) { + mc.player.swing(InteractionHand.MAIN_HAND); + } + + sendAction(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, direction); + + progress = 0.0f; + prevProgress = 0.0f; + } + + private boolean update() { + if (mc.player == null || mc.level == null) { + finishSwitch(); + return true; + } + + if (!canContinueMining(pos)) { + cancel(); + return true; + } + + if (pauseEat.getValue() && mc.player.isUsingItem()) { + return false; + } + + if (onlyGround.getValue() && !mc.player.onGround()) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (state.isAir()) { + finishSwitch(); + return true; + } + + prevProgress = progress; + + if (progress < speed.getValue()) { + progress += getBlockStrength(pos, miningSlot); + } + + if (progress >= speed.getValue()) { + if (!applyRotations(pos, direction)) { + return false; + } + + if (stopPacket.getValue()) { + sendAction(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, pos, direction); + } + + if (abortPacket.getValue()) { + sendAction(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, pos, direction); + } + + if (startPacket.getValue()) { + sendAction(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, pos, direction); + } + + if (stop2Packet.getValue()) { + sendAction(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, pos, direction); + } + + if (endSwing.getValue()) { + mc.player.connection.send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND)); + } + + if (clientRemove.getValue() && mc.gameMode != null) { + try { + mc.gameMode.destroyBlock(pos); + } catch (Throwable ignored) { + } + } + } + + return false; + } + + private void reset() { + finishSwitch(); + + progress = 0.0f; + prevProgress = 0.0f; + + start(); + } + + private void cancel() { + sendAction(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, pos, direction); + finishSwitch(); + } + + private void finishSwitch() { + if (switchInfo != null) { + switchBack(switchInfo); + switchInfo = null; + } + } + + private void render(PoseStack stack) { + if (mc.level == null) { + return; + } + + float speedValue = speed.getValue(); + + if (speedValue <= 0.0f) { + return; + } + + float progressValue = Mth.clamp(progress / speedValue, 0.0f, 1.0f); + float previousValue = Mth.clamp(prevProgress / speedValue, 0.0f, 1.0f); + float tickDelta = 1.0f; + + float interpolated = Mth.lerp(tickDelta, previousValue, progressValue); + interpolated = Mth.clamp(interpolated, 0.0f, 1.0f); + + AABB targetBox = getMiningBox(interpolated); + + if (isInvalidRenderBox(targetBox)) { + return; + } + + updateBlockAnimation(pos, targetBox); + + if (blockAnimation.getValue() == AnimationMode.Fade) { + renderFadeSwitch(stack, interpolated); + return; + } + + AABB box = getAnimatedRenderBox(); + + if (isInvalidRenderBox(box)) { + return; + } + + RenderColors colors = getRenderColors(interpolated); + + drawBox(stack, box, colors.fill(), colors.outline()); + } + + private AABB getMiningBox(float progress) { + progress = Mth.clamp(progress, 0.0f, 1.0f); + + double min = MIN_RENDER_BOX_SIZE; + double centerX = pos.getX() + 0.5D; + double centerY = pos.getY() + 0.5D; + double centerZ = pos.getZ() + 0.5D; + + return switch (renderMode.getValue()) { + case Block, FadeIn, FadeOut, GradientSolid, OutlinePulse, FillPulse, Inverted -> new AABB(pos); + + case Grow, SlideUp -> { + double height = Math.max(progress, min); + + yield new AABB( + pos.getX(), + pos.getY(), + pos.getZ(), + pos.getX() + 1.0D, + pos.getY() + height, + pos.getZ() + 1.0D + ); + } + + case SlideDown -> { + double height = Math.max(progress, min); + + yield new AABB( + pos.getX(), + pos.getY() + 1.0D - height, + pos.getZ(), + pos.getX() + 1.0D, + pos.getY() + 1.0D, + pos.getZ() + 1.0D + ); + } + + case Shrink, CenterGrow -> { + double shrink = (1.0D - progress) * 0.5D; + shrink = Math.min(shrink, 0.5D - min); + + yield new AABB(pos).deflate(shrink, shrink, shrink); + } + + case Pop -> { + double eased = easePop(progress); + double shrink = (1.0D - eased) * 0.5D; + shrink = Math.min(shrink, 0.5D - min); + + yield new AABB(pos).deflate(shrink, shrink, shrink); + } + + case Pulse -> { + double pulse = Math.sin(progress * Math.PI); + double inflate = pulse * 0.08D; + + yield new AABB(pos).inflate(inflate, inflate, inflate); + } + + case VerticalShrink -> { + double halfHeight = Math.max(progress * 0.5D, min); + + yield new AABB( + pos.getX(), + centerY - halfHeight, + pos.getZ(), + pos.getX() + 1.0D, + centerY + halfHeight, + pos.getZ() + 1.0D + ); + } + + case HorizontalGrow -> { + double half = Math.max(progress * 0.5D, min); + + yield new AABB( + centerX - half, + pos.getY(), + centerZ - half, + centerX + half, + pos.getY() + 1.0D, + centerZ + half + ); + } + + case HorizontalShrink -> { + double half = Math.max((1.0D - progress) * 0.5D, min); + + yield new AABB( + centerX - half, + pos.getY(), + centerZ - half, + centerX + half, + pos.getY() + 1.0D, + centerZ + half + ); + } + + case Flat -> { + double height = Math.max(0.02D, progress * 0.08D); + + yield new AABB( + pos.getX(), + pos.getY(), + pos.getZ(), + pos.getX() + 1.0D, + pos.getY() + height, + pos.getZ() + 1.0D + ); + } + + case FlatReverse -> { + double height = Math.max(0.02D, progress * 0.08D); + + yield new AABB( + pos.getX(), + pos.getY() + 1.0D - height, + pos.getZ(), + pos.getX() + 1.0D, + pos.getY() + 1.0D, + pos.getZ() + 1.0D + ); + } + + case CornerGrow -> { + double size = Math.max(progress, min); + + yield new AABB( + pos.getX(), + pos.getY(), + pos.getZ(), + pos.getX() + size, + pos.getY() + size, + pos.getZ() + size + ); + } + + case CornerShrink -> { + double size = Math.max(1.0D - progress, min); + + yield new AABB( + pos.getX(), + pos.getY(), + pos.getZ(), + pos.getX() + size, + pos.getY() + size, + pos.getZ() + size + ); + } + + case Diamond -> { + double size = Math.max(progress * 0.5D, min); + double wave = Math.sin(progress * Math.PI) * 0.08D; + + yield new AABB( + centerX - size - wave, + centerY - size, + centerZ - size - wave, + centerX + size + wave, + centerY + size, + centerZ + size + wave + ); + } + + case Wave -> { + double wave = 0.08D + Math.sin(progress * Math.PI * 4.0D) * 0.05D; + double shrink = (1.0D - progress) * 0.5D; + shrink = Math.min(shrink, 0.5D - min); + + yield new AABB(pos).deflate(shrink, shrink, shrink).inflate(wave, wave, wave); + } + + case Breathe -> { + double breathe = 0.04D + Math.sin(System.currentTimeMillis() / 120.0D) * 0.035D; + double shrink = (1.0D - progress) * 0.5D; + shrink = Math.min(shrink, 0.5D - min); + + yield new AABB(pos).deflate(shrink, shrink, shrink).inflate(breathe, breathe, breathe); + } + + case ExpandFade -> { + double inflate = progress * 0.15D; + + yield new AABB(pos).inflate(inflate, inflate, inflate); + } + + case ContractFade -> { + double shrink = progress * 0.45D; + shrink = Math.min(shrink, 0.5D - min); + + yield new AABB(pos).deflate(shrink, shrink, shrink); + } + }; + } + + private RenderColors getRenderColors(float progress) { + Color fill = getProgressColor( + startFillColor.getValue(), + endFillColor.getValue(), + progress, + smooth.getValue() + ); + + Color outline = getProgressColor( + startOutlineColor.getValue(), + endOutlineColor.getValue(), + progress, + smooth.getValue() + ); + + switch (renderMode.getValue()) { + case FadeIn -> { + fill = withAlphaMultiplier(fill, progress); + outline = withAlphaMultiplier(outline, progress); + } + + case FadeOut -> { + double alpha = 1.0D - progress; + fill = withAlphaMultiplier(fill, alpha); + outline = withAlphaMultiplier(outline, alpha); + } + + case Pulse -> { + double pulse = 0.35D + Math.sin(progress * Math.PI) * 0.65D; + fill = withAlphaMultiplier(fill, pulse); + outline = withAlphaMultiplier(outline, pulse); + } + + case GradientSolid -> { + fill = getGradientSolidColor(startFillColor.getValue(), endFillColor.getValue(), progress, true); + outline = getGradientSolidColor(startOutlineColor.getValue(), endOutlineColor.getValue(), progress, false); + } + + case Wave -> { + double wave = 0.45D + Math.sin(progress * Math.PI * 4.0D) * 0.35D + progress * 0.2D; + fill = withAlphaMultiplier(fill, wave); + outline = withAlphaMultiplier(outline, Math.min(1.0D, wave + 0.2D)); + } + + case Breathe -> { + double breathe = 0.65D + Math.sin(System.currentTimeMillis() / 120.0D) * 0.25D; + fill = withAlphaMultiplier(fill, breathe); + outline = withAlphaMultiplier(outline, breathe); + } + + case ExpandFade -> { + double alpha = 1.0D - progress * 0.65D; + fill = withAlphaMultiplier(fill, alpha); + outline = withAlphaMultiplier(outline, alpha); + } + + case ContractFade -> { + double alpha = 0.25D + progress * 0.75D; + fill = withAlphaMultiplier(fill, alpha); + outline = withAlphaMultiplier(outline, alpha); + } + + case OutlinePulse -> { + double pulse = 0.35D + Math.sin(progress * Math.PI * 6.0D) * 0.35D + progress * 0.3D; + fill = withAlphaMultiplier(fill, 0.0D); + outline = withAlphaMultiplier(outline, pulse); + } + + case FillPulse -> { + double pulse = 0.35D + Math.sin(progress * Math.PI * 6.0D) * 0.35D + progress * 0.3D; + fill = withAlphaMultiplier(fill, pulse); + outline = withAlphaMultiplier(outline, 0.25D); + } + + case Inverted -> { + fill = getProgressColor(endFillColor.getValue(), startFillColor.getValue(), progress, smooth.getValue()); + outline = getProgressColor(endOutlineColor.getValue(), startOutlineColor.getValue(), progress, smooth.getValue()); + } + + default -> { + } + } + + return new RenderColors(fill, outline); + } + + private void renderFadeSwitch(PoseStack stack, float mineProgress) { + if (blockAnimationTime.getValue() <= 0) { + AABB box = animationTargetBox; + + if (!isInvalidRenderBox(box)) { + RenderColors colors = getRenderColors(mineProgress); + drawBox(stack, box, colors.fill(), colors.outline()); + } + + fadeOutBox = null; + fadeInBox = animationTargetBox; + animationCurrentBox = animationTargetBox; + return; + } + + long now = System.currentTimeMillis(); + + double switchProgress = (double) (now - animationStartTime) / (double) blockAnimationTime.getValue(); + switchProgress = clamp(switchProgress, 0.0D, 1.0D); + + double eased = ease(switchProgress, AnimationMode.EaseOut); + + RenderColors colors = getRenderColors(mineProgress); + + double fadeOutAlpha = 1.0D - eased; + double fadeInAlpha = eased; + + if (fadeOutBox != null && fadeOutAlpha > 0.01D && !isInvalidRenderBox(fadeOutBox)) { + drawBox( + stack, + fadeOutBox, + withAlphaMultiplier(colors.fill(), fadeOutAlpha), + withAlphaMultiplier(colors.outline(), fadeOutAlpha) + ); + } + + AABB inBox = fadeInBox == null ? animationTargetBox : fadeInBox; + + if (inBox != null && fadeInAlpha > 0.01D && !isInvalidRenderBox(inBox)) { + drawBox( + stack, + inBox, + withAlphaMultiplier(colors.fill(), fadeInAlpha), + withAlphaMultiplier(colors.outline(), fadeInAlpha) + ); + } + + if (switchProgress >= 1.0D) { + fadeOutBox = null; + fadeInBox = animationTargetBox; + animationCurrentBox = animationTargetBox; + } + } + } + + private void drawBox(PoseStack stack, AABB box, Color fill, Color outline) { + if (fill != null && fill.getAlpha() > 0) { + RenderUtil.drawBoxFilled(stack, box, fill); + } + + if (outline != null && outline.getAlpha() > 0 && lineWidth.getValue() > 0.0f) { + RenderUtil.drawBox(stack, box, outline, lineWidth.getValue()); + } + } + + private static Color getProgressColor(Color start, Color end, float progress, boolean smooth) { + if (!smooth) { + return progress >= 0.9f ? end : start; + } + + progress = Mth.clamp(progress, 0.0f, 1.0f); + + int r = (int) (start.getRed() + (end.getRed() - start.getRed()) * progress); + int g = (int) (start.getGreen() + (end.getGreen() - start.getGreen()) * progress); + int b = (int) (start.getBlue() + (end.getBlue() - start.getBlue()) * progress); + int a = (int) (start.getAlpha() + (end.getAlpha() - start.getAlpha()) * progress); + + return new Color( + clampColor(r), + clampColor(g), + clampColor(b), + clampColor(a) + ); + } + + private static Color getGradientSolidColor(Color start, Color end, float progress, boolean fill) { + progress = Mth.clamp(progress, 0.0f, 1.0f); + + float colorProgress = progress * progress; + float alphaProgress = fill + ? 0.25f + progress * 0.75f + : 0.45f + progress * 0.55f; + + int r = (int) (start.getRed() + (end.getRed() - start.getRed()) * colorProgress); + int g = (int) (start.getGreen() + (end.getGreen() - start.getGreen()) * colorProgress); + int b = (int) (start.getBlue() + (end.getBlue() - start.getBlue()) * colorProgress); + int a = (int) ((start.getAlpha() + (end.getAlpha() - start.getAlpha()) * progress) * alphaProgress); + + return new Color( + clampColor(r), + clampColor(g), + clampColor(b), + clampColor(a) + ); + } + + private static Color withAlphaMultiplier(Color color, double multiplier) { + if (color == null) { + return null; + } + + multiplier = Math.max(0.0D, Math.min(1.0D, multiplier)); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + clampColor(alpha) + ); + } + + private static int clampColor(int value) { + return Math.max(0, Math.min(255, value)); + } + + private double easePop(double progress) { + progress = clamp(progress, 0.0D, 1.0D); + + double overshoot = 1.70158D; + double value = progress - 1.0D; + + return 1.0D + value * value * ((overshoot + 1.0D) * value + overshoot); + } + + private record RenderColors(Color fill, Color outline) { + } + + private static final class SwitchInfo { + private final int oldSlot; + private final int newSlot; + private final int inventorySlot; + private final int miningSlot; + + private final boolean switched; + private final boolean inventorySwap; + private final boolean serverSlotSwitch; + + private boolean switchedBack; + + private SwitchInfo( + int oldSlot, + int newSlot, + int inventorySlot, + int miningSlot, + boolean switched, + boolean inventorySwap, + boolean serverSlotSwitch, + boolean switchedBack + ) { + this.oldSlot = oldSlot; + this.newSlot = newSlot; + this.inventorySlot = inventorySlot; + this.miningSlot = miningSlot; + this.switched = switched; + this.inventorySwap = inventorySwap; + this.serverSlotSwitch = serverSlotSwitch; + this.switchedBack = switchedBack; + } + + private static SwitchInfo noSwitch(int slot) { + return new SwitchInfo( + slot, + slot, + -1, + slot, + false, + false, + false, + false + ); + } + + private int oldSlot() { + return oldSlot; + } + + private int newSlot() { + return newSlot; + } + + private int inventorySlot() { + return inventorySlot; + } + + private int miningSlot() { + return miningSlot; + } + + private boolean switched() { + return switched; + } + + private boolean inventorySwap() { + return inventorySwap; + } + + private boolean serverSlotSwitch() { + return serverSlotSwitch; + } + + private boolean switchedBack() { + return switchedBack; + } + + private void markSwitchedBack() { + switchedBack = true; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PearlCatcher.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PearlCatcher.java new file mode 100644 index 0000000..d62ad9d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PearlCatcher.java @@ -0,0 +1,532 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class PearlCatcher extends Module { + + private static final String ROT_ID = "pearlcatcher"; + private static final int ROT_PRIORITY = 3; + + private final Setting range = num("Range", 6.0, 1.0, 6.0); + private final Setting blocksPerTick = num("ShiftTicks", 1, 1, 10); + private final Setting delay = num("Delay", 0, 0, 1000); + private final Setting targetRange = num("TargetRange", 5.0, 1.0, 10.0); + private final Setting rotate = bool("Rotate", true); + private final Setting strictDirection = bool("Strict", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(120, 180, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(120, 180, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final Timer timer = new Timer(); + private final Map oppPearls = new ConcurrentHashMap<>(); + private final List toPlace = new ArrayList<>(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private Entity target; + + public PearlCatcher() { + super("PearlCatcher", "Blocks thrown pearls with airplace", Category.COMBAT); + } + + @Override + public void onEnable() { + timer.reset(); + oppPearls.clear(); + toPlace.clear(); + renderPositions.clear(); + renderFadeState.reset(); + target = null; + } + + @Override + public void onDisable() { + clearRotations(); + oppPearls.clear(); + toPlace.clear(); + renderPositions.clear(); + renderFadeState.reset(); + target = null; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + target = getTarget(player, level, targetRange.getValue()); + + scanPearls(player, level); + removeDeadPearls(level); + + toPlace.clear(); + + if (target == null) { + renderPositions.clear(); + return; + } + + if (player.isUsingItem()) { + return; + } + + if (findHotbarObsidian(player) == -1) { + return; + } + + if (!timer.passedMs(delay.getValue())) { + return; + } + + if (oppPearls.isEmpty()) { + renderPositions.clear(); + return; + } + + List pearls = getPearlsSortedByDistance(player, level); + + if (pearls.isEmpty()) { + renderPositions.clear(); + return; + } + + for (Entity pearl : pearls) { + BlockPos catchPos = findCatchPos(player, level, pearl); + + if (catchPos == null) { + continue; + } + + if (toPlace.contains(catchPos)) { + continue; + } + + toPlace.add(catchPos); + + if (toPlace.size() >= blocksPerTick.getValue()) { + break; + } + } + + renderPositions.clear(); + renderPositions.addAll(toPlace); + + if (toPlace.isEmpty()) { + return; + } + + int placed = placeQueued(player, gameMode); + + if (placed > 0) { + timer.reset(); + } + } + + private void scanPearls(LocalPlayer self, ClientLevel level) { + for (Entity entity : level.entitiesForRendering()) { + if (shouldSkipPearl(entity)) { + continue; + } + + if (oppPearls.containsKey(entity.getId())) { + continue; + } + + Player nearest = null; + double nearestDistance = Double.MAX_VALUE; + + for (Player player : level.players()) { + if (player == self) { + continue; + } + + if (nolongerhuman.friendManager.isFriend(player)) { + continue; + } + + double distance = player.distanceTo(entity); + + if (distance > 3.0) { + continue; + } + + if (distance < nearestDistance) { + nearestDistance = distance; + nearest = player; + } + } + + if (nearest != null) { + oppPearls.put(entity.getId(), nearest.getName().getString()); + } + } + } + + private void removeDeadPearls(ClientLevel level) { + oppPearls.keySet().removeIf(id -> { + Entity entity = level.getEntity(id); + return shouldSkipPearl(entity) || !entity.isAlive(); + }); + } + + private List getPearlsSortedByDistance(LocalPlayer player, ClientLevel level) { + List pearls = new ArrayList<>(); + + for (Integer id : oppPearls.keySet()) { + Entity entity = level.getEntity(id); + + if (shouldSkipPearl(entity) || !entity.isAlive()) { + continue; + } + + pearls.add(entity); + } + + pearls.sort(Comparator.comparingDouble(player::distanceTo)); + return pearls; + } + + private Entity getNearestPearl(LocalPlayer player, ClientLevel level) { + Entity nearest = null; + double nearestDistance = Double.MAX_VALUE; + + for (Integer id : oppPearls.keySet()) { + Entity entity = level.getEntity(id); + + if (shouldSkipPearl(entity) || !entity.isAlive()) { + continue; + } + + double distance = player.distanceTo(entity); + + if (distance < nearestDistance) { + nearestDistance = distance; + nearest = entity; + } + } + + return nearest; + } + + private boolean shouldSkipPearl(Entity entity) { + return entity == null || !entity.getType().toString().toLowerCase().contains("ender_pearl"); + } + + private BlockPos findCatchPos(LocalPlayer player, ClientLevel level, Entity pearl) { + Vec3 pos = pearl.position(); + Vec3 velocity = pearl.getDeltaMovement(); + + for (int i = 0; i < 80; i++) { + pos = pos.add(velocity); + velocity = velocity.scale(0.99).add(0.0, -0.03, 0.0); + + BlockPos blockPos = BlockPos.containing(pos.x, pos.y, pos.z); + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(blockPos)) > range.getValue() * range.getValue()) { + continue; + } + + if (canPlaceBlock(level, blockPos, strictDirection.getValue())) { + return blockPos; + } + + if (!level.getBlockState(blockPos).isAir()) { + return null; + } + } + + return null; + } + + private int placeQueued(LocalPlayer player, MultiPlayerGameMode gameMode) { + if (toPlace.isEmpty()) { + return 0; + } + + int slot = findHotbarObsidian(player); + + if (slot == -1) { + return 0; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + int placed = 0; + + for (BlockPos pos : toPlace) { + if (placed >= blocksPerTick.getValue()) { + break; + } + + if (!switched) { + switchSlot(player, slot); + switched = true; + } + + if (rotate.getValue()) { + applyRotations(Vec3.atCenterOf(pos)); + } + + if (placeBlock(player, gameMode, pos)) { + placed++; + } + } + + if (switched) { + switchSlot(player, oldSlot); + } + + resetSpoofIfNeeded(); + toPlace.clear(); + + return placed; + } + + private Entity getTarget(LocalPlayer self, ClientLevel level, double range) { + Player best = null; + double bestDistance = Double.MAX_VALUE; + + for (Player player : level.players()) { + if (player == self) { + continue; + } + + if (!player.isAlive()) { + continue; + } + + if (nolongerhuman.friendManager.isFriend(player)) { + continue; + } + + double distance = self.distanceTo(player); + + if (distance > range) { + continue; + } + + if (distance < bestDistance) { + bestDistance = distance; + best = player; + } + } + + return best; + } + + private boolean placeBlock(LocalPlayer player, MultiPlayerGameMode gameMode, BlockPos pos) { + BlockHitResult hit = buildHitResult(pos, strictDirection.getValue()); + + if (hit == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hit); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private boolean canPlaceBlock(ClientLevel level, BlockPos pos, boolean strict) { + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + if (!level.getEntitiesOfClass(Entity.class, new AABB(pos), entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return buildHitResult(pos, strict) != null; + } + + private BlockHitResult buildHitResult(BlockPos pos, boolean strict) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = null; + Vec3 bestHit = null; + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + if (strict) { + Vec3 normal = new Vec3(side.getStepX(), side.getStepY(), side.getStepZ()).normalize(); + Vec3 toEye = eye.subtract(hit).normalize(); + + if (toEye.dot(normal) <= 0.0) { + continue; + } + } + + double distance = eye.distanceTo(hit); + + if (distance < bestDist) { + bestDist = distance; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private int findHotbarObsidian(LocalPlayer player) { + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(Items.OBSIDIAN)) { + return i; + } + } + + return -1; + } + + private void switchSlot(LocalPlayer player, int slot) { + if (slot < 0 || slot > 8) { + return; + } + + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private void applyRotations(Vec3 vec) { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.applyRotationTo(ROT_ID, ROT_PRIORITY, vec); + } + + private void resetSpoofIfNeeded() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + return; + } + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + rotationManager.resetSpoofedRotations(); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } + + @Override + public String getDisplayInfo() { + return String.valueOf(oppPearls.size()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PearlChaser.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PearlChaser.java new file mode 100644 index 0000000..99c0f0c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/PearlChaser.java @@ -0,0 +1,469 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class PearlChaser extends Module { + + private static final String ROT_ID = "autopearl"; + private static final int ROT_PRIORITY = 100; + + private final Setting stopMotion = bool("StopMotion", false); + private final Setting legitStop = bool("LegitStop", false); + private final Setting pauseAura = bool("PauseAura", false); + private final Setting onlyOnGround = bool("OnlyOnGround", false); + private final Setting noMove = bool("NoMove", false); + private final Setting onlyTarget = bool("OnlyTarget", false); + + private final Setting delay = num("Delay", 100, 0, 2000); + private final Setting minHealth = num("MinHealth", 5.0f, 0.0f, 36.0f); + private final Setting selfIgnoreRange = num("SelfIgnoreRange", 7.0, 0.0, 16.0); + private final Setting traceTolerance = num("TraceTolerance", 6.0, 1.0, 12.0); + + private final Timer delayTimer = new Timer(); + + private final Set seenPearls = new HashSet<>(); + private final Set ownPearls = new HashSet<>(); + private final Map targets = new HashMap<>(); + + private BlockPos targetBlock; + private int lastPearlId = -1; + private boolean reEnableAura; + + public PearlChaser() { + super("PearlChaser", "Throws a pearl to chase enemy pearls", Category.COMBAT); + } + + @Override + public void onEnable() { + delayTimer.reset(); + seenPearls.clear(); + ownPearls.clear(); + targets.clear(); + targetBlock = null; + lastPearlId = -1; + reEnableAura = false; + } + + @Override + public void onDisable() { + clearRotations(); + seenPearls.clear(); + ownPearls.clear(); + targets.clear(); + targetBlock = null; + lastPearlId = -1; + + if (reEnableAura) { + Module aura = nolongerhuman.moduleManager.getModuleByClass(Aura.class); + if (aura != null && !aura.isEnabled()) { + aura.enable(); + } + } + + reEnableAura = false; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) return; + + updateTargets(); + expireTargets(); + scanOwnPearls(player, level); + + if (player.getHealth() + player.getAbsorptionAmount() < minHealth.getValue()) return; + if (!delayTimer.passedMs(delay.getValue())) return; + + Entity pearl = findPearlToChase(player, level); + if (pearl == null) return; + + targetBlock = calcTrajectory(level, pearl); + if (targetBlock == null) return; + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(targetBlock)) < selfIgnoreRange.getValue() * selfIgnoreRange.getValue()) { + return; + } + + float pitch = (float) -Math.toDegrees(calcThrowPitch(player, targetBlock)); + float yaw = (float) Math.toDegrees(Math.atan2( + targetBlock.getZ() + 0.5 - player.getZ(), + targetBlock.getX() + 0.5 - player.getX() + )) - 90.0f; + + pitch = Mth.clamp(pitch, -89.0f, 89.0f); + + BlockPos traced = checkTrajectory(player, level, yaw, pitch); + if (traced == null) return; + + if (Vec3.atCenterOf(targetBlock).distanceToSqr(Vec3.atCenterOf(traced)) > traceTolerance.getValue() * traceTolerance.getValue()) { + return; + } + + if (onlyOnGround.getValue() && !player.onGround()) return; + if (noMove.getValue() && isMoving(player)) return; + + if (stopMotion.getValue()) { + stopPlayer(player); + return; + } + + int pearlSlot = findPearlSlot(player); + if (pearlSlot == -1) return; + + if (pauseAura.getValue()) { + pauseAuraForThrow(); + } + + nolongerhuman.rotationManager.applyRotation(ROT_ID, ROT_PRIORITY, yaw, pitch); + + player.setYRot(yaw); + player.setXRot(pitch); + + throwPearl(player, gameMode, pearlSlot); + + targetBlock = null; + lastPearlId = pearl.getId(); + delayTimer.reset(); + } + + private void updateTargets() { + if (!onlyTarget.getValue()) return; + + Module auraModule = nolongerhuman.moduleManager.getModuleByClass(Aura.class); + if (auraModule instanceof Aura aura && aura.isEnabled() && aura.target instanceof Player player) { + targets.put(player, System.currentTimeMillis()); + } + + } + + private void expireTargets() { + long now = System.currentTimeMillis(); + targets.entrySet().removeIf(entry -> now - entry.getValue() > 10_000L); + } + + private void scanOwnPearls(LocalPlayer self, ClientLevel level) { + for (Entity entity : level.entitiesForRendering()) { + if (!isPearl(entity)) continue; + if (seenPearls.contains(entity.getId())) continue; + + seenPearls.add(entity.getId()); + + Player nearest = level.players() + .stream() + .min(Comparator.comparingDouble(player -> player.distanceToSqr(entity))) + .orElse(null); + + if (nearest == self) { + ownPearls.add(entity.getId()); + } + } + + ownPearls.removeIf(id -> { + Entity entity = level.getEntity(id); + return entity == null || !entity.isAlive() || !isPearl(entity); + }); + + seenPearls.removeIf(id -> { + Entity entity = level.getEntity(id); + return entity == null || !entity.isAlive() || !isPearl(entity); + }); + } + + private Entity findPearlToChase(LocalPlayer self, ClientLevel level) { + Entity best = null; + double bestDistance = Double.MAX_VALUE; + + for (Entity entity : level.entitiesForRendering()) { + if (!isPearl(entity)) continue; + if (!entity.isAlive()) continue; + if (entity.getId() == lastPearlId) continue; + if (ownPearls.contains(entity.getId())) continue; + + Player thrower = getNearestPlayerToPearl(self, level, entity); + if (thrower == null) continue; + if (thrower == self) continue; + if (nolongerhuman.friendManager.isFriend(thrower)) continue; + + if (onlyTarget.getValue() && !targets.containsKey(thrower)) { + continue; + } + + double distance = self.distanceToSqr(entity); + if (distance < bestDistance) { + bestDistance = distance; + best = entity; + } + } + + return best; + } + + private Player getNearestPlayerToPearl(LocalPlayer self, ClientLevel level, Entity pearl) { + Player best = null; + double bestDistance = Double.MAX_VALUE; + + for (Player player : level.players()) { + double distance = player.distanceToSqr(pearl); + if (distance > bestDistance) continue; + + bestDistance = distance; + best = player; + } + + return best; + } + + private boolean isPearl(Entity entity) { + return entity.getType().toString().toLowerCase().contains("ender_pearl"); + } + + private boolean isArrow(Entity entity) { + String type = entity.getType().toString().toLowerCase(); + return type.contains("arrow") || type.contains("spectral_arrow"); + } + + private int findPearlSlot(LocalPlayer player) { + if (player.getMainHandItem().is(Items.ENDER_PEARL)) { + return player.getInventory().getSelectedSlot(); + } + + for (int i = 0; i < 9; i++) { + if (player.getInventory().getItem(i).is(Items.ENDER_PEARL)) { + return i; + } + } + + return -1; + } + + private void throwPearl(LocalPlayer player, MultiPlayerGameMode gameMode, int pearlSlot) { + int oldSlot = player.getInventory().getSelectedSlot(); + + if (pearlSlot != oldSlot) { + player.getInventory().setSelectedSlot(pearlSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(pearlSlot)); + } + + gameMode.useItem(player, InteractionHand.MAIN_HAND); + player.swing(InteractionHand.MAIN_HAND); + + if (pearlSlot != oldSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (reEnableAura) { + Module aura = nolongerhuman.moduleManager.getModuleByClass(Aura.class); + if (aura != null && !aura.isEnabled()) { + aura.enable(); + } + + reEnableAura = false; + } + } + + private void pauseAuraForThrow() { + Module aura = nolongerhuman.moduleManager.getModuleByClass(Aura.class); + + if (aura != null && aura.isEnabled()) { + aura.disable(); + reEnableAura = true; + } + } + + private boolean isMoving(LocalPlayer player) { + return player.zza != 0.0f || player.xxa != 0.0f; + } + + private void stopPlayer(LocalPlayer player) { + if (!legitStop.getValue()) { + player.setDeltaMovement(0.0, 0.0, 0.0); + } + + mc.options.keyUp.setDown(false); + mc.options.keyDown.setDown(false); + mc.options.keyLeft.setDown(false); + mc.options.keyRight.setDown(false); + + player.zza = 0.0f; + player.xxa = 0.0f; + } + + private float calcThrowPitch(LocalPlayer player, BlockPos blockPos) { + double horizontal = Math.hypot( + blockPos.getX() + 0.5 - player.getX(), + blockPos.getZ() + 0.5 - player.getZ() + ); + + double y = 6.125 * ( + (blockPos.getY() + 1.0) + - (player.getY() + player.getEyeHeight(player.getPose())) + ); + + y = 0.05000000074505806 * ((0.05000000074505806 * (horizontal * horizontal)) + y); + + if (y > 9.37890625) { + return Float.NaN; + } + + y = Math.sqrt(9.37890625 - y); + + double d = 3.0625 - y; + y = Math.atan2(d * d + y, 0.05000000074505806 * horizontal); + d = Math.atan2(d, 0.05000000074505806 * horizontal); + + return (float) Math.min(y, d); + } + + private BlockPos calcTrajectory(ClientLevel level, Entity entity) { + Vec3 velocity = entity.getDeltaMovement(); + + return traceTrajectory( + level, + entity.getX(), + entity.getY(), + entity.getZ(), + velocity.x, + velocity.y, + velocity.z + ); + } + + private BlockPos checkTrajectory(LocalPlayer player, ClientLevel level, float yaw, float pitch) { + if (Float.isNaN(pitch)) return null; + + float yawRad = yaw / 180.0f * Mth.PI; + float pitchRad = pitch / 180.0f * Mth.PI; + + double x = player.getX() - Mth.cos(yawRad) * 0.16f; + double y = player.getY() + player.getEyeHeight(player.getPose()) - 0.1000000014901161; + double z = player.getZ() - Mth.sin(yawRad) * 0.16f; + + double motionX = -Mth.sin(yawRad) * Mth.cos(pitchRad) * 0.4f; + double motionY = -Mth.sin(pitchRad) * 0.4f; + double motionZ = Mth.cos(yawRad) * Mth.cos(pitchRad) * 0.4f; + + float distance = Mth.sqrt((float) (motionX * motionX + motionY * motionY + motionZ * motionZ)); + if (distance == 0.0f) return null; + + motionX /= distance; + motionY /= distance; + motionZ /= distance; + + motionX *= 1.5f; + motionY *= 1.5f; + motionZ *= 1.5f; + + if (!player.onGround()) { + motionY += player.getDeltaMovement().y; + } + + return traceTrajectory(level, x, y, z, motionX, motionY, motionZ); + } + + private BlockPos traceTrajectory(ClientLevel level, double x, double y, double z, double motionX, double motionY, double motionZ) { + LocalPlayer player = mc.player; + if (player == null) return null; + + for (int i = 0; i < 300; i++) { + Vec3 lastPos = new Vec3(x, y, z); + + x += motionX; + y += motionY; + z += motionZ; + + motionX *= 0.99; + motionY *= 0.99; + motionZ *= 0.99; + motionY -= 0.03; + + Vec3 pos = new Vec3(x, y, z); + + BlockHitResult hitResult = level.clip(new ClipContext( + lastPos, + pos, + ClipContext.Block.OUTLINE, + ClipContext.Fluid.NONE, + player + )); + + if (hitResult.getType() == HitResult.Type.BLOCK) { + return hitResult.getBlockPos(); + } + + AABB pearlBox = new AABB( + x - 0.3, + y - 0.3, + z - 0.3, + x + 0.3, + y + 0.3, + z + 0.2 + ); + + for (Entity entity : level.entitiesForRendering()) { + if (entity == player) continue; + if (isArrow(entity)) continue; + if (isPearl(entity)) continue; + + if (entity.getBoundingBox().intersects(pearlBox)) { + return null; + } + } + + if (y <= -65.0) break; + } + + return null; + } + + private void clearRotations() { + RotationManager rotationManager = nolongerhuman.rotationManager; + if (rotationManager == null) return; + + rotationManager.cancel(ROT_ID); + rotationManager.clearRotations(ROT_PRIORITY); + + RotationManager.RotationMethod method = rotationManager.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rotationManager.resetSpoofedRotations(); + } + } + + @Override + public String getDisplayInfo() { + return targetBlock == null ? "Idle" : "Chasing"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/SelfBow.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/SelfBow.java new file mode 100644 index 0000000..e6bada4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/SelfBow.java @@ -0,0 +1,447 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.alchemy.PotionContents; + +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.FULL_SCOPE; +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.HOTBAR_SCOPE; + +public class SelfBow extends Module { + public enum Swing { + Normal, + Packet, + Both, + None + } + + private enum ArrowType { + Speed, + Strength, + Done + } + + private static final String ROTATION_ID = "SelfBow"; + private static final int ROTATION_PRIORITY = 50; + private static final int FIRST_NON_HOTBAR_SLOT = 9; + + private final Setting inventory = bool("Inventory", true); + private final Setting itemDisable = bool("ItemDisable", true); + private final Setting drawTicks = num("DrawTicks", 20, 3, 40); + private final Setting restoreSlot = bool("RestoreSlot", true); + private final Setting swing = mode("Swing", Swing.Normal); + + private Result bowResult; + private int oldSlot = -1; + private int ticksDrawing = 0; + private int waitTicks = 0; + private boolean started = false; + private boolean shotSpeed = false; + private boolean shotStrength = false; + private ArrowType currentType = ArrowType.Speed; + + public SelfBow() { + super("SelfBow", "Literally just quiver module", Category.COMBAT); + } + + @Override + public void onEnable() { + bowResult = null; + oldSlot = InventoryUtil.selected(); + ticksDrawing = 0; + waitTicks = 0; + started = false; + shotSpeed = false; + shotStrength = false; + currentType = ArrowType.Speed; + + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + bowResult = InventoryUtil.find( + Items.BOW, + inventory.getValue() ? FULL_SCOPE : HOTBAR_SCOPE + ); + + if (bowResult == null || bowResult.type() == ResultType.NONE) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + if (!InventoryUtil.swap(bowResult)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + started = true; + } + + @Override + public void onDisable() { + releaseBowIfNeeded(); + + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager != null) { + rotationManager.endRotation(ROTATION_ID, ROTATION_PRIORITY); + } + + if (started && restoreSlot.getValue() && bowResult != null && oldSlot >= 0) { + InventoryUtil.swapBack(bowResult, oldSlot); + } + + bowResult = null; + oldSlot = -1; + ticksDrawing = 0; + waitTicks = 0; + started = false; + shotSpeed = false; + shotStrength = false; + currentType = ArrowType.Done; + } + + @Override + public void onTick() { + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + rotateStraightUp(); + + if (!isHoldingBow()) { + if (bowResult == null || !InventoryUtil.swap(bowResult)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + } + + if (waitTicks > 0) { + waitTicks--; + return; + } + + updateCurrentType(); + + if (currentType == ArrowType.Done) { + disable(); + return; + } + + if (!mc.player.isUsingItem()) { + if (!moveArrowToFirstInventorySlot(currentType)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + startUsingBow(); + ticksDrawing = 0; + return; + } + + ticksDrawing++; + + if (ticksDrawing >= Math.max(3, drawTicks.getValue())) { + releaseBow(); + doSwing(InteractionHand.MAIN_HAND); + + if (currentType == ArrowType.Speed) { + shotSpeed = true; + } else if (currentType == ArrowType.Strength) { + shotStrength = true; + } + + ticksDrawing = 0; + waitTicks = 2; + } + } + + private void updateCurrentType() { + if (!shotSpeed) { + currentType = ArrowType.Speed; + return; + } + + if (!shotStrength) { + currentType = ArrowType.Strength; + return; + } + + currentType = ArrowType.Done; + } + + private void rotateStraightUp() { + if (mc.player == null) { + return; + } + + float yaw = mc.player.getYRot(); + float pitch = -90.0f; + + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + mc.player.setXRot(pitch); + return; + } + + rotationManager.applyRotation( + ROTATION_ID, + ROTATION_PRIORITY, + yaw, + pitch + ); + } + + private boolean isHoldingBow() { + if (mc.player == null) { + return false; + } + + return mc.player.getMainHandItem().is(Items.BOW); + } + + private void startUsingBow() { + if (mc.player == null || mc.gameMode == null) { + return; + } + + mc.gameMode.useItem(mc.player, InteractionHand.MAIN_HAND); + } + + private void releaseBowIfNeeded() { + if (mc.player == null) { + return; + } + + if (!mc.player.isUsingItem()) { + return; + } + + if (mc.player.getUseItem().is(Items.BOW) || mc.player.getMainHandItem().is(Items.BOW)) { + releaseBow(); + return; + } + + mc.player.stopUsingItem(); + } + + private void releaseBow() { + if (mc.player == null) { + return; + } + + if (!mc.player.isUsingItem()) { + return; + } + + if (mc.gameMode != null) { + mc.gameMode.releaseUsingItem(mc.player); + } + + if (mc.player.isUsingItem() && mc.player.connection != null) { + mc.player.connection.send( + new ServerboundPlayerActionPacket( + ServerboundPlayerActionPacket.Action.RELEASE_USE_ITEM, + BlockPos.ZERO, + Direction.DOWN + ) + ); + + mc.player.stopUsingItem(); + } + } + + private boolean moveArrowToFirstInventorySlot(ArrowType type) { + if (mc.player == null || mc.gameMode == null) { + return false; + } + + ItemStack firstSlotStack = mc.player.getInventory().getItem(FIRST_NON_HOTBAR_SLOT); + + if (isArrowType(firstSlotStack, type)) { + return true; + } + + int arrowSlot = findArrowSlot(type); + + if (arrowSlot == -1) { + return false; + } + + if (arrowSlot == FIRST_NON_HOTBAR_SLOT) { + return true; + } + + swapInventorySlots(arrowSlot, FIRST_NON_HOTBAR_SLOT); + + ItemStack newFirstSlotStack = mc.player.getInventory().getItem(FIRST_NON_HOTBAR_SLOT); + + return isArrowType(newFirstSlotStack, type); + } + + private int findArrowSlot(ArrowType type) { + if (mc.player == null) { + return -1; + } + + for (int i = 0; i < 36; i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (isArrowType(stack, type)) { + return i; + } + } + + return -1; + } + + private boolean isArrowType(ItemStack stack, ArrowType type) { + if (stack == null || stack.isEmpty()) { + return false; + } + + if (!stack.is(Items.TIPPED_ARROW)) { + return false; + } + + PotionContents contents = stack.get(DataComponents.POTION_CONTENTS); + + if (contents == null) { + return false; + } + + return switch (type) { + case Speed -> hasEffect(contents, "speed"); + case Strength -> hasEffect(contents, "strength"); + case Done -> false; + }; + } + + private boolean hasEffect(PotionContents contents, String wantedEffect) { + for (MobEffectInstance effect : contents.getAllEffects()) { + String descriptionId = effect.getEffect().value().getDescriptionId(); + + if (descriptionId.equals("effect.minecraft." + wantedEffect)) { + return true; + } + } + + return false; + } + + private void swapInventorySlots(int fromInventorySlot, int toInventorySlot) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + int fromContainerSlot = toContainerSlot(fromInventorySlot); + int targetContainerSlot = toContainerSlot(toInventorySlot); + + if (fromContainerSlot == -1 || targetContainerSlot == -1) { + return; + } + + if (fromContainerSlot == targetContainerSlot) { + return; + } + + mc.gameMode.handleInventoryMouseClick( + mc.player.inventoryMenu.containerId, + fromContainerSlot, + 0, + ClickType.PICKUP, + mc.player + ); + + mc.gameMode.handleInventoryMouseClick( + mc.player.inventoryMenu.containerId, + targetContainerSlot, + 0, + ClickType.PICKUP, + mc.player + ); + + mc.gameMode.handleInventoryMouseClick( + mc.player.inventoryMenu.containerId, + fromContainerSlot, + 0, + ClickType.PICKUP, + mc.player + ); + } + + private int toContainerSlot(int inventorySlot) { + if (inventorySlot < 0 || inventorySlot > 35) { + return -1; + } + + if (inventorySlot < 9) { + return 36 + inventorySlot; + } + + return inventorySlot; + } + + private void doSwing(InteractionHand hand) { + if (mc.player == null) { + return; + } + + switch (swing.getValue()) { + case Normal -> mc.player.swing(hand); + case Packet -> { + if (mc.player.connection != null) { + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + } + case Both -> { + mc.player.swing(hand); + + if (mc.player.connection != null) { + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + } + case None -> { + } + } + } + + @Override + public String getDisplayInfo() { + if (currentType == ArrowType.Done) { + return "Done"; + } + + return currentType.name() + " " + drawTicks.getValue(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/SelfTrap.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/SelfTrap.java new file mode 100644 index 0000000..c2fec83 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/SelfTrap.java @@ -0,0 +1,544 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +public class SelfTrap extends Module { + public static SelfTrap INSTANCE; + + public enum SwitchMode { + Normal, + Silent, + None + } + + private static final String ROT_ID = "selftrap"; + private static final int ROT_PRIORITY = 3; + + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting airPlace = bool("AirPlace", false); + public final Setting shiftTicks = num("ShiftTicks", 4, 1, 10); + public final Setting await = bool("Await", false); + public final Setting strictDirection = bool("StrictDirection", false); + public final Setting selfDisable = bool("SelfDisable", false); + public final Setting itemDisable = bool("ItemDisable", false); + public final Setting placeRange = num("PlaceRange", 5.0f, 0.0f, 12.0f); + public final Setting multitask = bool("MultiTask", false); + public final Setting swing = bool("Swing", true); + public final Setting blocks = num("ShiftTicks", 4, 1, 6); + public final Setting delay = num("Delay", 2, 0, 20); + public final Setting head = bool("Head", true); + public final Setting face = bool("Face", false); + public final Setting feet = bool("Feet", false); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 60)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.5f, 4f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private Player target; + private List placements = new ArrayList<>(); + private double prevY; + private int ticks = 0; + private int blocksPlaced = 0; + private int invSwapSlot = -1; + + public SelfTrap() { + super("SelfTrap", "Traps yourself", Category.COMBAT); + INSTANCE = this; + } + + @Override + public void onEnable() { + if (mc.player == null) { + return; + } + + prevY = mc.player.getY(); + invSwapSlot = -1; + target = mc.player; + renderFadeState.reset(); + } + + @Override + public void onDisable() { + placements = new ArrayList<>(); + target = null; + invSwapSlot = -1; + ticks = 0; + blocksPlaced = 0; + renderFadeState.reset(); + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + if (mc.player == null || mc.level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && mc.player.isUsingItem()) { + return; + } + + target = mc.player; + + if (Math.abs(mc.player.getY() - prevY) > 0.5) { + disable(); + return; + } + + blocksPlaced = 0; + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + int slot = findResistantBlockSlot(); + + if (slot == -1) { + placements = new ArrayList<>(); + + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + placements = getSelfTrapPositions(); + + double placeRangeSq = placeRange.getValue() * placeRange.getValue(); + + List positions = placements.stream() + .filter(pos -> mc.player.distanceToSqr(Vec3.atCenterOf(pos)) <= placeRangeSq) + .filter(this::isPlaceable) + .toList(); + + if (positions.isEmpty()) { + if (selfDisable.getValue()) { + disable(); + } + + return; + } + + int oldSlot = mc.player.getInventory().getSelectedSlot(); + boolean switched = false; + int limit = Math.min(blocks.getValue(), shiftTicks.getValue()); + + List placed = new ArrayList<>(); + + for (BlockPos pos : positions) { + if (blocksPlaced >= limit) { + break; + } + + if (!switched) { + if (!doSwitch(slot, oldSlot)) { + break; + } + + switched = true; + } + + Direction dir = findPlaceDirection(pos, placed, strictDirection.getValue()); + + if (dir == null) { + BlockPos support = pos.below(); + Direction supportDir = findPlaceDirection(support, placed, strictDirection.getValue()); + + if (!isPlaceable(support) || supportDir == null) { + continue; + } + + if (applyRotations(Vec3.atCenterOf(support))) { + continue; + } + + if (placeBlock(support)) { + placed.add(support); + blocksPlaced++; + + if (blocksPlaced >= limit) { + break; + } + } else { + continue; + } + + if (await.getValue()) { + continue; + } + + dir = findPlaceDirection(pos, placed, strictDirection.getValue()); + + if (dir == null) { + continue; + } + } + + if (applyRotations(Vec3.atCenterOf(pos))) { + continue; + } + + if (placeBlock(pos)) { + placed.add(pos); + blocksPlaced++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + ticks = 0; + } + + private List getSelfTrapPositions() { + List list = new ArrayList<>(); + + if (mc.player == null) { + return list; + } + + BlockPos base = mc.player.blockPosition(); + + if (head.getValue()) { + list.add(base.above(2)); + } + + if (face.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + list.add(base.above().relative(dir)); + } + } + + if (feet.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + list.add(base.relative(dir)); + } + } + + return list; + } + + private Direction findPlaceDirection(BlockPos pos, List placed, boolean strictDir) { + if (mc.player == null || mc.level == null) { + return null; + } + + Direction best = null; + double bestDist = Double.MAX_VALUE; + Vec3 eye = mc.player.getEyePosition(); + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + + boolean solid = !mc.level.getBlockState(neighbor).canBeReplaced() + || placed.contains(neighbor); + + if (!solid) { + continue; + } + + if (strictDir) { + Vec3 faceCenter = Vec3.atCenterOf(neighbor) + .add(new Vec3(dir.getStepX(), dir.getStepY(), dir.getStepZ()).scale(0.5)); + + Vec3 toEye = eye.subtract(faceCenter).normalize(); + Vec3 faceNormal = new Vec3(dir.getStepX(), dir.getStepY(), dir.getStepZ()).normalize(); + + if (toEye.dot(faceNormal) <= 0.0) { + continue; + } + } + + double dist = eye.distanceTo(Vec3.atCenterOf(neighbor)); + + if (dist < bestDist) { + bestDist = dist; + best = dir; + } + } + + return best; + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return false; + } + + return !rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + if (mc.player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + mc.player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + mc.player.getInventory().setSelectedSlot(slot); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> mc.player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + if (mc.player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + mc.player.getInventory().setSelectedSlot(oldSlot); + mc.player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + mc.player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + mc.player + ); + } + + invSwapSlot = -1; + } + } + + private boolean placeBlock(BlockPos pos) { + if (mc.player == null || mc.level == null || mc.gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + mc.gameMode.useItemOn(mc.player, InteractionHand.MAIN_HAND, hitResult); + + if (swing.getValue()) { + mc.player.swing(InteractionHand.MAIN_HAND); + } + + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + if (mc.player == null || mc.level == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = mc.player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = mc.level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(mc.level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isPlaceable(BlockPos pos) { + if (mc.level == null) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + return airPlace.getValue() || buildHitResult(pos) != null; + } + + private int findResistantBlockSlot() { + if (mc.player == null) { + return -1; + } + + for (int i = 0; i < 9; i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (stack.getItem() instanceof BlockItem blockItem && isResistant(blockItem.getBlock())) { + return i; + } + } + + return -1; + } + + private boolean isResistant(Block block) { + return block == Blocks.OBSIDIAN + || block == Blocks.CRYING_OBSIDIAN + || block == Blocks.RESPAWN_ANCHOR + || block == Blocks.ENDER_CHEST + || block == Blocks.NETHERITE_BLOCK + || block == Blocks.ANCIENT_DEBRIS; + } + + private List getRenderablePositions() { + List renderable = new ArrayList<>(); + + for (BlockPos pos : placements) { + if (isPlaceable(pos)) { + renderable.add(pos); + } + } + + return renderable; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (mc.player == null || mc.level == null || !render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + getRenderablePositions(), + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Surround.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Surround.java new file mode 100644 index 0000000..a8163d4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/combat/Surround.java @@ -0,0 +1,541 @@ +package me.humanbeing.nolongerhuman.features.modules.combat; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +public class Surround extends Module { + + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + public enum CenterMode { + None, + Instant + } + + private static final String ROT_ID = "surround"; + private static final int ROT_PRIORITY = 500; + + public final Setting multitask = bool("MultiTask", true); + public final Setting switchMode = mode("Switch", SwitchMode.Silent); + public final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + public final Setting range = num("Range", 5.0f, 1.0f, 6.0f); + public final Setting blocksPerTick = num("ShiftTicks", 4, 1, 12); + public final Setting delay = num("Delay", 0, 0, 20); + public final Setting extend = bool("Extend", true); + public final Setting support = bool("Support", true); + public final Setting floor = bool("Floor", false); + public final Setting antiFacePlace = bool("AntiFacePlace", false); + public final Setting onlyOnGround = bool("OnlyGround", false); + public final Setting strict = bool("Strict", true); + public final Setting airPlace = bool("AirPlace", false); + public final Setting center = mode("Center", CenterMode.None); + + public final Setting render = bool("Render", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 70)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + public final Setting lineWidth = num("LineWidth", 1.0f, 0.1f, 4.0f); + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + private final Timer timer = new Timer(); + private final List renderPositions = new ArrayList<>(); + private final FadeRenderUtil.FadeState renderFadeState = new FadeRenderUtil.FadeState(); + + private int ticks = 0; + private int invSwapSlot = -1; + private BlockPos startPos = null; + + public Surround() { + super("Surround", "Reading the description? Gooooood boooooy!", Category.COMBAT); + } + + @Override + public void onEnable() { + if (mc.player != null) { + startPos = mc.player.blockPosition(); + + if (center.getValue() == CenterMode.Instant) { + centerPlayer(); + } + } + + ticks = delay.getValue(); + invSwapSlot = -1; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onDisable() { + clearRotations(); + ticks = 0; + invSwapSlot = -1; + startPos = null; + renderPositions.clear(); + renderFadeState.reset(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null || mc.gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + if (onlyOnGround.getValue() && !player.onGround()) { + return; + } + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + if (!timer.passedMs(1L)) { + return; + } + + List positions = getSurroundPositions(player); + + positions.removeIf(pos -> !isValidSpot(pos)); + positions.sort(Comparator.comparingDouble(pos -> player.distanceToSqr(Vec3.atCenterOf(pos)))); + + renderPositions.clear(); + renderPositions.addAll(positions); + + if (positions.isEmpty()) { + ticks = 0; + return; + } + + int slot = findBlockSlot(); + + if (slot == -1) { + ticks = 0; + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + boolean switched = false; + int placed = 0; + + for (BlockPos pos : positions) { + if (placed >= blocksPerTick.getValue()) { + break; + } + + if (!switched) { + if (!doSwitch(slot, oldSlot)) { + break; + } + + switched = true; + } + + if (!applyRotations(Vec3.atCenterOf(pos))) { + break; + } + + boolean success = place(pos); + + if (!success && support.getValue()) { + BlockPos supportPos = pos.below(); + + if (isValidSpot(supportPos)) { + if (applyRotations(Vec3.atCenterOf(supportPos)) && place(supportPos)) { + placed++; + + if (applyRotations(Vec3.atCenterOf(pos))) { + success = place(pos); + } + } + } + } + + if (success) { + placed++; + } + } + + if (switched) { + switchBack(oldSlot); + } + + resetSpoofIfNeeded(); + ticks = 0; + timer.reset(); + } + + private List getSurroundPositions(LocalPlayer player) { + Set positions = new LinkedHashSet<>(); + BlockPos base = player.blockPosition(); + + if (extend.getValue()) { + AABB bb = player.getBoundingBox(); + int minX = Mth.floor(bb.minX); + int maxX = Mth.floor(bb.maxX); + int minZ = Mth.floor(bb.minZ); + int maxZ = Mth.floor(bb.maxZ); + int y = base.getY(); + + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + BlockPos feet = new BlockPos(x, y, z); + + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(feet.relative(dir)); + } + + if (floor.getValue()) { + positions.add(feet.below()); + } + } + } + } else { + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.relative(dir)); + } + + if (floor.getValue()) { + positions.add(base.below()); + } + } + + if (antiFacePlace.getValue()) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + positions.add(base.relative(dir).above()); + } + } + + return new ArrayList<>(positions); + } + + private boolean place(BlockPos pos) { + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null) { + return false; + } + + BlockHitResult hitResult = buildHitResult(pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + player.swing(InteractionHand.MAIN_HAND); + return true; + } + + private BlockHitResult buildHitResult(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5, + side.getStepY() * 0.5, + side.getStepZ() * 0.5 + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isValidSpot(BlockPos pos) { + ClientLevel level = mc.level; + LocalPlayer player = mc.player; + + if (level == null || player == null) { + return false; + } + + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) > range.getValue() * range.getValue()) { + return false; + } + + if (!level.getEntitiesOfClass(Entity.class, new AABB(pos), entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return airPlace.getValue() || buildHitResult(pos) != null; + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + private boolean doSwitch(int slot, int currentHotbarSlot) { + LocalPlayer player = mc.player; + + if (player == null || mc.gameMode == null) { + return false; + } + + if (slot < 0 || slot > 35) { + return false; + } + + if (slot > 8) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + slot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = slot; + slot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(slot); + player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == slot; + }; + } + + private void switchBack(int oldSlot) { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + if (switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot != -1) { + if (mc.gameMode != null) { + mc.gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + } + + invSwapSlot = -1; + } + } + + private int findBlockSlot() { + LocalPlayer player = mc.player; + + if (player == null) { + return -1; + } + + int selected = player.getInventory().getSelectedSlot(); + + if (isSurroundBlock(player.getInventory().getItem(selected).getItem())) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (isSurroundBlock(player.getInventory().getItem(i).getItem())) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (isSurroundBlock(player.getInventory().getItem(i).getItem())) { + return i; + } + } + + return -1; + } + + private boolean isSurroundBlock(Item item) { + return item == Items.OBSIDIAN + || item == Items.CRYING_OBSIDIAN; + } + + private void centerPlayer() { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + BlockPos pos = player.blockPosition(); + double x = pos.getX() + 0.5; + double z = pos.getZ() + 0.5; + + player.setPos(x, player.getY(), z); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue()) { + renderFadeState.reset(); + return; + } + + PoseStack stack = event.getMatrix(); + + FadeRenderUtil.renderBlockPositions( + stack, + renderFadeState, + renderPositions, + fillColor.getValue(), + outlineColor.getValue(), + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue() + ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArmorHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArmorHudModule.java new file mode 100644 index 0000000..6a38650 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArmorHudModule.java @@ -0,0 +1,165 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.item.ItemStack; + +import java.awt.Color; + +public class ArmorHudModule extends HudModule { + + private static final EquipmentSlot[] ARMOR_ORDER = { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + + public final Setting percentIcon = bool("Percent", false); + public final Setting small = bool("Small", false); + public final Setting triColor = bool("TriColor", false); + + public final Setting armorColorA = color("HighColor", new Color(34, 255, 0, 255)); + public final Setting armorColorB = color("MiddleColor", new Color(255, 136, 0, 255)); + public final Setting armorColorC = color("LowColor", new Color(255, 0, 0, 255)); + + public final Setting autoPos = bool("AutoPos", true); + public final Setting shadow = bool("Shadow", true); + + @SuppressWarnings("unused") + public ArmorHudModule() { + super("ArmorHud", "Renders your armor on screen", 84, 28); + } + + @Override + protected void render(Render2DEvent event) { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + if (autoPos.getValue()) { + float x = (mc.getWindow().getGuiScaledWidth() / 2.0f - 42.0f) / mc.getWindow().getGuiScaledWidth(); + float y = (mc.getWindow().getGuiScaledHeight() - 55.0f) / mc.getWindow().getGuiScaledHeight(); + + pos.getValue().x = x; + pos.getValue().y = y; + } + + super.render(event); + + int baseX = (int) getX(); + int baseY = (int) getY(); + int index = 0; + + for (EquipmentSlot slot : ARMOR_ORDER) { + ItemStack stack = player.getItemBySlot(slot); + + if (stack.isEmpty()) { + index++; + continue; + } + + int itemX = baseX + index * 20; + + event.getContext().renderItem(stack, itemX, baseY); + event.getContext().renderItemDecorations(mc.font, stack, itemX, baseY); + + drawStackCount(event, stack, itemX, baseY); + drawDurability(event, stack, itemX, baseY); + + index++; + } + + setWidth(84.0f); + setHeight(28.0f); + } + + private void drawStackCount(Render2DEvent event, ItemStack stack, int itemX, int itemY) { + if (stack.getCount() <= 1) return; + + String count = String.valueOf(stack.getCount()); + int countX = itemX + 19 - mc.font.width(count); + + event.getContext().drawString( + mc.font, + count, + countX, + itemY + 9, + Color.WHITE.getRGB(), + shadow.getValue() + ); + } + + private void drawDurability(Render2DEvent event, ItemStack stack, int itemX, int itemY) { + if (!stack.isDamageableItem()) return; + if (stack.getMaxDamage() <= 0) return; + + int percent = getDurabilityPercent(stack); + String text = percent + (percentIcon.getValue() ? "%" : ""); + int color = getArmorColor(percent).getRGB(); + + int textX = itemX + 8 - mc.font.width(text) / 2; + int textY = small.getValue() ? itemY - 7 : itemY - 9; + + event.getContext().drawString( + mc.font, + text, + textX, + textY, + color, + shadow.getValue() + ); + } + + private int getDurabilityPercent(ItemStack stack) { + if (!stack.isDamageableItem() || stack.getMaxDamage() <= 0) { + return 100; + } + + float remaining = stack.getMaxDamage() - stack.getDamageValue(); + float max = stack.getMaxDamage(); + + return Math.max(0, Math.min(100, Math.round((remaining / max) * 100.0f))); + } + + public Color getArmorColor(int durability) { + if (!triColor.getValue()) { + return nolongerhuman.colorManager.getColor(); + } + + if (durability < 50) { + float factor = normalize(durability, 1.0f, 50.0f); + return interpolate(armorColorC.getValue(), armorColorB.getValue(), factor); + } + + float factor = normalize(durability, 50.0f, 100.0f); + return interpolate(armorColorB.getValue(), armorColorA.getValue(), factor); + } + + private float normalize(float value, float min, float max) { + if (max - min == 0.0f) { + return 0.0f; + } + + return Math.max(0.0f, Math.min(1.0f, (value - min) / (max - min))); + } + + private Color interpolate(Color from, Color to, float factor) { + factor = Math.max(0.0f, Math.min(1.0f, factor)); + + int r = (int) (from.getRed() + (to.getRed() - from.getRed()) * factor); + int g = (int) (from.getGreen() + (to.getGreen() - from.getGreen()) * factor); + int b = (int) (from.getBlue() + (to.getBlue() - from.getBlue()) * factor); + int a = (int) (from.getAlpha() + (to.getAlpha() - from.getAlpha()) * factor); + + return new Color(r, g, b, a); + } + + @Override + public String getDisplayInfo() { + return triColor.getValue() ? "Tri" : "Normal"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArmorWarnerHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArmorWarnerHudModule.java new file mode 100644 index 0000000..b5265ea --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArmorWarnerHudModule.java @@ -0,0 +1,100 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.item.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class ArmorWarnerHudModule extends HudModule { + + public final Setting autoPos = bool("AutoPos", true); + public final Setting armorThreshold = num("Threshold", 50, 1, 100); + public final Setting shadow = bool("Shadow", true); + + public ArmorWarnerHudModule() { + super("ArmorWarner", "Warns you when armor is low", 150, 40); + } + + @Override + protected void render(Render2DEvent event) { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + List warnings = getWarnings(player); + + if (autoPos.getValue()) { + pos.getValue().x = (mc.getWindow().getGuiScaledWidth() / 2.0f - 75.0f) / mc.getWindow().getGuiScaledWidth(); + pos.getValue().y = 0.12f; + } + + super.render(event); + + if (warnings.isEmpty()) { + setWidth(80); + setHeight(mc.font.lineHeight); + return; + } + + int x = (int) getX(); + int y = (int) getY(); + + int widest = 0; + int lineY = y; + + for (String warning : warnings) { + widest = Math.max(widest, mc.font.width(warning)); + + event.getContext().drawString( + mc.font, + warning, + x, + lineY, + nolongerhuman.colorManager.getColor().getRGB(), + shadow.getValue() + ); + + lineY += mc.font.lineHeight + 2; + } + + setWidth(widest); + setHeight(warnings.size() * (mc.font.lineHeight + 2)); + } + + private List getWarnings(LocalPlayer player) { + List warnings = new ArrayList<>(); + + addWarning(warnings, "helmet", player.getItemBySlot(EquipmentSlot.HEAD)); + addWarning(warnings, "chestplate", player.getItemBySlot(EquipmentSlot.CHEST)); + addWarning(warnings, "leggings", player.getItemBySlot(EquipmentSlot.LEGS)); + addWarning(warnings, "boots", player.getItemBySlot(EquipmentSlot.FEET)); + + return warnings; + } + + private void addWarning(List warnings, String name, ItemStack stack) { + if (stack == null || stack.isEmpty()) return; + if (!stack.isDamageableItem() || stack.getMaxDamage() <= 0) return; + + int durability = getDurabilityPercent(stack); + if (durability > armorThreshold.getValue()) return; + + String verb = name.equals("boots") || name.equals("leggings") ? "are" : "is"; + warnings.add("Your " + name + " " + verb + " at " + durability + "%!"); + } + + private int getDurabilityPercent(ItemStack stack) { + float remaining = stack.getMaxDamage() - stack.getDamageValue(); + return Math.max(0, Math.min(100, Math.round((remaining / stack.getMaxDamage()) * 100.0f))); + } + + @Override + public String getDisplayInfo() { + return armorThreshold.getValue() + "%"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArrayListHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArrayListHudModule.java new file mode 100644 index 0000000..63a4ac7 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/ArrayListHudModule.java @@ -0,0 +1,338 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.ChatFormatting; + +import java.awt.Color; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class ArrayListHudModule extends HudModule { + public enum Alignment { + Left, + Right + } + + public enum Sort { + Width, + Alphabetical, + None + } + + public final Setting alignment = mode("Alignment", Alignment.Right); + public final Setting sort = mode("Sort", Sort.Width); + public final Setting shadow = bool("Shadow", true); + public final Setting showHudModules = bool("ShowHudModules", false); + public final Setting showInfo = bool("ShowInfo", true); + public final Setting spacing = num("Spacing", 2, 0, 10); + public final Setting customColor = bool("CustomColor", false); + public final Setting color = color("Color", new Color(255, 255, 255, 255)); + + public ArrayListHudModule() { + super("ArrayList", "Displays active drawn modules", 120, 80); + } + + @Override + protected void render(Render2DEvent event) { + if (mc.player == null || mc.level == null) { + return; + } + + List entries = getEntries(); + + super.render(event); + + if (entries.isEmpty()) { + setWidth(80); + setHeight(mc.font.lineHeight); + return; + } + + sortEntries(entries); + + int widest = getWidest(entries); + int totalHeight = getTotalHeight(entries); + + setWidth(widest); + setHeight(totalHeight); + + int baseX = (int) getX(); + int safeLargestX = getSafeLargestX(baseX, widest); + int y = (int) getY(); + + for (ArrayEntry entry : entries) { + int drawX = getDrawX(baseX, safeLargestX, widest, entry.width()); + int drawColor = getTextColor(); + + event.getContext().drawString( + mc.font, + entry.text(), + drawX, + y, + drawColor, + shadow.getValue() + ); + + y += mc.font.lineHeight + spacing.getValue(); + } + } + + private int getSafeLargestX(int baseX, int widest) { + int screenWidth = mc.getWindow().getGuiScaledWidth(); + + if (widest >= screenWidth) { + return 0; + } + + if (baseX < 0) { + return 0; + } + + if (baseX + widest > screenWidth) { + return screenWidth - widest; + } + + return baseX; + } + + private int getDrawX(int baseX, int safeLargestX, int widest, int entryWidth) { + if (entryWidth == widest) { + return safeLargestX; + } + + if (alignment.getValue() == Alignment.Left) { + return baseX; + } + + return baseX + widest - entryWidth; + } + + private List getEntries() { + List entries = new ArrayList<>(); + + for (Module module : getModules()) { + if (!shouldDisplay(module)) { + continue; + } + + String text = getArrayText(module); + + if (text.isEmpty()) { + continue; + } + + entries.add(new ArrayEntry(text, mc.font.width(text))); + } + + return entries; + } + + private boolean shouldDisplay(Module module) { + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!module.isDrawn()) { + return false; + } + + if (module.hidden) { + return false; + } + + return showHudModules.getValue() || module.getCategory() != Module.Category.HUD; + } + + private String getArrayText(Module module) { + if (showInfo.getValue()) { + return module.getFullArrayString(); + } + + return module.getDisplayName(); + } + + private void sortEntries(List entries) { + switch (sort.getValue()) { + case Width -> entries.sort(Comparator.comparingInt(ArrayEntry::width).reversed()); + case Alphabetical -> entries.sort(Comparator.comparing(ArrayEntry::plainText, String.CASE_INSENSITIVE_ORDER)); + case None -> { + } + } + } + + private int getWidest(List entries) { + int widest = 0; + + for (ArrayEntry entry : entries) { + widest = Math.max(widest, entry.width()); + } + + return widest; + } + + private int getTotalHeight(List entries) { + if (entries.isEmpty()) { + return mc.font.lineHeight; + } + + return entries.size() * mc.font.lineHeight + + Math.max(0, entries.size() - 1) * spacing.getValue(); + } + + private int getTextColor() { + if (customColor.getValue()) { + return color.getValue().getRGB(); + } + + if (nolongerhuman.colorManager == null) { + return Color.WHITE.getRGB(); + } + + return nolongerhuman.colorManager.getColor().getRGB(); + } + + private List getModules() { + Object moduleManager = nolongerhuman.moduleManager; + + if (moduleManager == null) { + return List.of(); + } + + List modulesFromMethods = getModulesFromMethods(moduleManager); + + if (!modulesFromMethods.isEmpty()) { + return modulesFromMethods; + } + + return getModulesFromFields(moduleManager); + } + + private List getModulesFromMethods(Object moduleManager) { + for (Method method : moduleManager.getClass().getMethods()) { + if (method.getParameterCount() != 0) { + continue; + } + + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + + String name = method.getName().toLowerCase(); + + if (!isModuleListMethodName(name)) { + continue; + } + + try { + Object value = method.invoke(moduleManager); + List modules = convertToModuleList(value); + + if (!modules.isEmpty()) { + return modules; + } + } catch (ReflectiveOperationException ignored) { + } + } + + return List.of(); + } + + private boolean isModuleListMethodName(String name) { + return name.equals("getmodules") + || name.equals("modules") + || name.equals("getmodulelist") + || name.equals("getfeatures") + || name.equals("features"); + } + + private List getModulesFromFields(Object moduleManager) { + for (Class clazz = moduleManager.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(moduleManager); + List modules = convertToModuleList(value); + + if (!modules.isEmpty()) { + return modules; + } + } catch (IllegalAccessException ignored) { + } + } + } + + return List.of(); + } + + private List convertToModuleList(Object value) { + if (value == null) { + return List.of(); + } + + if (value instanceof Iterable iterable) { + return convertIterableToModuleList(iterable); + } + + if (value.getClass().isArray()) { + return convertArrayToModuleList(value); + } + + return List.of(); + } + + private List convertIterableToModuleList(Iterable iterable) { + List modules = new ArrayList<>(); + + for (Object object : iterable) { + if (object instanceof Module module) { + modules.add(module); + } + } + + return modules; + } + + private List convertArrayToModuleList(Object array) { + List modules = new ArrayList<>(); + + int length = java.lang.reflect.Array.getLength(array); + + for (int i = 0; i < length; i++) { + Object object = java.lang.reflect.Array.get(array, i); + + if (object instanceof Module module) { + modules.add(module); + } + } + + return modules; + } + + @Override + public String getDisplayInfo() { + return alignment.getValue().name(); + } + + private record ArrayEntry(String text, int width) { + private String plainText() { + return ChatFormatting.stripFormatting(text); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/CompassHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/CompassHudModule.java new file mode 100644 index 0000000..2fc19e1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/CompassHudModule.java @@ -0,0 +1,101 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; + +import java.awt.Color; + +public class CompassHudModule extends HudModule { + + private enum CompassDirection { + N, + W, + S, + E + } + + private static final double HALF_PI = Math.PI / 2.0; + + public final Setting autoPos = bool("AutoPos", true); + public final Setting scale = num("Scale", 16, 1, 60); + public final Setting shadow = bool("Shadow", true); + + @SuppressWarnings("unused") + public CompassHudModule() { + super("Compass", "Displays a directional compass", 64, 64); + } + + @Override + protected void render(Render2DEvent event) { + if (mc.player == null || mc.level == null) return; + + if (autoPos.getValue()) { + float centerX = mc.getWindow().getGuiScaledWidth() / 2.0f; + float centerY = mc.getWindow().getGuiScaledHeight() * 0.8f; + + pos.getValue().x = centerX / mc.getWindow().getGuiScaledWidth(); + pos.getValue().y = centerY / mc.getWindow().getGuiScaledHeight(); + } + + super.render(event); + + Entity cameraEntity = getCameraEntity(); + if (cameraEntity == null) return; + + float centerX = getX(); + float centerY = getY(); + + for (CompassDirection direction : CompassDirection.values()) { + double radians = getCompassRadians(cameraEntity, direction); + + float x = (float) (centerX + getXOffset(radians)); + float y = (float) (centerY + getYOffset(cameraEntity, radians)); + + int color = direction == CompassDirection.N + ? nolongerhuman.colorManager.getColor().getRGB() + : Color.WHITE.getRGB(); + + event.getContext().drawString( + mc.font, + direction.name(), + (int) x, + (int) y, + color, + shadow.getValue() + ); + } + + setWidth(scale.getValue() * 2.0f + 10.0f); + setHeight(scale.getValue() * 2.0f + 10.0f); + } + + private Entity getCameraEntity() { + Entity entity = mc.getCameraEntity(); + return entity != null ? entity : mc.player; + } + + private double getCompassRadians(Entity cameraEntity, CompassDirection direction) { + double yaw = Math.toRadians(Mth.wrapDegrees(cameraEntity.getYRot())); + return yaw + direction.ordinal() * HALF_PI; + } + + private double getXOffset(double radians) { + return Math.sin(radians) * scale.getValue(); + } + + private double getYOffset(Entity cameraEntity, double radians) { + double pitch = Mth.clamp(cameraEntity.getXRot() + 30.0f, -90.0f, 90.0f); + double pitchRadians = Math.toRadians(pitch); + + return Math.cos(radians) * Math.sin(pitchRadians) * scale.getValue(); + } + + @Override + public String getDisplayInfo() { + return String.valueOf(scale.getValue()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/CoordinatesHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/CoordinatesHudModule.java new file mode 100644 index 0000000..4f8e2b4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/CoordinatesHudModule.java @@ -0,0 +1,42 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; + +public class CoordinatesHudModule extends HudModule { + public Setting nether = bool("Nether", false); + + public CoordinatesHudModule() { + super("Coordinates", "Display coordinates", 150, 20); + } + + @Override + protected void render(Render2DEvent e) { + super.render(e); + + if (nullCheck()) return; + + String coordsStr = String.format("X: %d Y: %d Z: %d", + mc.player.getBlockX(), + mc.player.getBlockY(), + mc.player.getBlockZ()); + + if (nether.getValue()) { + int netherX = mc.player.level().dimension().identifier().getPath().equals("the_nether") + ? mc.player.getBlockX() * 8 + : mc.player.getBlockX() / 8; + int netherZ = mc.player.level().dimension().identifier().getPath().equals("the_nether") + ? mc.player.getBlockZ() * 8 + : mc.player.getBlockZ() / 8; + coordsStr += String.format(" [%d, %d]", netherX, netherZ); + } + + e.getContext().drawString(mc.font, coordsStr, + (int) getX(), (int) getY(), -1); + + setWidth(mc.font.width(coordsStr)); + setHeight(mc.font.lineHeight); + } +} + diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/HealthBarHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/HealthBarHudModule.java new file mode 100644 index 0000000..bca482e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/HealthBarHudModule.java @@ -0,0 +1,217 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.player.LocalPlayer; + +import java.awt.Color; +import java.text.DecimalFormat; + +public class HealthBarHudModule extends HudModule { + + public enum Mode { + Vanilla, + Bar, + None + } + + public enum BarColor { + Scissor, + Custom + } + + public final Setting mode = mode("Mode", Mode.Bar); + public final Setting barColor = mode("BarColor", BarColor.Scissor); + public final Setting barThickness = num("Thickness", 2.0f, 0.5f, 15.0f); + + public final Setting leftColor = color("LeftColor", new Color(255, 0, 255, 255)); + public final Setting rightColor = color("RightColor", new Color(0, 255, 0, 255)); + + public final Setting text = bool("Text", true); + public final Setting autoPos = bool("AutoPos", true); + public final Setting shadow = bool("Shadow", true); + + private final DecimalFormat format = new DecimalFormat("#.#"); + + public HealthBarHudModule() { + super("HealthBar", "Draws a health bar", 82, 16); + } + + @Override + protected void render(Render2DEvent event) { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + float width = 80.0f; + float height = getRenderHeight(); + + if (autoPos.getValue()) { + pos.getValue().x = ((mc.getWindow().getGuiScaledWidth() / 2.0f) - (width / 2.0f)) / mc.getWindow().getGuiScaledWidth(); + pos.getValue().y = (mc.getWindow().getGuiScaledHeight() - 70.0f) / mc.getWindow().getGuiScaledHeight(); + } + + super.render(event); + + switch (mode.getValue()) { + case Vanilla -> renderVanilla(event, player); + case Bar -> renderBar(event, player); + case None -> { + if (text.getValue()) { + renderHealthText(event, player, getX(), getY()); + } + } + } + + setWidth(width + 2.0f); + setHeight(height); + } + + private void renderVanilla(Render2DEvent event, LocalPlayer player) { + float x = getX(); + float y = getY(); + + float hearts = getHealthHearts(player); + float absorption = player.getAbsorptionAmount() / 2.0f; + + String healthString = "❤ " + format.format(hearts); + + if (absorption > 0.0f) { + healthString += " +" + format.format(absorption); + } + + event.getContext().drawString( + mc.font, + healthString, + (int) x, + (int) y, + getHealthColor(player).getRGB(), + shadow.getValue() + ); + + if (text.getValue()) { + String detailed = getHealthText(player); + event.getContext().drawString( + mc.font, + detailed, + (int) x, + (int) (y + mc.font.lineHeight + 2), + -1, + shadow.getValue() + ); + } + } + + private void renderBar(Render2DEvent event, LocalPlayer player) { + float x = getX(); + float y = getY(); + + float width = 80.0f; + float thickness = barThickness.getValue(); + + float maxHealth = Math.max(1.0f, player.getMaxHealth()); + float health = Math.max(0.0f, Math.min(player.getHealth(), maxHealth)); + float percent = health / maxHealth; + + Color healthColor = getHealthColor(player); + + int background = new Color(0, 0, 0, 120).getRGB(); + + RenderUtil.rect( + event.getContext(), + x - 0.5f, + y - 0.5f, + x + width + 0.5f, + y + thickness + 0.5f, + background, + 1.0f + ); + + Color start = barColor.getValue() == BarColor.Scissor ? Color.RED : leftColor.getValue(); + Color end = barColor.getValue() == BarColor.Scissor ? healthColor : rightColor.getValue(); + + int segments = Math.max(1, (int) (width * percent)); + + for (int i = 0; i < segments; i++) { + float segmentPercent = i / width; + Color color = interpolate(start, end, segmentPercent); + + RenderUtil.rect( + event.getContext(), + x + i, + y, + x + i + 1.0f, + y + thickness, + color.getRGB(), + 1.0f + ); + } + + if (text.getValue()) { + renderHealthText(event, player, x + width / 2.0f, y + thickness + 4.0f); + } + } + + private void renderHealthText(Render2DEvent event, LocalPlayer player, float x, float y) { + String healthText = getHealthText(player); + int textWidth = mc.font.width(healthText); + + event.getContext().drawString( + mc.font, + healthText, + (int) (x - textWidth / 2.0f), + (int) y, + getHealthColor(player).getRGB(), + shadow.getValue() + ); + } + + private String getHealthText(LocalPlayer player) { + float hearts = getHealthHearts(player); + float absorption = player.getAbsorptionAmount() / 2.0f; + + String result = format.format(hearts); + + if (absorption > 0.0f) { + result += " +" + format.format(absorption); + } + + return result; + } + + private float getHealthHearts(LocalPlayer player) { + return player.getHealth() <= 0.0f ? 0.0f : player.getHealth() / 2.0f; + } + + private Color getHealthColor(LocalPlayer player) { + float max = Math.max(1.0f, player.getMaxHealth()); + float ratio = Math.max(0.0f, Math.min(player.getHealth(), max) / max); + + return new Color(Color.HSBtoRGB(ratio / 3.0f, 1.0f, 1.0f) | 0xFF000000, true); + } + + private Color interpolate(Color from, Color to, float factor) { + factor = Math.max(0.0f, Math.min(1.0f, factor)); + + int r = (int) (from.getRed() + (to.getRed() - from.getRed()) * factor); + int g = (int) (from.getGreen() + (to.getGreen() - from.getGreen()) * factor); + int b = (int) (from.getBlue() + (to.getBlue() - from.getBlue()) * factor); + int a = (int) (from.getAlpha() + (to.getAlpha() - from.getAlpha()) * factor); + + return new Color(r, g, b, a); + } + + private float getRenderHeight() { + return switch (mode.getValue()) { + case Vanilla -> text.getValue() ? mc.font.lineHeight * 2.0f + 4.0f : mc.font.lineHeight; + case Bar -> barThickness.getValue() + (text.getValue() ? mc.font.lineHeight + 6.0f : 2.0f); + case None -> text.getValue() ? mc.font.lineHeight : 2.0f; + }; + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/HeldItemHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/HeldItemHudModule.java new file mode 100644 index 0000000..508cc7c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/HeldItemHudModule.java @@ -0,0 +1,353 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.item.ItemStack; + +import java.awt.Color; + +public class HeldItemHudModule extends HudModule { + public final Setting autoPos = bool("AutoPos", true); + public final Setting scale = num("Scale", 1.0f, 0.25f, 3.0f); + public final Setting shadow = bool("Shadow", true); + public final Setting background = bool("Background", true); + public final Setting mainHand = bool("MainHand", true); + + public final Setting backgroundColor = color("BackgroundColor", new Color(20, 20, 30, 165)); + public final Setting shadowColor = color("ShadowColor", new Color(0, 0, 0, 90)); + public final Setting labelColor = color("LabelColor", new Color(235, 235, 245, 255)); + public final Setting highColor = color("HighColor", new Color(65, 255, 145, 255)); + public final Setting midColor = color("MiddleColor", new Color(255, 170, 55, 255)); + public final Setting lowColor = color("LowColor", new Color(255, 75, 75, 255)); + + public final Setting radius = num("Radius", 5, 0, 12); + public final Setting padding = num("Padding", 5, 2, 12); + public final Setting gap = num("Gap", 5, 1, 12); + + public HeldItemHudModule() { + super("HeldItemHud", "Shows your held item and stack amount on the HUD", 92, 24); + } + + @Override + protected void render(Render2DEvent event) { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + ItemStack stack = mainHand.getValue() + ? player.getMainHandItem() + : player.getOffhandItem(); + + boolean hudEditorOpen = isHudEditorOpen(); + + if (stack.isEmpty()) { + if (mc.screen instanceof ChatScreen) { + return; + } + + if (!hudEditorOpen) { + return; + } + } + + String label = "Amount: "; + String amount = stack.isEmpty() ? "0" : String.valueOf(stack.getCount()); + + int pad = padding.getValue(); + int itemSize = 16; + int textGap = gap.getValue(); + + int labelWidth = mc.font.width(label); + int amountWidth = mc.font.width(amount); + + float hudScale = getSafeScale(); + + float baseWidth = pad + itemSize + textGap + labelWidth + amountWidth + pad; + float baseHeight = Math.max(itemSize + pad * 2.0f, mc.font.lineHeight + pad * 2.0f); + + float scaledWidth = baseWidth * hudScale; + float scaledHeight = baseHeight * hudScale; + + setWidth(scaledWidth); + setHeight(scaledHeight); + + if (autoPos.getValue() && !hudEditorOpen) { + float x = (mc.getWindow().getGuiScaledWidth() / 2.0f - scaledWidth / 2.0f) + / mc.getWindow().getGuiScaledWidth(); + float y = (mc.getWindow().getGuiScaledHeight() - 72.0f) + / mc.getWindow().getGuiScaledHeight(); + + pos.getValue().x = x; + pos.getValue().y = y; + } + + super.render(event); + + if (stack.isEmpty()) { + return; + } + + float x = getX(); + float y = getY(); + + event.getContext().pose().pushMatrix(); + + try { + event.getContext().pose().translate(x, y); + event.getContext().pose().scale(hudScale, hudScale); + + if (background.getValue()) { + int safeRadius = getSafeRadius(baseWidth, baseHeight); + + + + drawOutsideOnlyRoundedShadow( + event, + 1.5f, + 1.5f, + baseWidth, + baseHeight, + safeRadius, + shadowColor.getValue().getRGB(), + 0.0f, + 0.0f, + baseWidth, + baseHeight + ); + + drawRoundedRectNoOverlap( + event, + 0.0f, + 0.0f, + baseWidth, + baseHeight, + safeRadius, + backgroundColor.getValue().getRGB() + ); + } + + int itemX = pad; + int itemY = Math.round(baseHeight / 2.0f - itemSize / 2.0f); + + event.getContext().renderItem(stack, itemX, itemY); + + int textX = pad + itemSize + textGap; + int textY = Math.round(baseHeight / 2.0f - mc.font.lineHeight / 2.0f + 1.0f); + + event.getContext().drawString( + mc.font, + label, + textX, + textY, + labelColor.getValue().getRGB(), + shadow.getValue() + ); + + event.getContext().drawString( + mc.font, + amount, + textX + labelWidth, + textY, + getAmountColor(stack).getRGB(), + shadow.getValue() + ); + } finally { + event.getContext().pose().popMatrix(); + } + } + + private void drawRoundedRectNoOverlap( + Render2DEvent event, + float x, + float y, + float width, + float height, + int radius, + int color + ) { + if (width <= 0.0f || height <= 0.0f) { + return; + } + + int alpha = color >>> 24; + + if (alpha <= 0) { + return; + } + + int startY = (int) Math.floor(y); + int endY = (int) Math.ceil(y + height); + + radius = Math.max(0, Math.min(radius, (int) Math.floor(Math.min(width, height) / 2.0f))); + + for (int row = startY; row < endY; row++) { + double localY = row + 0.5D - y; + + if (localY < 0.0D || localY > height) { + continue; + } + + double inset = getRoundedInset(localY, height, radius); + + float left = x + (float) inset; + float right = x + width - (float) inset; + + fillRect(event, left, row, right, row + 1.0f, color); + } + } + + private void drawOutsideOnlyRoundedShadow( + Render2DEvent event, + float x, + float y, + float width, + float height, + int radius, + int color, + float cutX, + float cutY, + float cutWidth, + float cutHeight + ) { + if (width <= 0.0f || height <= 0.0f) { + return; + } + + int alpha = color >>> 24; + + if (alpha <= 0) { + return; + } + + int startY = (int) Math.floor(y); + int endY = (int) Math.ceil(y + height); + + float cutRight = cutX + cutWidth; + float cutBottom = cutY + cutHeight; + + radius = Math.max(0, Math.min(radius, (int) Math.floor(Math.min(width, height) / 2.0f))); + + for (int row = startY; row < endY; row++) { + double localY = row + 0.5D - y; + + if (localY < 0.0D || localY > height) { + continue; + } + + double inset = getRoundedInset(localY, height, radius); + + float left = x + (float) inset; + float right = x + width - (float) inset; + + boolean rowInsideCut = row + 1.0f > cutY && row < cutBottom; + + if (!rowInsideCut) { + fillRect(event, left, row, right, row + 1.0f, color); + continue; + } + + + fillRect(event, left, row, Math.min(right, cutX), row + 1.0f, color); + fillRect(event, Math.max(left, cutRight), row, right, row + 1.0f, color); + } + } + + private double getRoundedInset(double localY, double height, int radius) { + if (radius <= 0) { + return 0.0D; + } + + double topRadius = radius; + double bottomRadiusStart = height - radius; + + if (localY < topRadius) { + double dy = topRadius - localY; + return radius - Math.sqrt(Math.max(0.0D, radius * radius - dy * dy)); + } + + if (localY > bottomRadiusStart) { + double dy = localY - bottomRadiusStart; + return radius - Math.sqrt(Math.max(0.0D, radius * radius - dy * dy)); + } + + return 0.0D; + } + + private void fillRect( + Render2DEvent event, + float x1, + float y1, + float x2, + float y2, + int color + ) { + int left = (int) Math.floor(x1); + int top = (int) Math.floor(y1); + int right = (int) Math.ceil(x2); + int bottom = (int) Math.ceil(y2); + + if (right <= left || bottom <= top) { + return; + } + + event.getContext().fill(left, top, right, bottom, color); + } + + private int getSafeRadius(float width, float height) { + int value = radius.getValue(); + + if (value <= 0) { + return 0; + } + + int max = (int) Math.floor(Math.min(width, height) / 2.0f); + + return Math.max(0, Math.min(value, max)); + } + + private float getSafeScale() { + float value = scale.getValue(); + + if (Float.isNaN(value) || Float.isInfinite(value)) { + return 1.0f; + } + + return Math.max(0.05f, value); + } + + private boolean isHudEditorOpen() { + return mc.screen != null + && mc.screen.getClass().getSimpleName().equals("HudEditorScreen"); + } + + private Color getAmountColor(ItemStack stack) { + int count = stack.getCount(); + int max = stack.getMaxStackSize(); + + if (max <= 0) { + return lowColor.getValue(); + } + + float fullness = count / (float) max; + + if (fullness > 0.75f) { + return highColor.getValue(); + } + + if (fullness >= 0.25f) { + return midColor.getValue(); + } + + return lowColor.getValue(); + } + + @Override + public String getDisplayInfo() { + return mainHand.getValue() ? "Main" : "Offhand"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/InfoHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/InfoHudModule.java new file mode 100644 index 0000000..1e8bba9 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/InfoHudModule.java @@ -0,0 +1,264 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.item.ItemStack; + +import java.awt.Color; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class InfoHudModule extends HudModule { + public final Setting speed = bool("Speed", true); + public final Setting fps = bool("FPS", true); + + public final Setting ping = bool("Ping", true); + public final Setting serverIp = bool("ServerIP", true); + + public final Setting durability = bool("Durability", true); + public final Setting durabilityPercent = bool("DuraPercent", true); + public final Setting systemTime = bool("SystemTime", true); + public final Setting worldTime = bool("WorldTime", true); + + public final Setting shadow = bool("Shadow", true); + public final Setting color = color("Color", new Color(255, 255, 255, 255)); + + private final DecimalFormat speedFormat = new DecimalFormat("0.00"); + private final SimpleDateFormat systemTimeFormat = new SimpleDateFormat("h:mm a"); + + public InfoHudModule() { + super("Info", "Shows speed, FPS, server, durability, and time info", 130, 90); + } + + @Override + protected void render(Render2DEvent event) { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + super.render(event); + + int x = (int) getX(); + int y = (int) getY(); + int lineHeight = mc.font.lineHeight + 2; + int offset = 0; + int widest = 0; + + if (speed.getValue()) { + String text = "Speed " + getSpeed(player) + " km/h"; + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + color.getValue().getRGB(), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + if (fps.getValue()) { + String text = "FPS " + Minecraft.getInstance().getFps(); + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + color.getValue().getRGB(), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + if (ping.getValue()) { + String text = "Ping " + getPing(player) + "ms"; + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + color.getValue().getRGB(), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + if (serverIp.getValue()) { + String text = "IP " + getServerIp(); + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + color.getValue().getRGB(), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + if (durability.getValue()) { + String text = "Durability " + getDurability(player); + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + getDurabilityColor(player), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + if (systemTime.getValue()) { + String text = "Time " + systemTimeFormat.format(new Date()); + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + color.getValue().getRGB(), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + if (worldTime.getValue()) { + String text = "WorldTime " + getWorldTime(); + + event.getContext().drawString( + mc.font, + text, + x, + y + offset, + color.getValue().getRGB(), + shadow.getValue() + ); + + widest = Math.max(widest, mc.font.width(text)); + offset += lineHeight; + } + + setWidth(Math.max(1, widest)); + setHeight(Math.max(mc.font.lineHeight, offset)); + } + + private String getSpeed(LocalPlayer player) { + double x = player.getX() - player.xOld; + double z = player.getZ() - player.zOld; + double blocksPerSecond = Math.sqrt(x * x + z * z) * 20.0D; + double kilometersPerHour = blocksPerSecond * 3.6D; + + return speedFormat.format(kilometersPerHour); + } + + private int getPing(LocalPlayer player) { + if (mc.getConnection() == null) { + return 0; + } + + PlayerInfo info = mc.getConnection().getPlayerInfo(player.getUUID()); + + return info == null ? 0 : info.getLatency(); + } + + private String getServerIp() { + if (mc.isLocalServer()) { + return "Singleplayer"; + } + + if (mc.getCurrentServer() == null) { + return "Unknown"; + } + + return mc.getCurrentServer().ip; + } + + private String getDurability(LocalPlayer player) { + ItemStack stack = player.getMainHandItem(); + + if (stack.isEmpty() || !stack.isDamageableItem() || stack.getMaxDamage() <= 0) { + return "N/A"; + } + + int remaining = stack.getMaxDamage() - stack.getDamageValue(); + + if (!durabilityPercent.getValue()) { + return String.valueOf(remaining); + } + + int percent = Math.round((remaining / (float) stack.getMaxDamage()) * 100.0F); + + return percent + "%"; + } + + private int getDurabilityColor(LocalPlayer player) { + ItemStack stack = player.getMainHandItem(); + + if (stack.isEmpty() || !stack.isDamageableItem() || stack.getMaxDamage() <= 0) { + return color.getValue().getRGB(); + } + + int remaining = stack.getMaxDamage() - stack.getDamageValue(); + float percent = (remaining / (float) stack.getMaxDamage()) * 100.0F; + + if (percent <= 10.0F) { + return new Color(170, 0, 0).getRGB(); + } + + if (percent <= 25.0F) { + return Color.RED.getRGB(); + } + + if (percent <= 50.0F) { + return Color.ORANGE.getRGB(); + } + + if (percent <= 75.0F) { + return Color.YELLOW.getRGB(); + } + + return Color.GREEN.getRGB(); + } + + private String getWorldTime() { + if (mc.level == null) { + return "0"; + } + + long time = mc.level.getDayTime() % 24000L; + long hours = (time / 1000L + 6L) % 24L; + long minutes = (time % 1000L) * 60L / 1000L; + + return String.format("%02d:%02d", hours, minutes); + } + + @Override + public String getDisplayInfo() { + return "Info"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/SafetyHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/SafetyHudModule.java new file mode 100644 index 0000000..ac50b43 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/SafetyHudModule.java @@ -0,0 +1,137 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.modules.render.HoleESP; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.HoleManager; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; + +import java.awt.Color; + +public class SafetyHudModule extends HudModule { + + public final Setting shadow = bool("Shadow", true); + public final Setting partialSafe = bool("PartialSafe", true); + + public SafetyHudModule() { + super("Safety", "Shows whether you are in a hole", 45, 10); + } + + @Override + protected void render(Render2DEvent event) { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null || nolongerhuman.holeManager == null) { + return; + } + + super.render(event); + + SafetyResult result = getSafety(player); + String text = result.safe() ? "SAFE" : "UNSAFE"; + Color color = result.color(); + + event.getContext().drawString( + mc.font, + text, + (int) getX(), + (int) getY(), + color.getRGB(), + shadow.getValue() + ); + + setWidth(mc.font.width(text)); + setHeight(mc.font.lineHeight); + } + + private SafetyResult getSafety(LocalPlayer player) { + HoleESP holeESP = getHoleESP(); + BlockPos pos = player.blockPosition(); + + HoleManager.Hole normalHole = nolongerhuman.holeManager.getHole(pos); + + if (normalHole != null) { + return switch (normalHole.holeType()) { + case BEDROCK -> new SafetyResult(true, getBedrockColor(holeESP)); + case UNSAFE -> new SafetyResult(true, getUnsafeColor(holeESP)); + case MIXED -> new SafetyResult(true, getMixedColor(holeESP)); + case PARTIAL -> new SafetyResult(partialSafe.getValue(), getPartialColor(holeESP)); + }; + } + + HoleManager.Hole partialHole = nolongerhuman.holeManager.getPartialHole(pos); + + if (partialHole != null) { + return new SafetyResult(partialSafe.getValue(), getPartialColor(holeESP)); + } + + return new SafetyResult(false, getUnsafeColor(holeESP)); + } + + private HoleESP getHoleESP() { + if (nolongerhuman.moduleManager == null) { + return null; + } + + Module module = nolongerhuman.moduleManager.getModuleByClass(HoleESP.class); + + if (module instanceof HoleESP holeESP) { + return holeESP; + } + + return null; + } + + private Color getBedrockColor(HoleESP holeESP) { + if (holeESP == null) { + return new Color(0, 255, 0, 255); + } + + return opaque(holeESP.bedrockColor.getValue()); + } + + private Color getUnsafeColor(HoleESP holeESP) { + if (holeESP == null) { + return new Color(255, 0, 0, 255); + } + + return opaque(holeESP.unsafeColor.getValue()); + } + + private Color getMixedColor(HoleESP holeESP) { + if (holeESP == null) { + return new Color(255, 165, 0, 255); + } + + return opaque(holeESP.mixedColor.getValue()); + } + + private Color getPartialColor(HoleESP holeESP) { + if (holeESP == null) { + return new Color(255, 255, 255, 255); + } + + return opaque(holeESP.partialColor.getValue()); + } + + private Color opaque(Color color) { + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + 255 + ); + } + + @Override + public String getDisplayInfo() { + return "Hole"; + } + + private record SafetyResult(boolean safe, Color color) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/WatermarkHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/WatermarkHudModule.java new file mode 100644 index 0000000..0c028db --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/WatermarkHudModule.java @@ -0,0 +1,118 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.chinaware.util.BuildConfig; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +public class WatermarkHudModule extends HudModule { + public final Setting name = bool("Name", true); + public final Setting version = bool("Version", true); + public final Setting hash = bool("Hash", true); + public final Setting buildTime = bool("BuildTime", true); + + public final Setting wave = bool("Wave", false); + public final Setting white = bool("White", false); + public final Setting autoPos = bool("AutoPos", true); + public final Setting shadow = bool("Shadow", true); + + public WatermarkHudModule() { + super("Watermark", "Displays the client watermark", 100, 10); + } + + @Override + protected void render(Render2DEvent event) { + if (autoPos.getValue()) { + pos.getValue().x = 1.0f / mc.getWindow().getGuiScaledWidth(); + pos.getValue().y = 1.0f / mc.getWindow().getGuiScaledHeight(); + } + + super.render(event); + + String watermark = getClientName(); + + float x = getX(); + float y = getY(); + + if (wave.getValue()) { + drawWaveText(event, watermark, x, y); + } else { + int color = white.getValue() + ? Color.WHITE.getRGB() + : nolongerhuman.colorManager.getColor().getRGB(); + + event.getContext().drawString( + mc.font, + watermark, + (int) x, + (int) y, + color, + shadow.getValue() + ); + } + + setWidth(mc.font.width(watermark)); + setHeight(mc.font.lineHeight); + } + + private void drawWaveText(Render2DEvent event, String string, float x, float y) { + float offset = 0.0f; + + for (int i = 0; i < string.length(); i++) { + String character = String.valueOf(string.charAt(i)); + + float hue = ((System.currentTimeMillis() % 4000L) / 4000.0f + i * 0.055f) % 1.0f; + + int color = white.getValue() + ? Color.WHITE.getRGB() + : Color.HSBtoRGB(hue, 0.8f, 1.0f); + + event.getContext().drawString( + mc.font, + character, + (int) (x + offset), + (int) y, + color, + shadow.getValue() + ); + + offset += mc.font.width(character); + } + } + + public String getClientName() { + List parts = new ArrayList<>(); + + if (name.getValue()) { + parts.add(BuildConfig.NAME); + } + + if (version.getValue()) { + parts.add(BuildConfig.VERSION); + } + + if (hash.getValue()) { + parts.add(BuildConfig.HASH); + } + + if (buildTime.getValue()) { + parts.add(BuildConfig.BUILD_TIME); + } + + if (parts.isEmpty()) { + return BuildConfig.NAME; + } + + return String.join(" - ", parts); + } + + @Override + public String getDisplayInfo() { + return getClientName(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/WelcomerHudModule.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/WelcomerHudModule.java new file mode 100644 index 0000000..b846e5e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/hud/WelcomerHudModule.java @@ -0,0 +1,127 @@ +package me.humanbeing.nolongerhuman.features.modules.hud; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.client.HudModule; +import me.humanbeing.nolongerhuman.features.settings.Setting; + +import java.awt.Color; +import java.time.ZonedDateTime; + +public class WelcomerHudModule extends HudModule { + + public enum Mode { + Extra, + NoExtra, + NoLongerHuman, + Only, + } + + public final Setting autoPos = bool("AutoPos", true); + public final Setting mode = mode("Mode", Mode.Extra); + public final Setting wheelChair = bool("WheelChair", false); + public final Setting wave = bool("Wave", false); + public final Setting whiteName = bool("WhiteName", false); + public final Setting shadow = bool("Shadow", true); + + public WelcomerHudModule() { + super("Welcomer", "Welcomes you on the HUD", 160, 10); + } + + @Override + protected void render(Render2DEvent event) { + if (mc.player == null || mc.level == null) { + return; + } + + String text = getWelcomeString(); + + if (autoPos.getValue()) { + float x = (mc.getWindow().getGuiScaledWidth() / 2.0f - mc.font.width(text) / 2.0f) + / mc.getWindow().getGuiScaledWidth(); + float y = 1.0f / mc.getWindow().getGuiScaledHeight(); + + pos.getValue().x = x; + pos.getValue().y = y; + } + + super.render(event); + + if (wave.getValue()) { + drawWaveText(event, text, getX(), getY()); + } else { + int color = whiteName.getValue() + ? Color.WHITE.getRGB() + : nolongerhuman.colorManager.getColor().getRGB(); + + event.getContext().drawString( + mc.font, + text, + (int) getX(), + (int) getY(), + color, + shadow.getValue() + ); + } + + setWidth(mc.font.width(text)); + setHeight(mc.font.lineHeight); + } + + private String getWelcomeString() { + String name = mc.player == null ? "Player" : mc.player.getName().getString(); + + ZonedDateTime time = ZonedDateTime.now(); + int hour = time.getHour(); + + String timer; + + if (hour <= 11) { + timer = "Good Morning "; + } else if (hour <= 18) { + timer = "Good Afternoon "; + } else { + timer = "Good Evening "; + } + + String text = switch (mode.getValue()) { + case NoLongerHuman -> "We Are NoLongerHuman " + name; + case Extra -> timer + name + " >:^)"; + case NoExtra -> timer + name; + case Only -> "Welcome, " + name; + }; + + if (wheelChair.getValue()) { + text += " ♿"; + } + + return text; + } + + private void drawWaveText(Render2DEvent event, String text, float x, float y) { + float offset = 0.0f; + + for (int i = 0; i < text.length(); i++) { + String character = String.valueOf(text.charAt(i)); + float hue = ((System.currentTimeMillis() % 4000L) / 4000.0f + i * 0.055f) % 1.0f; + + int color = Color.HSBtoRGB(hue, 0.8f, 1.0f); + + event.getContext().drawString( + mc.font, + character, + (int) (x + offset), + (int) y, + color, + shadow.getValue() + ); + + offset += mc.font.width(character); + } + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Accelerate.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Accelerate.java new file mode 100644 index 0000000..5d5a03a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Accelerate.java @@ -0,0 +1,195 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.Vec3; + +public class Accelerate extends Module { + + private final Setting air = bool("Air", true); + private final Setting speedInWater = bool("SpeedInWater", false); + private final Setting instantStop = bool("InstantStop", true); + private final Setting stopInAir = bool("StopInAir", true); + private final Setting stopInWater = bool("StopInWater", false); + + private final Setting groundSpeed = num("GroundSpeed", 0.2, 0.05, 0.5); + private final Setting airSpeed = num("AirSpeed", 0.2, 0.05, 0.5); + private final Setting waterSpeed = num("WaterSpeed", 0.1, 0.05, 0.5); + + public Accelerate() { + super("Accelerate", "Gives you more precise instant movement", Category.MOVEMENT); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + if (isMovementControlBlocked(player, level)) { + return; + } + + if (shouldInstantStop(player)) { + stopHorizontalMovement(player); + return; + } + + if (!hasMovementInput(player)) { + return; + } + + Vec3 movement = forward(player, moveSpeed(player)); + Vec3 current = player.getDeltaMovement(); + + player.setDeltaMovement( + movement.x, + current.y, + movement.z + ); + } + + private boolean isMovementControlBlocked(LocalPlayer player, ClientLevel level) { + if (player.fallDistance >= 5.0F) { + return true; + } + + if (player.isShiftKeyDown()) { + return true; + } + + if (player.onClimbable()) { + return true; + } + + if (level.getBlockState(player.blockPosition()).getBlock() == Blocks.COBWEB) { + return true; + } + + if (player.getAbilities().flying) { + return true; + } + + if (player.isFallFlying()) { + return true; + } + + if (!player.onGround() && !air.getValue()) { + return true; + } + + return (player.isInWater() || player.isInLava()) && !speedInWater.getValue(); + } + + private boolean shouldInstantStop(LocalPlayer player) { + if (!instantStop.getValue()) { + return false; + } + + if (hasMovementInput(player)) { + return false; + } + + if (!player.onGround() && !stopInAir.getValue()) { + return false; + } + + if ((player.isInWater() || player.isInLava()) && !stopInWater.getValue()) { + return false; + } + + return true; + } + + private boolean hasMovementInput(LocalPlayer player) { + return Math.abs(player.zza) > 0.0001F || Math.abs(player.xxa) > 0.0001F; + } + + private void stopHorizontalMovement(LocalPlayer player) { + Vec3 velocity = player.getDeltaMovement(); + + if (Math.abs(velocity.x) <= 0.00001 && Math.abs(velocity.z) <= 0.00001) { + return; + } + + player.setDeltaMovement( + 0.0, + velocity.y, + 0.0 + ); + } + + private Vec3 forward(LocalPlayer player, double speed) { + float forward = player.zza; + float strafe = player.xxa; + + if (forward == 0.0F && strafe == 0.0F) { + return Vec3.ZERO; + } + + float yaw = player.getYRot(); + + if (forward != 0.0F) { + if (strafe > 0.0F) { + yaw += forward > 0.0F ? -45.0F : 45.0F; + } else if (strafe < 0.0F) { + yaw += forward > 0.0F ? 45.0F : -45.0F; + } + + strafe = 0.0F; + + if (forward > 0.0F) { + forward = 1.0F; + } else if (forward < 0.0F) { + forward = -1.0F; + } + } + + double radians = Math.toRadians(yaw + 90.0F); + double sin = Math.sin(radians); + double cos = Math.cos(radians); + + return new Vec3( + forward * speed * cos + strafe * speed * sin, + 0.0, + forward * speed * sin - strafe * speed * cos + ); + } + + private double moveSpeed(LocalPlayer player) { + double base; + + if (player.isInWater() || player.isInLava()) { + base = waterSpeed.getValue(); + } else if (!player.onGround()) { + base = airSpeed.getValue(); + } else { + base = groundSpeed.getValue(); + } + + MobEffectInstance speedEffect = player.getEffect(MobEffects.SPEED); + + if (speedEffect != null) { + base *= 1.0 + 0.2 * (speedEffect.getAmplifier() + 1); + } + + return base; + } + + @Override + public String getDisplayInfo() { + if (instantStop.getValue()) { + return "Instant"; + } + + return "Move"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Anchor.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Anchor.java new file mode 100644 index 0000000..2edef58 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Anchor.java @@ -0,0 +1,487 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.entity.player.TravelEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.HoleManager; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.List; + +public class Anchor extends Module { + public enum Mode { + Pitch, + Always + } + + public final Setting mode = mode("Mode", Mode.Always); + public final Setting pitch = num("Pitch", 60, 0, 90); + public final Setting range = num("Range", 1.5, 0.5, 3.0); + public final Setting verticalRange = num("VerticalRange", 6, 1, 6); + public final Setting pull = bool("Pull", true); + public final Setting stepUp = bool("StepUp", true); + public final Setting partial = bool("Partial", true); + public final Setting noSameHole = bool("NoSameHole", true); + public final Setting noAnchorOnMove = bool("NoAnchorOnMove", false); + public final Setting cooldown = num("Cooldown", 10, 0, 100); + + private static final double PULL_CAP = 0.32D; + private static final double MIN_PULL = 0.045D; + private static final double CENTER_THRESHOLD = 0.12D; + private static final double HOLD_THRESHOLD = 0.025D; + private static final double DOWN_PULL_RANGE = 0.35D; + private static final double DOWN_PULL_SPEED = -0.28D; + + private BlockPos anchoredIn; + private BlockPos lastAnchoredHole; + private BlockPos targetHole; + private Vec3 pendingPull = Vec3.ZERO; + private int snapCooldown; + + public Anchor() { + super("Anchor", "Anchors you into nearby holes", Category.MOVEMENT); + } + + @Override + public void onEnable() { + clearState(); + } + + @Override + public void onDisable() { + clearState(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + + if (player == null || mc.level == null || nolongerhuman.holeManager == null) { + clearState(); + return; + } + + pendingPull = Vec3.ZERO; + targetHole = null; + + if (noAnchorOnMove.getValue() && isTryingToMove()) { + clearCurrentAnchor(); + return; + } + + BlockPos currentHole = getCurrentHole(player); + + if (currentHole != null) { + anchoredIn = currentHole; + lastAnchoredHole = currentHole; + snapCooldown = 0; + + if (shouldAnchorNow(player)) { + targetHole = currentHole; + pendingPull = calculateAnchorMotion(player, currentHole); + applyPullVelocity(player, pendingPull); + } + + return; + } + + if (anchoredIn != null) { + lastAnchoredHole = anchoredIn; + anchoredIn = null; + + if (mode.getValue() == Mode.Always) { + snapCooldown = cooldown.getValue(); + } + } + + if (!shouldSearchForAnchor(player)) { + return; + } + + BlockPos foundHole = findTargetHole(player); + + if (foundHole == null) { + return; + } + + anchoredIn = foundHole; + targetHole = foundHole; + pendingPull = calculateAnchorMotion(player, foundHole); + applyPullVelocity(player, pendingPull); + } + + @Subscribe + public void onTravel(TravelEvent event) { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + if (targetHole == null) { + return; + } + + if (!shouldAnchorNow(player)) { + return; + } + + Vec3 pullMotion = calculateAnchorMotion(player, targetHole); + + if (pullMotion == Vec3.ZERO) { + return; + } + + + event.setX(pullMotion.x); + event.setZ(pullMotion.z); + + Vec3 currentMotion = player.getDeltaMovement(); + + player.setDeltaMovement( + pullMotion.x, + pullMotion.y == 0.0D ? currentMotion.y : pullMotion.y, + pullMotion.z + ); + } + + private void clearState() { + anchoredIn = null; + lastAnchoredHole = null; + targetHole = null; + pendingPull = Vec3.ZERO; + snapCooldown = 0; + } + + private void clearCurrentAnchor() { + if (anchoredIn != null) { + lastAnchoredHole = anchoredIn; + anchoredIn = null; + } + + targetHole = null; + pendingPull = Vec3.ZERO; + } + + private boolean shouldAnchorNow(LocalPlayer player) { + return mode.getValue() == Mode.Always || player.getXRot() >= pitch.getValue(); + } + + private boolean shouldSearchForAnchor(LocalPlayer player) { + if (mode.getValue() == Mode.Pitch && player.getXRot() < pitch.getValue()) { + return false; + } + + if (mode.getValue() == Mode.Always && snapCooldown > 0) { + snapCooldown--; + return false; + } + + return true; + } + + private boolean isTryingToMove() { + return mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown(); + } + + private BlockPos getCurrentHole(LocalPlayer player) { + BlockPos feet = player.blockPosition(); + + if (isValidManagerHole(feet)) { + return feet; + } + + BlockPos below = feet.below(); + + if (isValidManagerHole(below)) { + return below; + } + + return null; + } + + private BlockPos findTargetHole(LocalPlayer player) { + HoleManager holeManager = nolongerhuman.holeManager; + + if (holeManager == null) { + return null; + } + + BlockPos origin = player.blockPosition(); + + double playerX = player.getX(); + double playerZ = player.getZ(); + + double maxRange = range.getValue(); + double maxRangeSq = maxRange * maxRange; + + int downRange = verticalRange.getValue(); + int upRange = stepUp.getValue() ? 2 : 0; + + BlockPos best = null; + double bestDistSq = Double.MAX_VALUE; + + List managerHoles = new ArrayList<>(holeManager.getHoles()); + + for (HoleManager.Hole hole : managerHoles) { + if (isDisallowedManagerHole(hole)) { + continue; + } + + BlockPos pos = hole.pos(); + + if (isDisallowedTarget(pos)) { + continue; + } + + int dy = pos.getY() - origin.getY(); + + if (dy > upRange || dy < -downRange) { + continue; + } + + double distSq = horizontalDistanceSq(pos, playerX, playerZ); + + if (distSq > maxRangeSq) { + continue; + } + + if (distSq < bestDistSq) { + bestDistSq = distSq; + best = pos; + } + } + + if (best != null) { + return best; + } + + int radius = (int) Math.ceil(maxRange) + 1; + + for (int x = -radius; x <= radius; x++) { + for (int y = -downRange; y <= upRange; y++) { + for (int z = -radius; z <= radius; z++) { + BlockPos pos = origin.offset(x, y, z); + + if (isDisallowedTarget(pos)) { + continue; + } + + HoleManager.Hole hole = getHoleFromManager(pos); + + if (hole == null || isDisallowedManagerHole(hole)) { + continue; + } + + double distSq = horizontalDistanceSq(pos, playerX, playerZ); + + if (distSq > maxRangeSq) { + continue; + } + + if (distSq < bestDistSq) { + bestDistSq = distSq; + best = pos; + } + } + } + } + + return best; + } + + private HoleManager.Hole getHoleFromManager(BlockPos pos) { + HoleManager holeManager = nolongerhuman.holeManager; + + if (holeManager == null) { + return null; + } + + HoleManager.Hole normal = holeManager.getHole(pos); + + if (normal != null) { + return normal; + } + + if (partial.getValue()) { + return holeManager.getPartialHole(pos); + } + + return null; + } + + private boolean isDisallowedManagerHole(HoleManager.Hole hole) { + return !partial.getValue() && hole.holeType() == HoleManager.HoleType.PARTIAL; + } + + private boolean isDisallowedTarget(BlockPos pos) { + return noSameHole.getValue() + && lastAnchoredHole != null + && pos.equals(lastAnchoredHole); + } + + private boolean isValidManagerHole(BlockPos pos) { + HoleManager holeManager = nolongerhuman.holeManager; + + if (holeManager == null) { + return false; + } + + if (holeManager.isNormalHole(pos)) { + return true; + } + + if (holeManager.getHole(pos) != null) { + return true; + } + + if (!partial.getValue()) { + return false; + } + + if (holeManager.isPartial(pos)) { + return true; + } + + return holeManager.getPartialHole(pos) != null; + } + + private double horizontalDistanceSq(BlockPos pos, double playerX, double playerZ) { + double dx = pos.getX() + 0.5D - playerX; + double dz = pos.getZ() + 0.5D - playerZ; + + return dx * dx + dz * dz; + } + + private void applyPullVelocity(LocalPlayer player, Vec3 motion) { + if (motion == Vec3.ZERO) { + return; + } + + Vec3 currentMotion = player.getDeltaMovement(); + + player.setDeltaMovement( + motion.x, + motion.y == 0.0D ? currentMotion.y : motion.y, + motion.z + ); + } + + private Vec3 calculateAnchorMotion(LocalPlayer player, BlockPos hole) { + if (!pull.getValue()) { + return calculateHoldMotion(player, hole); + } + + return calculatePullMotion(player, hole); + } + + private Vec3 calculatePullMotion(LocalPlayer player, BlockPos hole) { + double centerX = hole.getX() + 0.5D; + double centerZ = hole.getZ() + 0.5D; + + double dx = centerX - player.getX(); + double dz = centerZ - player.getZ(); + + double absX = Math.abs(dx); + double absZ = Math.abs(dz); + + Vec3 currentMotion = player.getDeltaMovement(); + + if (absX <= HOLD_THRESHOLD && absZ <= HOLD_THRESHOLD) { + return new Vec3( + 0.0D, + getAnchoredYMotion(player, hole, currentMotion.y, true), + 0.0D + ); + } + + if (absX <= CENTER_THRESHOLD && absZ <= CENTER_THRESHOLD) { + return new Vec3( + dx * 0.45D, + getAnchoredYMotion(player, hole, currentMotion.y, true), + dz * 0.45D + ); + } + + double motionX = getPullMotion(dx); + double motionZ = getPullMotion(dz); + + return new Vec3( + motionX, + getAnchoredYMotion(player, hole, currentMotion.y, false), + motionZ + ); + } + + private Vec3 calculateHoldMotion(LocalPlayer player, BlockPos hole) { + Vec3 currentMotion = player.getDeltaMovement(); + + return new Vec3( + 0.0D, + getAnchoredYMotion(player, hole, currentMotion.y, true), + 0.0D + ); + } + + private double getAnchoredYMotion( + LocalPlayer player, + BlockPos hole, + double currentY, + boolean centered + ) { + if (!centered) { + return 0.0D; + } + + double holeY = hole.getY(); + double playerY = player.getY(); + + if (playerY > holeY + DOWN_PULL_RANGE) { + return Math.min(currentY, DOWN_PULL_SPEED); + } + + return 0.0D; + } + + private double getPullMotion(double delta) { + if (delta == 0.0D) { + return 0.0D; + } + + double motion = delta * 0.55D; + double clamped = clampPull(motion); + + if (Math.abs(clamped) < MIN_PULL) { + return Math.copySign(MIN_PULL, delta); + } + + return clamped; + } + + private double clampPull(double value) { + return Math.max(-PULL_CAP, Math.min(PULL_CAP, value)); + } + + @Override + public String getDisplayInfo() { + return anchoredIn == null + ? null + : anchoredIn.getX() + ", " + anchoredIn.getY() + ", " + anchoredIn.getZ(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AntiClimb.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AntiClimb.java new file mode 100644 index 0000000..b7d0579 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AntiClimb.java @@ -0,0 +1,97 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; + +public class AntiClimb extends Module { + public static AntiClimb INSTANCE; + + private final Setting ladders = bool("Ladders", true); + private final Setting vines = bool("Vines", true); + private final Setting keepVerticalMotion = bool("KeepVerticalMotion", true); + + public AntiClimb() { + super("AntiClimb", "Prevents climbing ladders and vines", Category.MOVEMENT); + INSTANCE = this; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + if (!shouldPreventClimbing(player)) { + return; + } + + + Vec3 motion = player.getDeltaMovement(); + + if (keepVerticalMotion.getValue()) { + player.setDeltaMovement(motion.x, Math.min(motion.y, 0.0D), motion.z); + } else { + player.setDeltaMovement(motion.x, 0.0D, motion.z); + } + } + + public boolean shouldPreventClimbing(LocalPlayer player) { + if (!isEnabled()) { + return false; + } + + if (player == null || mc.level == null) { + return false; + } + + return isAntiClimbBlock(player.blockPosition()) + || isAntiClimbBlock(BlockPos.containing(player.getX(), player.getY() + 0.5D, player.getZ())) + || isAntiClimbBlock(BlockPos.containing(player.getX(), player.getEyeY(), player.getZ())); + } + + private boolean isAntiClimbBlock(BlockPos pos) { + if (mc.level == null) { + return false; + } + + BlockState state = mc.level.getBlockState(pos); + + if (ladders.getValue() && state.is(BlockTags.CLIMBABLE)) { + return true; + } + + return vines.getValue() && isVineBlock(state); + } + + private boolean isVineBlock(BlockState state) { + return state.is(BlockTags.CLIMBABLE); + } + + public static boolean shouldCancelClimb(LocalPlayer player) { + return INSTANCE != null && INSTANCE.shouldPreventClimbing(player); + } + + @Override + public String getDisplayInfo() { + if (ladders.getValue() && vines.getValue()) { + return "All"; + } + + if (ladders.getValue()) { + return "Ladders"; + } + + if (vines.getValue()) { + return "Vines"; + } + + return "None"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AntiVoid.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AntiVoid.java new file mode 100644 index 0000000..aa20735 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AntiVoid.java @@ -0,0 +1,111 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.lang.reflect.Method; + +public class AntiVoid extends Module { + + public enum Mode { + FLING, + FLOAT, + BOUNCE, + PACKET + } + + private final Setting mode = mode("Mode", Mode.PACKET); + + public AntiVoid() { + super("AntiVoid", "Prevents you from falling into the void", Category.MOVEMENT); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + if (player == null || level == null) return; + + if (!overVoid(player, level)) return; + + Vec3 velocity = player.getDeltaMovement(); + + switch (mode.getValue()) { + case FLING -> player.setDeltaMovement(velocity.x, 1.0, velocity.z); + + case FLOAT -> player.setDeltaMovement(velocity.x, 0.0, velocity.z); + + case BOUNCE -> player.setDeltaMovement( + velocity.x, + Math.max(velocity.y, 0.4), + velocity.z + ); + + case PACKET -> player.connection.send(new ServerboundMovePlayerPacket.Pos( + player.getX(), + player.getY() + 3.0, + player.getZ(), + false, + player.horizontalCollision + )); + } + } + + private boolean overVoid(LocalPlayer player, ClientLevel level) { + int minY = getMinY(level); + double playerY = player.getY(); + + if (playerY > minY + 8.0) { + return false; + } + + AABB box = player.getBoundingBox(); + + for (double y = playerY; y > minY; y -= 1.0) { + if (!level.noCollision(player, box.move(0.0, y - playerY, 0.0))) { + return false; + } + } + + return true; + } + + private int getMinY(ClientLevel level) { + + Integer reflected = callIntNoArgs(level, "getMinY", "getMinBuildHeight"); + if (reflected != null) return reflected; + + try { + Object dimensionType = level.dimensionType(); + Integer dimMin = callIntNoArgs(dimensionType, "minY", "getMinY"); + if (dimMin != null) return dimMin; + } catch (Throwable ignored) { + } + + return -64; + } + + private Integer callIntNoArgs(Object object, String... names) { + Class clazz = object.getClass(); + + for (String name : names) { + try { + Method method = clazz.getMethod(name); + method.setAccessible(true); + + Object value = method.invoke(object); + if (value instanceof Number number) { + return number.intValue(); + } + } catch (Throwable ignored) { + } + } + + return null; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AutoLongJump.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AutoLongJump.java new file mode 100644 index 0000000..3c59ee2 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/AutoLongJump.java @@ -0,0 +1,76 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.BoostManager; +import net.minecraft.client.player.LocalPlayer; + +public class AutoLongJump extends Module { + + private final Setting threshold = num("Boost", 0.5, 0.1, 3.0); + private final Setting disableLongJumpOnLand = bool("DisableLongJumpOnLand", true); + + private boolean triggered; + private boolean airborne; + + public AutoLongJump() { + super("AutoLongJump", "LongJumps when enough explosion boost is received", Category.MOVEMENT); + } + + @Override + public void onDisable() { + releaseLongJump(); + triggered = false; + airborne = false; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + Module module = nolongerhuman.moduleManager.getModuleByClass(LongJump.class); + if (!(module instanceof LongJump longJump)) return; + + boolean moving = player.zza != 0.0F || player.xxa != 0.0F; + BoostManager boostManager = BoostManager.get(); + + if (!triggered) { + if (player.onGround() && moving && boostManager.hasBoost(threshold.getValue())) { + if (!longJump.isEnabled()) { + longJump.enable(); + } + + triggered = true; + airborne = false; + boostManager.consume(); + } + + return; + } + + if (!player.onGround()) { + airborne = true; + return; + } + + if (airborne) { + if (disableLongJumpOnLand.getValue() && longJump.isEnabled()) { + longJump.disable(); + } + + triggered = false; + airborne = false; + } + } + + private void releaseLongJump() { + if (!triggered) return; + + Module module = nolongerhuman.moduleManager.getModuleByClass(LongJump.class); + if (module instanceof LongJump longJump && longJump.isEnabled()) { + longJump.disable(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/ElytraFly.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/ElytraFly.java new file mode 100644 index 0000000..ef151c5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/ElytraFly.java @@ -0,0 +1,1218 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import me.humanbeing.nolongerhuman.util.models.Timer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.phys.Vec3; + +public class ElytraFly extends Module { + public enum Mode { + Control, + Creative, + Packet, + Boost, + Bounce, + Factor, + Freeze, + Rotation, + Pitch, + None + } + + public enum Strict { + None, + Normal, + NCP, + Glide, + Old, + New, + Motion + } + + public enum YawMode { + Normal, + Smart + } + + private final Setting mode = mode("Mode", Mode.Control); + + private final Setting autoEquip = bool("AutoEquip", true); + private final Setting autoStart = bool("AutoStart", true); + private final Setting setFlag = bool("SetFlag", false); + private final Setting autoStop = bool("AutoStop", true); + private final Setting jonarchy = bool("Jonarchy", false); + + private final Setting speed = num("Speed", 1.0, 0.1, 10.0); + private final Setting horizontal = num("Horizontal", 2.0, 0.1, 10.0); + private final Setting vertical = num("Vertical", 1.0, 0.1, 10.0); + private final Setting moveVertically = bool("MoveVertically", true); + + private final Setting lockY = bool("LockY", true); + + private final Setting upPitch = num("UpPitch", 0.0, 0.0, 90.0); + private final Setting upFactor = num("UpFactor", 1.0, 0.0, 10.0); + private final Setting downFactor = num("FallSpeed", 1.0, 0.0, 10.0); + private final Setting downSpeed = num("DownSpeed", 1.0, 0.1, 10.0); + + private final Setting speedLimit = bool("SpeedLimit", true); + private final Setting maxSpeed = num("MaxSpeed", 2.5, 0.1, 10.0); + private final Setting noDrag = bool("NoDrag", false); + + private final Setting firework = bool("Firework", false); + private final Setting fireworkDelay = num("Delay", 1000.0, 0.0, 20000.0); + private final Setting packetInteract = bool("PacketInteract", true); + private final Setting inventorySwap = bool("InventorySwap", true); + private final Setting onlyOne = bool("OnlyOne", true); + private final Setting usingPause = bool("UsingPause", true); + private final Setting checkSpeed = bool("CheckSpeed", false); + private final Setting minSpeed = num("MinSpeed", 70.0, 0.1, 200.0); + + private final Setting infiniteDurability = bool("InfiniteDurability", false); + private final Setting packetDelay = num("PacketDelay", 0, 0, 20); + private final Setting stopOnGround = bool("StopOnGround", true); + private final Setting ncpStrict = mode("NCPStrict", Strict.None); + + private final Setting boost = num("Boost", 1.0, 0.1, 4.0); + + private final Setting autoJump = bool("AutoJump", true); + private final Setting sprint = bool("Sprint", true); + private final Setting restart = bool("Restart", true); + private final Setting restartDelay = num("RestartDelay", 7, 0, 20); + private final Setting bouncePitch = num("Pitch", 85.0, 0.0, 90.0); + private final Setting yawMode = mode("YawMode", YawMode.Normal); + + private final Setting factor = num("Factor", 1.5, 0.1, 50.0); + private final Setting accelerate = bool("Accelerate", true); + private final Setting antiKick = bool("AntiKick", true); + + private final Setting freeze = bool("Freeze", false); + private final Setting motionStop = bool("MotionStop", false); + + private final Setting infiniteMaxSpeed = num("InfiniteMaxSpeed", 150.0, 50.0, 170.0); + private final Setting infiniteMinSpeed = num("InfiniteMinSpeed", 25.0, 10.0, 70.0); + private final Setting infiniteMaxHeight = num("InfiniteMaxHeight", 200.0, -50.0, 360.0); + + private final Setting timeout = num("Timeout", 0.5, 0.0, 1.0); + + private final Timer instantFlyTimer = new Timer(); + private final Timer fireworkTimer = new Timer(); + + private boolean hasElytra; + private boolean rubberbanded; + private boolean resetSpeed; + private boolean infinitePitchDown; + + private int restartTicks; + private int packetTicks; + private int elytraStartGraceTicks; + private int unloadedChunkTicks; + + private double currentFactorSpeed; + private float infinitePitch; + + private double lockedY; + private boolean lockedYSet; + + private double lastX; + private double lastY; + private double lastZ; + + public ElytraFly() { + super("ElytraFly", "Control your elytra flight", Category.MOVEMENT); + } + + @Override + public void onEnable() { + LocalPlayer player = mc.player; + + hasElytra = false; + rubberbanded = false; + resetSpeed = false; + infinitePitchDown = false; + + restartTicks = restartDelay.getValue(); + packetTicks = 0; + elytraStartGraceTicks = 0; + unloadedChunkTicks = 0; + + currentFactorSpeed = 1.0D; + infinitePitch = 0.0F; + + lockedY = 0.0D; + lockedYSet = false; + + instantFlyTimer.reset(); + fireworkTimer.setMs(99999999L); + + if (player != null) { + lastX = player.getX(); + lastY = player.getY(); + lastZ = player.getZ(); + + resetVanillaFlying(player); + } + } + + @Override + public void onDisable() { + LocalPlayer player = mc.player; + + hasElytra = false; + rubberbanded = false; + resetSpeed = false; + elytraStartGraceTicks = 0; + unloadedChunkTicks = 0; + + lockedY = 0.0D; + lockedYSet = false; + + if (player != null) { + resetVanillaFlying(player); + } + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + tickGrace(); + + if (autoEquip.getValue()) { + equipElytra(player); + } + + hasElytra = isElytraUsable(player.getItemBySlot(EquipmentSlot.CHEST)); + + if (!hasElytra) { + resetYLock(); + resetVanillaFlying(player); + updateLastPosition(player); + return; + } + + Module module = nolongerhuman.moduleManager.getModuleByClass(LongJump.class); + + if (module instanceof LongJump longJump && longJump.isGrimJumping()) { + resetYLock(); + resetVanillaFlying(player); + updateLastPosition(player); + return; + } + + if (shouldAutoStop(player, level)) { + resetYLock(); + setLimitedMotion(player, Vec3.ZERO); + updateLastPosition(player); + return; + } + + updateYLock(player); + updateInfinitePitch(player); + + if (mode.getValue() == Mode.Bounce) { + handleBounce(player); + player.fallDistance = 0.0F; + updateLastPosition(player); + return; + } + + if (mode.getValue() == Mode.Packet) { + handlePacket(player, level); + applyYLockPosition(player); + player.fallDistance = 0.0F; + updateLastPosition(player); + return; + } + + if (autoStart.getValue()) { + tryStartFlying(player); + } + + handleFirework(player); + + if (isNotFlyingWithElytra(player) && mode.getValue() != Mode.Factor && mode.getValue() != Mode.Creative) { + resetYLock(); + resetVanillaFlying(player); + updateLastPosition(player); + return; + } + + switch (mode.getValue()) { + case Control -> handleControl(player); + case Creative -> handleCreative(player); + case Boost -> handleBoost(player); + case Factor -> handleFactor(player); + case Freeze -> handleFreeze(player); + case Rotation -> handleRotation(player); + case Pitch -> handlePitch(player); + case None -> handleNone(player); + case Packet, Bounce -> { + } + } + + applyYLockPosition(player); + + player.fallDistance = 0.0F; + updateLastPosition(player); + } + + private void tickGrace() { + if (elytraStartGraceTicks > 0) { + elytraStartGraceTicks--; + } + } + + private void handleControl(LocalPlayer player) { + resetVanillaFlying(player); + + Vec3 motion = player.getDeltaMovement(); + Vec3 lookVec = getRotationVector(-upPitch.getValue().floatValue(), player.getYRot()); + + double lookDist = Math.sqrt((lookVec.x * lookVec.x) + (lookVec.z * lookVec.z)); + double motionDist = Math.sqrt((motion.x * motion.x) + (motion.z * motion.z)); + + double x = motion.x; + double z = motion.z; + double y = getControlY(); + + if (mc.options.keyJump.isDown() && lookDist > 0.0D && !jonarchy.getValue()) { + if (motionDist > upFactor.getValue() / 10.0D) { + double rawUpSpeed = motionDist * 0.01325D; + + y += rawUpSpeed * 3.2D; + x -= lookVec.x * rawUpSpeed / lookDist; + z -= lookVec.z * rawUpSpeed / lookDist; + } else { + double[] direction = directionSpeed(speed.getValue(), getMoveYaw(player)); + + x = direction[0]; + z = direction[1]; + } + } + + if (lookDist > 0.0D) { + x += ((lookVec.x / lookDist * motionDist) - x) * 0.1D; + z += ((lookVec.z / lookDist * motionDist) - z) * 0.1D; + } + + if (!mc.options.keyJump.isDown() || jonarchy.getValue()) { + double[] direction = directionSpeed(speed.getValue(), getMoveYaw(player)); + + x = direction[0]; + z = direction[1]; + } + + if (!noDrag.getValue()) { + y *= 0.9900000095367432D; + x *= 0.9800000190734863D; + z *= 0.9900000095367432D; + } + + setLimitedMotion(player, new Vec3(x, applyJonarchyY(y), z)); + } + + private double getControlY() { + if (!moveVertically.getValue()) { + return 0.0D; + } + + if (mc.options.keyShift.isDown()) { + return -downSpeed.getValue(); + } + + if (mc.options.keyJump.isDown() && !jonarchy.getValue()) { + return upFactor.getValue(); + } + + return 0.0D; + } + + private void handleCreative(LocalPlayer player) { + if (player.getAbilities().mayfly) { + player.getAbilities().flying = true; + player.getAbilities().setFlyingSpeed(horizontal.getValue().floatValue() / 15.0F); + } else { + resetVanillaFlying(player); + } + + double[] direction = directionSpeed(horizontal.getValue(), getMoveYaw(player)); + double y = getSimpleVerticalY(); + + setLimitedMotion(player, new Vec3(direction[0], applyJonarchyY(y), direction[1])); + } + + private void handlePacket(LocalPlayer player, ClientLevel level) { + resetVanillaFlying(player); + + if (stopOnGround.getValue() && isBlockBelow(player, level)) { + return; + } + + if (packetTicks < packetDelay.getValue()) { + packetTicks++; + return; + } + + packetTicks = 0; + + if (infiniteDurability.getValue()) { + equipToChest(InventoryUtil.find(Items.ELYTRA, InventoryUtil.FULL_SCOPE)); + } + + if (infiniteDurability.getValue() || isNotActuallyFallFlying(player)) { + startFlying(player); + } + + double[] direction = directionSpeed(horizontal.getValue(), getMoveYaw(player)); + double y = applyStrictY(player, getSimpleVerticalY()); + + if (infiniteDurability.getValue() || ncpStrict.getValue() == Strict.Motion) { + if (!isMoving() && Math.abs(direction[0]) < 0.121D) { + double angle = Math.toRadians(4.5D * (player.tickCount % 80)); + + setLimitedMotion( + player, + new Vec3( + Math.sin(angle) * 0.12D, + applyJonarchyY(y), + Math.cos(angle) * 0.12D + ) + ); + + return; + } + } + + setLimitedMotion(player, new Vec3(direction[0], applyJonarchyY(y), direction[1])); + } + + private void handleBoost(LocalPlayer player) { + resetVanillaFlying(player); + + if (isNotFlyingWithElytra(player)) { + return; + } + + Vec3 motion = player.getDeltaMovement(); + double yaw = Math.toRadians(player.getYRot()); + + if (mc.options.keyUp.isDown()) { + setLimitedMotion( + player, + new Vec3( + motion.x - (Math.sin(yaw) * boost.getValue() / 10.0D), + applyJonarchyY(motion.y), + motion.z + (Math.cos(yaw) * boost.getValue() / 10.0D) + ) + ); + return; + } + + setLimitedMotion(player, new Vec3(motion.x, applyJonarchyY(motion.y), motion.z)); + } + + private void handleBounce(LocalPlayer player) { + resetYLock(); + resetVanillaFlying(player); + + if (autoJump.getValue() && player.onGround() && !jonarchy.getValue()) { + setLimitedMotion(player, new Vec3(player.getDeltaMovement().x, 0.42D, player.getDeltaMovement().z)); + } + + if (player.horizontalCollision) { + rubberbanded = true; + } + + if (isNotActuallyFallFlying(player) && !rubberbanded) { + startFlying(player); + } + + if (rubberbanded && restart.getValue()) { + if (restartTicks > 0) { + restartTicks--; + } else { + startFlying(player); + rubberbanded = false; + restartTicks = restartDelay.getValue(); + } + } + + if (checkConditions(player)) { + if (sprint.getValue()) { + player.setSprinting(canSprint(player)); + } else if (isActuallyFallFlying(player)) { + player.setSprinting(player.onGround()); + } else { + player.setSprinting(true); + } + } + + player.setXRot(bouncePitch.getValue().floatValue()); + + double[] direction = directionSpeed(horizontal.getValue(), getBounceYaw(player)); + double y = getBounceY(player); + + setLimitedMotion(player, new Vec3(direction[0], applyJonarchyY(y), direction[1])); + } + + private double getBounceY(LocalPlayer player) { + double currentY = player.getDeltaMovement().y; + + if (player.onGround() && !jonarchy.getValue()) { + return Math.max(currentY, 0.42D); + } + + return currentY; + } + + private void handleFactor(LocalPlayer player) { + resetVanillaFlying(player); + + if (isNotFlyingWithElytra(player)) { + startFlying(player); + } + + if (player.horizontalCollision) { + resetSpeed = true; + } + + updateFactorSpeed(); + + double[] direction = directionSpeed(horizontal.getValue(), getMoveYaw(player)); + + double x = direction[0] * currentFactorSpeed; + double z = direction[1] * currentFactorSpeed; + double y = getFactorY(player, x, z); + + if (antiKick.getValue() && x == 0.0D && z == 0.0D && !resetSpeed) { + x = Math.sin(Math.toRadians(player.tickCount % 360)) * 0.03D; + z = Math.cos(Math.toRadians(player.tickCount % 360)) * 0.03D; + } + + setLimitedMotion(player, new Vec3(x, applyJonarchyY(y), z)); + } + + private void updateFactorSpeed() { + if (!accelerate.getValue()) { + currentFactorSpeed = factor.getValue(); + return; + } + + if (resetSpeed) { + currentFactorSpeed = 1.0D; + resetSpeed = false; + } + + if (currentFactorSpeed < factor.getValue()) { + currentFactorSpeed += 0.1D; + } + + if (currentFactorSpeed - 0.1D > factor.getValue()) { + currentFactorSpeed -= 0.1D; + } + } + + private double getFactorY(LocalPlayer player, double x, double z) { + if (mc.options.keyJump.isDown() && !jonarchy.getValue()) { + return upFactor.getValue(); + } + + if (mc.options.keyShift.isDown()) { + return -downFactor.getValue(); + } + + return switch (ncpStrict.getValue()) { + case Normal -> player.tickCount % 32 == 0 && (Math.abs(x) >= 0.05D || Math.abs(z) >= 0.05D) + ? 0.006200000000000001D + : -2.0E-4D; + case NCP, Glide -> -0.00001D; + case Old -> 0.0002D - (player.tickCount % 2 == 0 ? 0.0D : 0.000001D); + case New -> -1.000088900582341E-12D; + case Motion -> -4.000355602329364E-12D; + case None -> 0.0D; + }; + } + + private void handleFreeze(LocalPlayer player) { + resetVanillaFlying(player); + + if (!isMoving() && !hasVerticalInput()) { + setLimitedMotion(player, Vec3.ZERO); + return; + } + + handleControl(player); + } + + private void handleRotation(LocalPlayer player) { + resetVanillaFlying(player); + + if (isNotFlyingWithElytra(player)) { + return; + } + + if (freeze.getValue() && !isMoving() && !hasVerticalInput()) { + setLimitedMotion(player, Vec3.ZERO); + return; + } + + if (isMoving()) { + player.setYRot(getMoveYaw(player)); + player.setXRot(getRotationPitch()); + + Vec3 motion = player.getDeltaMovement(); + + if (motionStop.getValue() && !hasVerticalInput()) { + motion = new Vec3(motion.x, 0.0D, motion.z); + } + + double[] direction = directionSpeed(speed.getValue(), player.getYRot()); + + setLimitedMotion(player, new Vec3(direction[0], applyJonarchyY(motion.y), direction[1])); + return; + } + + if (mc.options.keyJump.isDown() && !jonarchy.getValue()) { + player.setXRot(-89.0F); + } else if (mc.options.keyShift.isDown()) { + player.setXRot(89.0F); + } else if (motionStop.getValue()) { + setLimitedMotion(player, Vec3.ZERO); + } else { + applyYLockPosition(player); + } + } + + private float getRotationPitch() { + if (mc.options.keyJump.isDown() && !jonarchy.getValue()) { + return -45.0F; + } + + if (mc.options.keyShift.isDown()) { + return 45.0F; + } + + return 0.0F; + } + + private void handlePitch(LocalPlayer player) { + resetVanillaFlying(player); + + if (isNotFlyingWithElytra(player)) { + tryStartFlying(player); + return; + } + + player.setXRot(infinitePitch); + + double[] direction = directionSpeed(speed.getValue(), getMoveYaw(player)); + double y = getPitchY(); + + setLimitedMotion(player, new Vec3(direction[0], applyJonarchyY(y), direction[1])); + } + + private double getPitchY() { + if (infinitePitch > 0.0F) { + return -Math.abs(vertical.getValue() * 0.15D); + } + + if (infinitePitch < 0.0F && !jonarchy.getValue()) { + return Math.abs(vertical.getValue() * 0.08D); + } + + return 0.0D; + } + + private void handleNone(LocalPlayer player) { + resetVanillaFlying(player); + + if (autoStart.getValue()) { + tryStartFlying(player); + } + + applyYLockPosition(player); + } + + private void handleFirework(LocalPlayer player) { + if (!firework.getValue()) { + return; + } + + if (usingPause.getValue() && player.isUsingItem()) { + return; + } + + if (isNotFlyingWithElytra(player)) { + return; + } + + if (!isMoving() && mode.getValue() != Mode.Rotation) { + return; + } + + if (checkSpeed.getValue() && getCurrentSpeed(player) > minSpeed.getValue()) { + return; + } + + long delay = getFireworkDelay(); + + if (!fireworkTimer.passedMs(delay)) { + return; + } + + useFirework(player); + fireworkTimer.reset(); + } + + private long getFireworkDelay() { + long delay = fireworkDelay.getValue().longValue(); + + if (onlyOne.getValue()) { + return delay + 250L; + } + + return delay; + } + + private void tryStartFlying(LocalPlayer player) { + if (player.onGround()) { + return; + } + + if (isFlyingWithElytra(player)) { + return; + } + + if (player.getDeltaMovement().y >= 0.0D) { + return; + } + + long timeoutMs = (long) (timeout.getValue() * 1000.0D); + + if (!instantFlyTimer.passedMs(timeoutMs)) { + return; + } + + instantFlyTimer.reset(); + fireworkTimer.setMs(99999999L); + + startFlying(player); + } + + private void startFlying(LocalPlayer player) { + if (!checkConditions(player)) { + return; + } + + if (elytraStartGraceTicks > 0) { + return; + } + + player.connection.send( + new ServerboundPlayerCommandPacket( + player, + ServerboundPlayerCommandPacket.Action.START_FALL_FLYING + ) + ); + + elytraStartGraceTicks = 5; + + if (setFlag.getValue()) { + player.startFallFlying(); + } + } + + private boolean checkConditions(LocalPlayer player) { + ItemStack chest = player.getItemBySlot(EquipmentSlot.CHEST); + + return !player.getAbilities().flying + && !player.isPassenger() + && !player.onClimbable() + && isElytraUsable(chest) + && !player.isInWater() + && !player.hasEffect(MobEffects.LEVITATION); + } + + private boolean canSprint(LocalPlayer player) { + return !player.isShiftKeyDown() + && !player.isPassenger() + && !player.isInWater() + && !player.isInLava() + && !player.onClimbable() + && !player.hasEffect(MobEffects.BLINDNESS) + && player.getFoodData().getFoodLevel() > 6.0F; + } + + private boolean isActuallyFallFlying(LocalPlayer player) { + return player.isFallFlying(); + } + + private boolean isNotActuallyFallFlying(LocalPlayer player) { + return !player.isFallFlying(); + } + + private boolean isFlyingWithElytra(LocalPlayer player) { + return player.isFallFlying() || elytraStartGraceTicks > 0 && hasElytra && !player.onGround(); + } + + private boolean isNotFlyingWithElytra(LocalPlayer player) { + return !player.isFallFlying() && (elytraStartGraceTicks <= 0 || !hasElytra || player.onGround()); + } + + private boolean isElytraUsable(ItemStack stack) { + return stack.is(Items.ELYTRA) + && (!stack.isDamageableItem() || stack.getDamageValue() < stack.getMaxDamage() - 1); + } + + private boolean isMoving() { + return mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown(); + } + + private boolean hasVerticalInput() { + return mc.options.keyJump.isDown() || mc.options.keyShift.isDown(); + } + + private boolean shouldLockY(LocalPlayer player) { + if (!lockY.getValue()) { + return false; + } + + if (mode.getValue() == Mode.Bounce) { + return false; + } + + if (!isFlyingWithElytra(player)) { + return false; + } + + return !hasVerticalInput(); + } + + private void updateYLock(LocalPlayer player) { + if (!lockY.getValue()) { + resetYLock(); + return; + } + + if (!isFlyingWithElytra(player)) { + resetYLock(); + return; + } + + if (hasVerticalInput()) { + lockedY = player.getY(); + lockedYSet = true; + return; + } + + if (!lockedYSet) { + lockedY = player.getY(); + lockedYSet = true; + } + } + + private void resetYLock() { + lockedY = 0.0D; + lockedYSet = false; + } + + private Vec3 applyYLockMotion(LocalPlayer player, Vec3 motion) { + if (!shouldLockY(player)) { + return motion; + } + + if (!lockedYSet) { + lockedY = player.getY(); + lockedYSet = true; + } + + double difference = lockedY - player.getY(); + + if (Math.abs(difference) < 1.0E-4D) { + return new Vec3(motion.x, 0.0D, motion.z); + } + + double correction = Math.max(-0.08D, Math.min(0.08D, difference)); + + return new Vec3(motion.x, correction, motion.z); + } + + private void applyYLockPosition(LocalPlayer player) { + if (!shouldLockY(player)) { + return; + } + + if (!lockedYSet) { + lockedY = player.getY(); + lockedYSet = true; + } + + if (Math.abs(player.getY() - lockedY) > 1.0E-3D) { + player.setPos(player.getX(), lockedY, player.getZ()); + } + + Vec3 motion = player.getDeltaMovement(); + + if (motion.y != 0.0D) { + player.setDeltaMovement(motion.x, 0.0D, motion.z); + } + } + + private float getMoveYaw(LocalPlayer player) { + float yaw = player.getYRot(); + + if (mc.options.keyUp.isDown() && !mc.options.keyDown.isDown()) { + if (mc.options.keyLeft.isDown() && !mc.options.keyRight.isDown()) { + yaw -= 45.0F; + } else if (mc.options.keyRight.isDown() && !mc.options.keyLeft.isDown()) { + yaw += 45.0F; + } + + return yaw; + } + + if (mc.options.keyDown.isDown() && !mc.options.keyUp.isDown()) { + yaw += 180.0F; + + if (mc.options.keyLeft.isDown() && !mc.options.keyRight.isDown()) { + yaw += 45.0F; + } else if (mc.options.keyRight.isDown() && !mc.options.keyLeft.isDown()) { + yaw -= 45.0F; + } + + return yaw; + } + + if (mc.options.keyLeft.isDown() && !mc.options.keyRight.isDown()) { + yaw -= 90.0F; + } else if (mc.options.keyRight.isDown() && !mc.options.keyLeft.isDown()) { + yaw += 90.0F; + } + + return yaw; + } + + private float getBounceYaw(LocalPlayer player) { + float yaw = getMoveYaw(player); + + if (yawMode.getValue() == YawMode.Smart) { + return Math.round((yaw + 1.0F) / 45.0F) * 45.0F; + } + + return yaw; + } + + private double[] directionSpeed(double amount, float yaw) { + if (!isMoving()) { + return new double[]{0.0D, 0.0D}; + } + + double radians = Math.toRadians(yaw); + + return new double[]{ + -Math.sin(radians) * amount, + Math.cos(radians) * amount + }; + } + + private Vec3 getRotationVector(float pitch, float yaw) { + float pitchRad = pitch * 0.017453292F; + float yawRad = -yaw * 0.017453292F; + + float yawCos = (float) Math.cos(yawRad); + float yawSin = (float) Math.sin(yawRad); + float pitchCos = (float) Math.cos(pitchRad); + float pitchSin = (float) Math.sin(pitchRad); + + return new Vec3(yawSin * pitchCos, -pitchSin, yawCos * pitchCos); + } + + private double getSimpleVerticalY() { + if (!moveVertically.getValue()) { + return 0.0D; + } + + if (mc.options.keyJump.isDown() && !jonarchy.getValue()) { + return vertical.getValue(); + } + + if (mc.options.keyShift.isDown()) { + return -vertical.getValue(); + } + + return 0.0D; + } + + private double applyStrictY(LocalPlayer player, double y) { + if (shouldLockY(player)) { + return 0.0D; + } + + return switch (ncpStrict.getValue()) { + case Old -> 0.0002D - (player.tickCount % 2 == 0 ? 0.0D : 0.000001D); + case New -> player.horizontalCollision && player.tickCount % 2 == 0 + ? -0.07840000152587923D + : -1.000088900582341E-12D; + case Motion -> player.horizontalCollision && player.tickCount % 2 == 0 + ? -0.07840000152587923D + : -4.000355602329364E-12D; + case Normal -> -2.0E-4D; + case NCP, Glide -> -0.00001D; + case None -> y; + }; + } + + private double applyJonarchyY(double y) { + if (jonarchy.getValue() && y > 0.0D) { + return 0.0D; + } + + return y; + } + + private void updateInfinitePitch(LocalPlayer player) { + double currentPlayerSpeed = Math.hypot(player.getX() - lastX, player.getZ() - lastZ); + + if (player.getY() < infiniteMaxHeight.getValue()) { + if (currentPlayerSpeed * 72.0D < infiniteMinSpeed.getValue() && !infinitePitchDown) { + infinitePitchDown = true; + } + + if (currentPlayerSpeed * 72.0D > infiniteMaxSpeed.getValue() && infinitePitchDown) { + infinitePitchDown = false; + } + } else { + infinitePitchDown = true; + } + + if (infinitePitchDown) { + infinitePitch += 3.0F; + } else { + infinitePitch -= 3.0F; + } + + clampInfinitePitch(); + } + + private void clampInfinitePitch() { + if (infinitePitch < -40.0F) { + infinitePitch = -40.0F; + } else if (infinitePitch > 40.0F) { + infinitePitch = 40.0F; + } + } + + private double getCurrentSpeed(LocalPlayer player) { + double x = player.getX() - lastX; + double y = player.getY() - lastY; + double z = player.getZ() - lastZ; + + double distance = Math.sqrt((x * x) + (y * y) + (z * z)) / 1000.0D; + double divisor = 0.05D / 3600.0D; + + return distance / divisor; + } + + private boolean isBlockBelow(LocalPlayer player, ClientLevel level) { + return !level.noCollision( + player, + player.getBoundingBox().inflate(-0.25D, 0.0D, -0.25D).move(0.0D, -0.3D, 0.0D) + ); + } + + private boolean shouldAutoStop(LocalPlayer player, ClientLevel level) { + if (!autoStop.getValue() || isNotActuallyFallFlying(player)) { + unloadedChunkTicks = 0; + return false; + } + + int chunkX = player.blockPosition().getX() >> 4; + int chunkZ = player.blockPosition().getZ() >> 4; + + if (level.getChunkSource().hasChunk(chunkX, chunkZ)) { + unloadedChunkTicks = 0; + return false; + } + + unloadedChunkTicks++; + + return unloadedChunkTicks >= 5; + } + + private void resetVanillaFlying(LocalPlayer player) { + if (!player.getAbilities().mayfly) { + player.getAbilities().flying = false; + } + + player.getAbilities().setFlyingSpeed(0.05F); + } + + private void updateLastPosition(LocalPlayer player) { + lastX = player.getX(); + lastY = player.getY(); + lastZ = player.getZ(); + } + + private void setLimitedMotion(LocalPlayer player, Vec3 motion) { + Vec3 locked = applyYLockMotion(player, motion); + Vec3 limited = limitMotion(locked); + + player.setDeltaMovement(limited); + } + + private Vec3 limitMotion(Vec3 motion) { + if (!speedLimit.getValue()) { + return motion; + } + + double x = motion.x; + double y = motion.y; + double z = motion.z; + + double max = maxSpeed.getValue(); + double horizontalSpeed = Math.sqrt((x * x) + (z * z)); + + if (horizontalSpeed > max && horizontalSpeed > 0.0D) { + double scale = max / horizontalSpeed; + + x *= scale; + z *= scale; + } + + if (y > max) { + y = max; + } else if (y < -max) { + y = -max; + } + + return new Vec3(x, y, z); + } + + private void useFirework(LocalPlayer player) { + if (player.getMainHandItem().is(Items.FIREWORK_ROCKET)) { + useMainHandFirework(player); + return; + } + + Result result = InventoryUtil.find(Items.FIREWORK_ROCKET, InventoryUtil.FULL_SCOPE); + + if (result == null || result.type() == ResultType.NONE) { + return; + } + + if (result.type() == ResultType.HOTBAR) { + useHotbarFirework(player, result.slot()); + return; + } + + if (!inventorySwap.getValue()) { + return; + } + + useInventoryFirework(player, result); + } + + private void useHotbarFirework(LocalPlayer player, int slot) { + int oldSlot = player.getInventory().getSelectedSlot(); + + player.getInventory().setSelectedSlot(slot); + useMainHandFirework(player); + player.getInventory().setSelectedSlot(oldSlot); + } + + private void useInventoryFirework(LocalPlayer player, Result result) { + int fromSlot = toMenuSlot(result); + + if (fromSlot < 0) { + return; + } + + int selectedSlot = player.getInventory().getSelectedSlot(); + + InventoryUtil.click(fromSlot, selectedSlot, ClickType.SWAP); + useMainHandFirework(player); + InventoryUtil.click(fromSlot, selectedSlot, ClickType.SWAP); + } + + private void useMainHandFirework(LocalPlayer player) { + if (mc.gameMode == null) { + return; + } + + mc.gameMode.useItem(player, InteractionHand.MAIN_HAND); + + if (!packetInteract.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + } + + private void equipElytra(LocalPlayer player) { + ItemStack chest = player.getItemBySlot(EquipmentSlot.CHEST); + + if (chest.is(Items.ELYTRA)) { + return; + } + + equipToChest( + InventoryUtil.find( + Items.ELYTRA, + InventoryUtil.FULL_SCOPE + ) + ); + } + + static void equipToChest(Result result) { + if (result == null || result.type() == ResultType.NONE) { + return; + } + + int fromSlot = toMenuSlot(result); + + if (fromSlot < 0) { + return; + } + + int chestSlot = 6; + + InventoryUtil.click(fromSlot, 0, ClickType.PICKUP); + InventoryUtil.click(chestSlot, 0, ClickType.PICKUP); + + if (!InventoryUtil.cursor().isEmpty()) { + InventoryUtil.click(fromSlot, 0, ClickType.PICKUP); + } + } + + static int toMenuSlot(Result result) { + return switch (result.type()) { + case OFFHAND -> 45; + case HOTBAR -> 36 + result.slot(); + case INVENTORY -> result.slot(); + default -> -1; + }; + } + + public String getInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastClimb.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastClimb.java new file mode 100644 index 0000000..5951f5b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastClimb.java @@ -0,0 +1,40 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.level.block.StairBlock; +import net.minecraft.world.phys.Vec3; + +public class FastClimb extends Module { + + public FastClimb() { + super("FastClimb", "Quickly climbs stairs", Category.MOVEMENT); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) return; + if (!player.onGround()) return; + if (player.zza == 0.0F && player.xxa == 0.0F) return; + + if (!(level.getBlockState(player.blockPosition().below()).getBlock() instanceof StairBlock)) { + return; + } + + double jump = 0.42; + + MobEffectInstance jumpBoost = player.getEffect(MobEffects.JUMP_BOOST); + if (jumpBoost != null) { + jump += (jumpBoost.getAmplifier() + 1) * 0.1; + } + + Vec3 velocity = player.getDeltaMovement(); + player.setDeltaMovement(velocity.x, jump, velocity.z); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastFirework.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastFirework.java new file mode 100644 index 0000000..1ab7867 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastFirework.java @@ -0,0 +1,64 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.phys.Vec3; + +public class FastFirework extends Module { + + private final Setting speed = num("Speed", 0.4, 0.1, 4.0); + private final Setting boost = bool("Boost", false); + private final Setting factor = num("Factor", 0.25, 0.1, 0.5); + + public FastFirework() { + super("FastFirework", "Speeds up the boost from fireworks", Category.MOVEMENT); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + if (!player.isFallFlying()) return; + + double amount = getSpeed(player); + double yaw = Math.toRadians(player.getYRot()); + + Vec3 velocity = player.getDeltaMovement(); + player.setDeltaMovement( + -Math.sin(yaw) * amount, + velocity.y, + Math.cos(yaw) * amount + ); + } + + public float getSpeed() { + LocalPlayer player = mc.player; + if (player == null) { + return speed.getValue().floatValue(); + } + + return getSpeed(player); + } + + private float getSpeed(LocalPlayer player) { + float kmh = getSpeedKmh(player); + + if (boost.getValue() && kmh > 90.0F) { + return speed.getValue().floatValue() + (kmh / 100.0F * factor.getValue().floatValue()); + } + + return speed.getValue().floatValue(); + } + + private float getSpeedKmh(LocalPlayer player) { + double dx = player.getX() - player.xo; + double dz = player.getZ() - player.zo; + return (float) (Math.sqrt(dx * dx + dz * dz) / 0.05 * 3.6); + } + + @Override + public String getDisplayInfo() { + return String.format("%.1f", getSpeed()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastSwim.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastSwim.java new file mode 100644 index 0000000..940fb3f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastSwim.java @@ -0,0 +1,123 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; + +public class FastSwim extends Module { + public static FastSwim INSTANCE; + + private final Setting speed = num("Speed", 0.2, 0.0, 1.0); + private final Setting downSpeed = num("DownSpeed", 0.2, 0.0, 1.0); + private final Setting upSpeed = num("UpSpeed", 0.2, 0.0, 1.0); + private final Setting downFactor = num("DownFactor", 0.0, 0.0, 1.0); + + public FastSwim() { + super("FastSwim", "Makes swimming faster", Category.MOVEMENT); + INSTANCE = this; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + if (!isInFluid(player)) { + return; + } + + double y = getVerticalMotion(); + double[] horizontal = getHorizontalMotion(speed.getValue(), getMoveYaw(player)); + + player.setDeltaMovement( + horizontal[0], + y, + horizontal[1] + ); + } + + private boolean isInFluid(LocalPlayer player) { + return player.isInWater() || player.isInLava(); + } + + private double getVerticalMotion() { + boolean sneak = mc.options.keyShift.isDown(); + boolean jump = mc.options.keyJump.isDown(); + + if (sneak && jump) { + return 0.0D; + } + + if (sneak) { + return -downSpeed.getValue(); + } + + if (jump) { + return upSpeed.getValue(); + } + + return -downFactor.getValue(); + } + + private double[] getHorizontalMotion(double amount, float yaw) { + if (!isMoving()) { + return new double[]{0.0D, 0.0D}; + } + + double radians = Math.toRadians(yaw); + + return new double[]{ + -Math.sin(radians) * amount, + Math.cos(radians) * amount + }; + } + + private boolean isMoving() { + return mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown(); + } + + private float getMoveYaw(LocalPlayer player) { + float yaw = player.getYRot(); + + if (mc.options.keyUp.isDown() && !mc.options.keyDown.isDown()) { + if (mc.options.keyLeft.isDown() && !mc.options.keyRight.isDown()) { + yaw -= 45.0F; + } else if (mc.options.keyRight.isDown() && !mc.options.keyLeft.isDown()) { + yaw += 45.0F; + } + + return yaw; + } + + if (mc.options.keyDown.isDown() && !mc.options.keyUp.isDown()) { + yaw += 180.0F; + + if (mc.options.keyLeft.isDown() && !mc.options.keyRight.isDown()) { + yaw += 45.0F; + } else if (mc.options.keyRight.isDown() && !mc.options.keyLeft.isDown()) { + yaw -= 45.0F; + } + + return yaw; + } + + if (mc.options.keyLeft.isDown() && !mc.options.keyRight.isDown()) { + yaw -= 90.0F; + } else if (mc.options.keyRight.isDown() && !mc.options.keyLeft.isDown()) { + yaw += 90.0F; + } + + return yaw; + } + + @Override + public String getDisplayInfo() { + return String.format("%.2f", speed.getValue()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastWeb.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastWeb.java new file mode 100644 index 0000000..f6b2211 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/FastWeb.java @@ -0,0 +1,263 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.List; + +public class FastWeb extends Module { + public enum Mode { + Vanilla, + Strict, + Custom, + Ignore + } + + private final Setting mode = mode("Mode", Mode.Ignore); + private final Setting speed = num("Speed", 3.0, 0.0, 8.0); + private final Setting xzSpeed = num("XZSpeed", 25.0, 0.0, 100.0); + private final Setting ySpeed = num("YSpeed", 100.0, 0.0, 100.0); + private final Setting onlySneak = bool("OnlySneak", true); + private final Setting grim = bool("Grim", false); + + private final Setting webBoost = bool("WebBoost", true); + private final Setting webBoostAmount = num("WebBoostAmount", 0.26, 0.05, 0.8); + private final Setting keepSprint = bool("KeepSprint", true); + + private boolean inWeb = false; + + public FastWeb() { + super("FastWeb", "Makes cobweb movement faster", Category.MOVEMENT); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + inWeb = false; + return; + } + + List webs = getIntersectingWebs(player, level); + inWeb = !webs.isEmpty(); + + if (!inWeb) { + return; + } + + if (grim.getValue()) { + sendGrimPackets(player, webs); + } + + handleWebBoost(player); + + if (!shouldWork(player)) { + return; + } + + switch (mode.getValue()) { + case Vanilla -> handleVanilla(player); + case Strict -> handleStrict(player); + case Custom -> handleCustom(player); + case Ignore -> { + } + } + } + + private boolean shouldWork(LocalPlayer player) { + return !player.onGround() && (!onlySneak.getValue() || mc.options.keyShift.isDown()); + } + + private void handleVanilla(LocalPlayer player) { + Vec3 motion = player.getDeltaMovement(); + + player.setDeltaMovement( + motion.x, + motion.y - speed.getValue(), + motion.z + ); + } + + private void handleStrict(LocalPlayer player) { + Vec3 motion = player.getDeltaMovement(); + + player.setDeltaMovement( + motion.x, + motion.y - speed.getValue() / 10.0D, + motion.z + ); + } + + private void handleCustom(LocalPlayer player) { + Vec3 motion = player.getDeltaMovement(); + + double horizontalMultiplier = xzSpeed.getValue() / 100.0D; + double verticalMultiplier = ySpeed.getValue() / 100.0D; + + player.setDeltaMovement( + motion.x * horizontalMultiplier, + motion.y * verticalMultiplier, + motion.z * horizontalMultiplier + ); + } + + private void handleWebBoost(LocalPlayer player) { + if (!webBoost.getValue()) { + return; + } + + if (!hasMovementInput(player)) { + return; + } + + if (keepSprint.getValue() && !player.isSprinting()) { + player.setSprinting(true); + } + + double boostSpeed = getWebBoostSpeed(player); + Vec3 boosted = forward(player, boostSpeed); + Vec3 current = player.getDeltaMovement(); + + player.setDeltaMovement( + boosted.x, + current.y, + boosted.z + ); + } + + private double getWebBoostSpeed(LocalPlayer player) { + double boostSpeed = webBoostAmount.getValue(); + MobEffectInstance speedEffect = player.getEffect(MobEffects.SPEED); + + if (speedEffect != null) { + boostSpeed *= 1.0D + 0.2D * (speedEffect.getAmplifier() + 1); + } + + return boostSpeed; + } + + private boolean hasMovementInput(LocalPlayer player) { + return Math.abs(player.zza) > 0.0001F || Math.abs(player.xxa) > 0.0001F; + } + + private Vec3 forward(LocalPlayer player, double speed) { + float forward = player.zza; + float strafe = player.xxa; + + if (forward == 0.0F && strafe == 0.0F) { + return Vec3.ZERO; + } + + float yaw = player.getYRot(); + + if (forward != 0.0F) { + if (strafe > 0.0F) { + yaw += forward > 0.0F ? -45.0F : 45.0F; + } else if (strafe < 0.0F) { + yaw += forward > 0.0F ? 45.0F : -45.0F; + } + + strafe = 0.0F; + + if (forward > 0.0F) { + forward = 1.0F; + } else if (forward < 0.0F) { + forward = -1.0F; + } + } + + double radians = Math.toRadians(yaw + 90.0F); + double sin = Math.sin(radians); + double cos = Math.cos(radians); + + return new Vec3( + forward * speed * cos + strafe * speed * sin, + 0.0D, + forward * speed * sin - strafe * speed * cos + ); + } + + private List getIntersectingWebs(LocalPlayer player, ClientLevel level) { + List blocks = new ArrayList<>(); + AABB box = player.getBoundingBox().inflate(0.001D); + + int minX = floor(box.minX) - 1; + int minY = floor(box.minY) - 1; + int minZ = floor(box.minZ) - 1; + int maxX = floor(box.maxX) + 1; + int maxY = floor(box.maxY) + 1; + int maxZ = floor(box.maxZ) + 1; + + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + BlockPos pos = new BlockPos(x, y, z); + BlockState state = level.getBlockState(pos); + + if (state.is(Blocks.COBWEB)) { + blocks.add(pos); + } + } + } + } + + return blocks; + } + + private void sendGrimPackets(LocalPlayer player, List webs) { + if (player.connection == null) { + return; + } + + for (BlockPos pos : webs) { + player.connection.send( + new ServerboundPlayerActionPacket( + ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, + pos, + Direction.DOWN + ) + ); + + player.connection.send( + new ServerboundPlayerActionPacket( + ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, + pos, + Direction.DOWN + ) + ); + } + } + + private int floor(double value) { + int integer = (int) value; + + if (value < integer) { + return integer - 1; + } + + return integer; + } + + @Override + public String getDisplayInfo() { + if (webBoost.getValue()) { + return mode.getValue().name() + " Boost"; + } + + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/HoleSnap.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/HoleSnap.java new file mode 100644 index 0000000..909928e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/HoleSnap.java @@ -0,0 +1,260 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.HoleManager; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; + +import java.util.Comparator; +import java.util.List; + +public class HoleSnap extends Module { + private final Setting range = num("Range", 5.0, 1.0, 8.0); + private final Setting speed = num("Speed", 0.2873, 0.05, 1.0); + private final Setting partial = bool("Partial", false); + private final Setting reRoute = bool("ReRoute", true); + private final Setting disableInHole = bool("DisableInHole", true); + private final Setting swapping = bool("Swapping", false); + private final Setting swappingRange = num("SwappingRange", 3.0, 1.0, 8.0); + + private static final double HOLE_TOLERANCE = 0.15D; + + private BlockPos targetHole; + private BlockPos startingHole; + + public HoleSnap() { + super("HoleSnap", "Moves you into nearby holes", Category.MOVEMENT); + } + + @Override + public void onEnable() { + LocalPlayer player = mc.player; + Level level = mc.level; + + targetHole = null; + startingHole = null; + + if (player == null || level == null || nolongerhuman.holeManager == null) { + disable(); + return; + } + + startingHole = getCurrentHole(player, level); + + if (swapping.getValue() && startingHole != null) { + targetHole = findBestHole(player, level, swappingRange.getValue(), startingHole); + } else { + targetHole = findBestHole(player, level, range.getValue(), null); + } + + if (targetHole == null) { + disable(); + } + } + + @Override + public void onDisable() { + targetHole = null; + startingHole = null; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + Level level = mc.level; + + if (player == null || level == null || nolongerhuman.holeManager == null) { + disable(); + return; + } + + if (targetHole == null || !isAllowedHole(level, targetHole)) { + if (!reRoute.getValue()) { + disable(); + return; + } + + targetHole = findBestHole(player, level, range.getValue(), startingHole); + + if (targetHole == null) { + disable(); + return; + } + } + + if (isCenteredInHole(player, targetHole)) { + player.setDeltaMovement(0.0D, player.getDeltaMovement().y, 0.0D); + + if (disableInHole.getValue()) { + disable(); + } + + return; + } + + moveToHole(player, targetHole); + } + + private void moveToHole(LocalPlayer player, BlockPos hole) { + double targetX = hole.getX() + 0.5D; + double targetZ = hole.getZ() + 0.5D; + + double dx = targetX - player.getX(); + double dz = targetZ - player.getZ(); + + double distance = Math.hypot(dx, dz); + + if (distance <= 1.0E-4D) { + player.setDeltaMovement(0.0D, player.getDeltaMovement().y, 0.0D); + return; + } + + double moveSpeed = Math.min(speed.getValue(), distance); + + player.setDeltaMovement( + dx / distance * moveSpeed, + player.getDeltaMovement().y, + dz / distance * moveSpeed + ); + } + + private BlockPos findBestHole( + LocalPlayer player, + Level level, + double searchRange, + BlockPos ignoredHole + ) { + BlockPos cachedHole = findBestCachedHole(player, level, searchRange, ignoredHole); + + if (cachedHole != null) { + return cachedHole; + } + + return scanForHole(player, level, searchRange, ignoredHole); + } + + private BlockPos findBestCachedHole( + LocalPlayer player, + Level level, + double searchRange, + BlockPos ignoredHole + ) { + List holes = partial.getValue() + ? nolongerhuman.holeManager.getHoles() + : nolongerhuman.holeManager.getNormalHoles(); + + double rangeSq = searchRange * searchRange; + + return holes.stream() + .map(HoleManager.Hole::pos) + .filter(pos -> isAllowedTarget(pos, ignoredHole)) + .filter(pos -> isAllowedHole(level, pos)) + .filter(pos -> horizontalDistanceSq(player, pos) <= rangeSq) + .min(Comparator.comparingDouble(pos -> horizontalDistanceSq(player, pos))) + .orElse(null); + } + + private BlockPos scanForHole( + LocalPlayer player, + Level level, + double searchRange, + BlockPos ignoredHole + ) { + BlockPos origin = player.blockPosition(); + + int radius = (int) Math.ceil(searchRange); + double rangeSq = searchRange * searchRange; + + BlockPos best = null; + double bestDistance = Double.MAX_VALUE; + + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= 1; y++) { + for (int z = -radius; z <= radius; z++) { + BlockPos pos = origin.offset(x, y, z); + + if (!isAllowedTarget(pos, ignoredHole)) { + continue; + } + + if (!isAllowedHole(level, pos)) { + continue; + } + + double distance = horizontalDistanceSq(player, pos); + + if (distance > rangeSq) { + continue; + } + + if (distance < bestDistance) { + bestDistance = distance; + best = pos; + } + } + } + } + + return best; + } + + private boolean isAllowedTarget(BlockPos pos, BlockPos ignoredHole) { + return ignoredHole == null || !pos.equals(ignoredHole); + } + + private boolean isAllowedHole(Level level, BlockPos pos) { + HoleManager.Hole normalHole = nolongerhuman.holeManager.getHole(pos); + + if (normalHole != null && normalHole.holeType() != HoleManager.HoleType.PARTIAL) { + return true; + } + + if (!partial.getValue()) { + return false; + } + + HoleManager.Hole partialHole = nolongerhuman.holeManager.getPartialHole(pos); + + return partialHole != null && partialHole.holeType() == HoleManager.HoleType.PARTIAL; + } + + private BlockPos getCurrentHole(LocalPlayer player, Level level) { + BlockPos feet = player.blockPosition(); + + if (isAllowedHole(level, feet)) { + return feet; + } + + BlockPos below = feet.below(); + + if (isAllowedHole(level, below)) { + return below; + } + + return null; + } + + private boolean isCenteredInHole(LocalPlayer player, BlockPos hole) { + return Math.abs(player.getX() - (hole.getX() + 0.5D)) <= HOLE_TOLERANCE + && Math.abs(player.getZ() - (hole.getZ() + 0.5D)) <= HOLE_TOLERANCE; + } + + private double horizontalDistanceSq(LocalPlayer player, BlockPos pos) { + double dx = player.getX() - (pos.getX() + 0.5D); + double dz = player.getZ() - (pos.getZ() + 0.5D); + + return dx * dx + dz * dz; + } + + @Override + public String getDisplayInfo() { + if (targetHole == null) { + return "None"; + } + + return partial.getValue() ? "Partial" : "Normal"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/InventoryMove.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/InventoryMove.java new file mode 100644 index 0000000..0e602e4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/InventoryMove.java @@ -0,0 +1,273 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import com.mojang.blaze3d.platform.InputConstants; +import me.humanbeing.nolongerhuman.features.modules.Module; +import net.minecraft.client.KeyMapping; +import net.minecraft.client.gui.screens.ChatScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.AbstractCommandBlockEditScreen; +import net.minecraft.client.gui.screens.inventory.AnvilScreen; +import net.minecraft.client.gui.screens.inventory.BookEditScreen; +import net.minecraft.client.gui.screens.inventory.SignEditScreen; +import org.lwjgl.glfw.GLFW; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class InventoryMove extends Module { + public InventoryMove() { + super("InventoryMove", "Allows movement while in inventories", Category.MOVEMENT); + } + + @Override + public void onTick() { + if (mc.player == null || mc.level == null) { + return; + } + + Screen screen = mc.screen; + + if (screen == null || isTypingScreen(screen)) { + return; + } + + long handle = getWindowHandle(); + + if (handle == 0L) { + return; + } + + updateKey(handle, mc.options.keyUp); + updateKey(handle, mc.options.keyDown); + updateKey(handle, mc.options.keyLeft); + updateKey(handle, mc.options.keyRight); + updateKey(handle, mc.options.keyJump); + updateKey(handle, mc.options.keySprint); + } + + private boolean isTypingScreen(Screen screen) { + return screen instanceof ChatScreen + || screen instanceof AbstractCommandBlockEditScreen + || screen instanceof SignEditScreen + || screen instanceof AnvilScreen + || screen instanceof BookEditScreen; + } + + private void updateKey(long windowHandle, KeyMapping keyMapping) { + InputConstants.Key key = getBoundKey(keyMapping); + + if (key == null) { + return; + } + + int keyCode = getKeyCode(key); + + if (keyCode < 0) { + return; + } + + keyMapping.setDown(GLFW.glfwGetKey(windowHandle, keyCode) == GLFW.GLFW_PRESS); + } + + private InputConstants.Key getBoundKey(KeyMapping keyMapping) { + InputConstants.Key fallback = null; + + for (Class clazz = keyMapping.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + + if (field.getType() != InputConstants.Key.class) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(keyMapping); + + if (!(value instanceof InputConstants.Key key)) { + continue; + } + + String name = field.getName().toLowerCase(); + + if (!name.contains("default")) { + return key; + } + + fallback = key; + } catch (IllegalAccessException ignored) { + } + } + } + + return fallback; + } + + private int getKeyCode(InputConstants.Key key) { + Integer methodValue = getKeyCodeFromMethod(key); + + if (methodValue != null) { + return methodValue; + } + + Integer fieldValue = getKeyCodeFromField(key); + + if (fieldValue != null) { + return fieldValue; + } + + return -1; + } + + private Integer getKeyCodeFromMethod(InputConstants.Key key) { + for (Method method : key.getClass().getDeclaredMethods()) { + if (method.getParameterCount() != 0) { + continue; + } + + if (method.getReturnType() != int.class && method.getReturnType() != Integer.class) { + continue; + } + + String name = method.getName().toLowerCase(); + + if (!name.contains("value") && !name.contains("code")) { + continue; + } + + try { + method.setAccessible(true); + + Object value = method.invoke(key); + + if (value instanceof Number number) { + return number.intValue(); + } + } catch (ReflectiveOperationException ignored) { + } + } + + return null; + } + + private Integer getKeyCodeFromField(InputConstants.Key key) { + for (Class clazz = key.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + + if (field.getType() != int.class && field.getType() != Integer.class) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(key); + + if (value instanceof Number number) { + return number.intValue(); + } + } catch (IllegalAccessException ignored) { + } + } + } + + return null; + } + + private long getWindowHandle() { + Object window = mc.getWindow(); + + Long methodValue = getWindowHandleFromMethod(window); + + if (methodValue != null) { + return methodValue; + } + + Long fieldValue = getWindowHandleFromField(window); + + if (fieldValue != null) { + return fieldValue; + } + + return 0L; + } + + private Long getWindowHandleFromMethod(Object window) { + for (Method method : window.getClass().getDeclaredMethods()) { + if (method.getParameterCount() != 0) { + continue; + } + + if (method.getReturnType() != long.class && method.getReturnType() != Long.class) { + continue; + } + + String name = method.getName().toLowerCase(); + + if (!name.contains("window") && !name.contains("handle")) { + continue; + } + + try { + method.setAccessible(true); + + Object value = method.invoke(window); + + if (value instanceof Number number) { + long handle = number.longValue(); + + if (handle != 0L) { + return handle; + } + } + } catch (ReflectiveOperationException ignored) { + } + } + + return null; + } + + private Long getWindowHandleFromField(Object window) { + for (Class clazz = window.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + + if (field.getType() != long.class && field.getType() != Long.class) { + continue; + } + + String name = field.getName().toLowerCase(); + + if (!name.contains("window") && !name.contains("handle")) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(window); + + if (value instanceof Number number) { + long handle = number.longValue(); + + if (handle != 0L) { + return handle; + } + } + } catch (IllegalAccessException ignored) { + } + } + } + + return null; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/LongJump.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/LongJump.java new file mode 100644 index 0000000..416d5ef --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/LongJump.java @@ -0,0 +1,135 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.phys.Vec3; + +public class LongJump extends Module { + + private static final double BASE_JUMP_Y = 0.40123128; + + private final Setting speed = num("Speed", 0.272, 0.1, 2.0); + private final Setting autoDisable = bool("AutoDisable", false); + private final Setting pauseNoAccel = bool("PauseNoAccel", true); + + private boolean jumping; + private boolean leftGround; + + public LongJump() { + super("LongJump", "Launches the player a long distance", Category.MOVEMENT); + } + + @Override + public void onEnable() { + jumping = false; + leftGround = false; + setNoAccelPaused(true); + } + + @Override + public void onDisable() { + jumping = false; + leftGround = false; + setNoAccelPaused(false); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + boolean moving = player.zza != 0.0F || player.xxa != 0.0F; + + if (player.onGround() && moving && !jumping) { + Vec3 velocity = player.getDeltaMovement(); + player.setDeltaMovement(velocity.x, getJumpMotionY(player), velocity.z); + + jumping = true; + leftGround = false; + } + + if (!jumping) return; + + if (!player.onGround()) { + leftGround = true; + } + + applyHorizontalSpeed(player); + + if (leftGround && player.onGround()) { + jumping = false; + leftGround = false; + + if (autoDisable.getValue()) { + disable(); + } + } + } + + public double getBaseMoveSpeed() { + return speed.getValue(); + } + + public boolean isGrimJumping() { + return isEnabled() && jumping; + } + + private double getJumpMotionY(LocalPlayer player) { + double jump = BASE_JUMP_Y; + + MobEffectInstance jumpBoost = player.getEffect(MobEffects.JUMP_BOOST); + if (jumpBoost != null) { + jump += (jumpBoost.getAmplifier() + 1) * 0.1; + } + + return jump; + } + + private void applyHorizontalSpeed(LocalPlayer player) { + double yaw = Math.toRadians(getMoveYaw(player)); + double moveSpeed = getBaseMoveSpeed(); + + Vec3 velocity = player.getDeltaMovement(); + + player.setDeltaMovement( + -Math.sin(yaw) * moveSpeed, + velocity.y, + Math.cos(yaw) * moveSpeed + ); + } + + private float getMoveYaw(LocalPlayer player) { + float yaw = player.getYRot(); + float forward = Math.signum(player.zza); + float strafe = Math.signum(player.xxa); + + if (forward == 0.0F && strafe == 0.0F) { + return yaw; + } + + if (forward != 0.0F) { + if (strafe > 0.0F) { + yaw += forward > 0.0F ? -45.0F : 45.0F; + } else if (strafe < 0.0F) { + yaw += forward > 0.0F ? 45.0F : -45.0F; + } + + if (forward < 0.0F) { + yaw += 180.0F; + } + } else { + yaw += strafe > 0.0F ? -90.0F : 90.0F; + } + + return yaw; + } + + private void setNoAccelPaused(boolean paused) { + if (!pauseNoAccel.getValue()) return; + + + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/NoJumpDelay.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/NoJumpDelay.java new file mode 100644 index 0000000..ae65f85 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/NoJumpDelay.java @@ -0,0 +1,74 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +public class NoJumpDelay extends Module { + public static NoJumpDelay INSTANCE; + + private final Setting ticks = num("Ticks", 0, 0, 20); + + public NoJumpDelay() { + super("NoJumpDelay", "Changes the delay between jumps", Category.MOVEMENT); + INSTANCE = this; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + setJumpDelay(player, ticks.getValue()); + } + + private void setJumpDelay(LocalPlayer player, int maxTicks) { + for (Class clazz = player.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + + if (field.getType() != int.class) { + continue; + } + + String name = field.getName().toLowerCase(); + + if (!isJumpDelayField(name)) { + continue; + } + + try { + field.setAccessible(true); + + int value = field.getInt(player); + + if (value > maxTicks) { + field.setInt(player, maxTicks); + } + } catch (Throwable ignored) { + } + } + } + } + + private boolean isJumpDelayField(String name) { + return name.contains("jump") + && (name.contains("delay") + || name.contains("time") + || name.contains("trigger") + || name.contains("ticks")); + } + + @Override + public String getDisplayInfo() { + return String.valueOf(ticks.getValue()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/NoSlow.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/NoSlow.java new file mode 100644 index 0000000..ea9c47d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/NoSlow.java @@ -0,0 +1,491 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.event.impl.entity.player.TravelEvent; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundContainerClickPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.Vec3; + +public class NoSlow extends Module { + private static NoSlow INSTANCE; + + private static final double VANILLA_USE_ITEM_SLOWDOWN = 0.2D; + private static final double CANCEL_USE_ITEM_SLOWDOWN_MULTIPLIER = 1.0D / VANILLA_USE_ITEM_SLOWDOWN; + + public final Setting items = bool("Items", true); + public final Setting itemMultiplier = num("ItemMultiplier", 5.0, 1.0, 10.0); + + public final Setting eating = bool("Eating", true); + public final Setting eatingBoostAmount = num("EatingBoostAmount", 0.26, 0.05, 0.5); + + public final Setting soulSand = bool("SoulSand", false); + public final Setting slimeBlocks = bool("SlimeBlocks", false); + public final Setting honeyBlocks = bool("HoneyBlocks", false); + + public final Setting ncpStrict = bool("NCPStrict", false); + public final Setting airStrict = bool("AirStrict", false); + public final Setting keepSprint = bool("KeepSprint", true); + + private boolean sneaking = false; + private int ncpTicks = 0; + private boolean blockHooksActive = false; + + public NoSlow() { + super("NoSlow", "Removes slowdown received from certain actions", Category.MOVEMENT); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + sneaking = false; + ncpTicks = 0; + blockHooksActive = updateBlockHookState(); + } + + @Override + public void onDisable() { + LocalPlayer player = mc.player; + + if (player != null && sneaking) { + sendSneakRelease(player); + } + + sneaking = false; + ncpTicks = 0; + blockHooksActive = false; + } + + @Subscribe + public void onTravel(TravelEvent event) { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + if (shouldSlow()) { + return; + } + + if (!shouldCancelUsingItemSlowdown(player)) { + return; + } + + double multiplier = getUseItemMultiplier(); + + event.setX(event.getX() * multiplier); + event.setZ(event.getZ() * multiplier); + + if (keepSprint.getValue() && hasMovementInput(player) && !player.isSprinting()) { + player.setSprinting(true); + } + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + blockHooksActive = updateBlockHookState(); + + handleAirStrict(player); + handleSprint(player); + handleEatingBoost(player); + } + + @Subscribe + public void onPacketSend(PacketEvent.Send event) { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return; + } + + if (!player.isUsingItem()) { + return; + } + + if (!shouldUseNcpStrict(player)) { + return; + } + + Packet packet = event.getPacket(); + + if (packet instanceof ServerboundMovePlayerPacket) { + handleNcpMovePacket(player); + return; + } + + if (packet instanceof ServerboundContainerClickPacket) { + handleNcpContainerPacket(player); + } + } + + private void handleSprint(LocalPlayer player) { + if (!keepSprint.getValue()) { + return; + } + + if (shouldCancelUsingItemSlowdown(player) && hasMovementInput(player) && !player.isSprinting()) { + player.setSprinting(true); + } + } + + private void handleEatingBoost(LocalPlayer player) { + if (!shouldBoostEating(player)) { + return; + } + + if (!hasMovementInput(player)) { + return; + } + + double boostSpeed = getEatingBoostSpeed(player); + Vec3 boosted = forward(player, boostSpeed); + Vec3 current = player.getDeltaMovement(); + + player.setDeltaMovement( + boosted.x, + current.y, + boosted.z + ); + } + + private void handleAirStrict(LocalPlayer player) { + boolean shouldSneak = + player.isUsingItem() + && !isEating(player) + && !player.isPassenger() + && !player.isShiftKeyDown() + && airStrict.getValue() + && items.getValue(); + + if (shouldSneak && !sneaking) { + sendSneakPress(player); + sneaking = true; + return; + } + + if (sneaking && !shouldSneak) { + sendSneakRelease(player); + sneaking = false; + } + } + + private void handleNcpMovePacket(LocalPlayer player) { + ncpTicks++; + + if (ncpTicks < 2) { + return; + } + + ncpTicks = 0; + + player.connection.send(new ServerboundSetCarriedItemPacket( + player.getInventory().getSelectedSlot() + )); + } + + private void handleNcpContainerPacket(LocalPlayer player) { + if (isEating(player)) { + return; + } + + if (player.isUsingItem()) { + player.stopUsingItem(); + } + + if (player.isSprinting()) { + player.connection.send(new ServerboundPlayerCommandPacket( + player, + ServerboundPlayerCommandPacket.Action.STOP_SPRINTING + )); + } + + if (sneaking || player.isShiftKeyDown()) { + sendSneakRelease(player); + sneaking = false; + } + } + + private boolean updateBlockHookState() { + return shouldCancelSoulSandSlowdown() + || shouldCancelSlimeSlowdown() + || shouldCancelHoneySlowdown(); + } + + private boolean shouldCancelUsingItemSlowdown(LocalPlayer player) { + if (!player.isUsingItem()) { + return false; + } + + if (shouldBoostEating(player)) { + return true; + } + + return items.getValue(); + } + + private double getCurrentMultiplier(LocalPlayer player) { + if (shouldBoostEating(player)) { + return CANCEL_USE_ITEM_SLOWDOWN_MULTIPLIER; + } + + if (player.isUsingItem() && items.getValue()) { + return itemMultiplier.getValue(); + } + + return 1.0D; + } + + private boolean shouldBoostEating(LocalPlayer player) { + return eating.getValue() && isEating(player); + } + + private boolean shouldUseNcpStrict(LocalPlayer player) { + if (!player.isUsingItem()) { + return false; + } + + if (isEating(player)) { + return false; + } + + return ncpStrict.getValue() && items.getValue(); + } + + private boolean isEating(LocalPlayer player) { + if (!player.isUsingItem()) { + return false; + } + + ItemStack stack = player.getUseItem(); + + if (isFood(stack)) { + return true; + } + + ItemStack mainHand = player.getMainHandItem(); + + if (isFood(mainHand)) { + return true; + } + + ItemStack offHand = player.getOffhandItem(); + + return isFood(offHand); + } + + private boolean isFood(ItemStack stack) { + return !stack.isEmpty() && stack.has(DataComponents.FOOD); + } + + private boolean hasMovementInput(LocalPlayer player) { + return Math.abs(player.zza) > 0.0001F || Math.abs(player.xxa) > 0.0001F; + } + + private Vec3 forward(LocalPlayer player, double speed) { + float forward = player.zza; + float strafe = player.xxa; + + if (forward == 0.0F && strafe == 0.0F) { + return Vec3.ZERO; + } + + float yaw = player.getYRot(); + + if (forward != 0.0F) { + if (strafe > 0.0F) { + yaw += forward > 0.0F ? -45.0F : 45.0F; + } else if (strafe < 0.0F) { + yaw += forward > 0.0F ? 45.0F : -45.0F; + } + + strafe = 0.0F; + + if (forward > 0.0F) { + forward = 1.0F; + } else if (forward < 0.0F) { + forward = -1.0F; + } + } + + double radians = Math.toRadians(yaw + 90.0F); + double sin = Math.sin(radians); + double cos = Math.cos(radians); + + return new Vec3( + forward * speed * cos + strafe * speed * sin, + 0.0D, + forward * speed * sin - strafe * speed * cos + ); + } + + private double getEatingBoostSpeed(LocalPlayer player) { + double speed = eatingBoostAmount.getValue(); + + MobEffectInstance speedEffect = player.getEffect(MobEffects.SPEED); + + if (speedEffect != null) { + speed *= 1.0D + 0.2D * (speedEffect.getAmplifier() + 1); + } + + return speed; + } + + public boolean shouldSlow() { + return !isEnabled(); + } + + public boolean shouldNoSlowSoulSand() { + return isEnabled() && soulSand.getValue(); + } + + public boolean shouldNoSlowSlimeBlocks() { + return isEnabled() && slimeBlocks.getValue(); + } + + public boolean shouldNoSlowHoneyBlocks() { + return isEnabled() && honeyBlocks.getValue(); + } + + public static boolean shouldCancelItemSlowdown() { + LocalPlayer player = mc.player; + + return INSTANCE != null + && INSTANCE.isEnabled() + && player != null + && INSTANCE.shouldCancelUsingItemSlowdown(player); + } + + public static boolean shouldCancelEatingSlowdown() { + LocalPlayer player = mc.player; + + return INSTANCE != null + && INSTANCE.isEnabled() + && player != null + && INSTANCE.shouldBoostEating(player); + } + + public static boolean shouldCancelSoulSandSlowdown() { + return INSTANCE != null + && INSTANCE.shouldNoSlowSoulSand(); + } + + public static boolean shouldCancelSlimeSlowdown() { + return INSTANCE != null + && INSTANCE.shouldNoSlowSlimeBlocks(); + } + + public static boolean shouldCancelHoneySlowdown() { + return INSTANCE != null + && INSTANCE.shouldNoSlowHoneyBlocks(); + } + + public static double getUseItemMultiplier() { + LocalPlayer player = mc.player; + + if (INSTANCE == null || !INSTANCE.isEnabled() || player == null) { + return 1.0D; + } + + return INSTANCE.getCurrentMultiplier(player); + } + + private void sendSneakPress(LocalPlayer player) { + sendPlayerCommand( + player, + "PRESS_SHIFT_KEY", + "START_SNEAKING" + ); + } + + private void sendSneakRelease(LocalPlayer player) { + sendPlayerCommand( + player, + "RELEASE_SHIFT_KEY", + "STOP_SNEAKING" + ); + } + + private void sendPlayerCommand(LocalPlayer player, String... actionNames) { + ServerboundPlayerCommandPacket.Action action = findAction(actionNames); + + if (action == null) { + return; + } + + player.connection.send(new ServerboundPlayerCommandPacket(player, action)); + } + + private ServerboundPlayerCommandPacket.Action findAction(String... names) { + for (String name : names) { + try { + return Enum.valueOf(ServerboundPlayerCommandPacket.Action.class, name); + } catch (IllegalArgumentException ignored) { + } + } + + return null; + } + + @Override + public String getDisplayInfo() { + StringBuilder builder = new StringBuilder(); + + if (items.getValue()) { + builder.append("Items"); + } + + if (eating.getValue()) { + appendInfo(builder, "Eating Boost"); + } + + if (blockHooksActive) { + appendInfo(builder, "Blocks"); + } else { + if (soulSand.getValue()) { + appendInfo(builder, "Soul"); + } + + if (slimeBlocks.getValue()) { + appendInfo(builder, "Slime"); + } + + if (honeyBlocks.getValue()) { + appendInfo(builder, "Honey"); + } + } + + if (builder.isEmpty()) { + return "None"; + } + + return builder.toString(); + } + + private void appendInfo(StringBuilder builder, String text) { + if (!builder.isEmpty()) { + builder.append(", "); + } + + builder.append(text); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/ReverseStep.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/ReverseStep.java new file mode 100644 index 0000000..5b803ac --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/ReverseStep.java @@ -0,0 +1,268 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.models.Timer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +public class ReverseStep extends Module { + public enum Mode { + Instant, + Shift, + CorrectionShift + } + + private static final double GROUND_SCAN_EXTRA = 0.05; + private static final double GROUND_SCAN_STEP = 0.01; + + private final Setting mode = mode("Mode", Mode.Shift); + private final Setting height = num("Height", 1.2, 0.0, 12.0); + private final Setting always = bool("Always", true); + + private final Timer cooldown = new Timer(); + + private boolean wasOnGround; + private boolean shifting; + private double fallStartY; + + public ReverseStep() { + super("ReverseStep", "Pulls you down only after stepping off a block", Category.MOVEMENT); + } + + @Override + public void onEnable() { + cooldown.reset(); + wasOnGround = false; + shifting = false; + + if (mc.player != null) { + fallStartY = mc.player.getY(); + } else { + fallStartY = 0.0; + } + } + + @Override + public void onDisable() { + shifting = false; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + boolean onGround = player.onGround(); + boolean steppedOffBlock = hasSteppedOffBlock(player, onGround); + + if (shouldSkip(player)) { + shifting = false; + wasOnGround = onGround; + + if (onGround) { + fallStartY = player.getY(); + } + + return; + } + + double maxHeight = height.getValue(); + + if (maxHeight <= 0.0) { + shifting = false; + wasOnGround = onGround; + fallStartY = player.getY(); + return; + } + + if (onGround) { + shifting = false; + fallStartY = player.getY(); + } + + switch (mode.getValue()) { + case Instant -> handleInstant(player, level, maxHeight, steppedOffBlock); + case Shift -> handleShift(player, level, maxHeight, steppedOffBlock, false); + case CorrectionShift -> handleShift(player, level, maxHeight, steppedOffBlock, true); + } + + wasOnGround = onGround; + } + + private boolean hasSteppedOffBlock(LocalPlayer player, boolean onGround) { + if (!wasOnGround || onGround) { + return false; + } + + Vec3 velocity = player.getDeltaMovement(); + + return velocity.y <= 0.0; + } + + private void handleInstant( + LocalPlayer player, + ClientLevel level, + double maxHeight, + boolean steppedOffBlock + ) { + if (!steppedOffBlock && !always.getValue()) { + return; + } + + if (!cooldown.passedMs(300L)) { + return; + } + + double drop = getAllowedDrop(player, level, maxHeight); + + if (drop <= 0.0) { + return; + } + + Vec3 velocity = player.getDeltaMovement(); + + player.setDeltaMovement( + velocity.x, + -drop, + velocity.z + ); + + shifting = true; + cooldown.reset(); + } + + private void handleShift( + LocalPlayer player, + ClientLevel level, + double maxHeight, + boolean steppedOffBlock, + boolean correction + ) { + if (!shifting) { + if (!steppedOffBlock && !always.getValue()) { + return; + } + + if (!cooldown.passedMs(300L)) { + return; + } + + double drop = getAllowedDrop(player, level, maxHeight); + + if (drop <= 0.0) { + return; + } + + shifting = true; + } + + if (player.onGround()) { + shifting = false; + cooldown.reset(); + fallStartY = player.getY(); + return; + } + + double remaining = getRemainingReverseStepDistance(player, maxHeight); + + if (remaining <= 0.0) { + shifting = false; + cooldown.reset(); + return; + } + + double drop = getAllowedDrop(player, level, remaining); + + if (drop <= 0.0) { + shifting = false; + cooldown.reset(); + return; + } + + Vec3 velocity = player.getDeltaMovement(); + + if (correction) { + player.setDeltaMovement( + 0.0, + -drop, + 0.0 + ); + } else { + player.setDeltaMovement( + velocity.x, + -drop, + velocity.z + ); + } + } + + private boolean shouldSkip(LocalPlayer player) { + return player.isPassenger() + || player.isFallFlying() + || player.onClimbable() + || player.isInLava() + || player.isInWater() + || mc.options.keyJump.isDown() + || mc.options.keyShift.isDown(); + } + + private double getAllowedDrop(LocalPlayer player, ClientLevel level, double maxHeight) { + if (maxHeight <= 0.0) { + return 0.0; + } + + double remaining = getRemainingReverseStepDistance(player, maxHeight); + + if (remaining <= 0.0) { + return 0.0; + } + + double allowedDistance = Math.min(maxHeight, remaining); + + + double groundDistance = distanceToGround( + player, + level, + allowedDistance + GROUND_SCAN_EXTRA + ); + + if (groundDistance <= 0.0) { + return 0.0; + } + + if (groundDistance > allowedDistance + GROUND_SCAN_EXTRA) { + return 0.0; + } + + return Math.min(allowedDistance, groundDistance); + } + + private double getRemainingReverseStepDistance(LocalPlayer player, double maxHeight) { + double fallen = Math.max(0.0, fallStartY - player.getY()); + + return Math.max(0.0, maxHeight - fallen); + } + + private double distanceToGround(LocalPlayer player, ClientLevel level, double maxDistance) { + if (maxDistance <= 0.0) { + return -1.0; + } + + AABB box = player.getBoundingBox(); + + for (double offset = GROUND_SCAN_STEP; offset <= maxDistance; offset += GROUND_SCAN_STEP) { + if (!level.noCollision(player, box.move(0.0, -offset, 0.0))) { + return offset; + } + } + + return -1.0; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Speed.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Speed.java new file mode 100644 index 0000000..affda08 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Speed.java @@ -0,0 +1,648 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.Vec3; + +public class Speed extends Module { + public enum Mode { + Strafe, + Strict, + StrafeVanilla, + StrictFast + } + + public final Setting speedMode = mode("Mode", Mode.StrictFast); + + public final Setting autoJump = bool("AutoJump", true); + public final Setting instantStop = bool("InstantStop", true); + public final Setting speedInWater = bool("SpeedInWater", false); + public final Setting useSpeedEffects = bool("SpeedEffects", true); + + public final Setting speedCap = bool("SpeedCap", true); + public final Setting maxSpeed = num("MaxSpeed", 0.28, 0.20, 2.0); + + public final Setting strafeMultiplier = num("StrafeMultiplier", 1.16, 1.0, 1.6); + public final Setting strafeJumpHeight = num("StrafeJumpHeight", 0.42, 0.20, 0.80); + public final Setting strafeJumpDelay = num("StrafeJumpDelay", 0.0, 0.0, 30.0); + public final Setting strafeAirFriction = num("StrafeAirFriction", 190.0, 120.0, 260.0); + + public final Setting strictMultiplier = num("StrictMultiplier", 1.18, 1.0, 1.6); + public final Setting strictFastMultiplier = num("StrictFastMultiplier", 1.38, 1.0, 2.0); + public final Setting strictLimit = num("StrictLimit", 0.44, 0.20, 1.0); + public final Setting strictFastLimit = num("StrictFastLimit", 0.49, 0.20, 1.2); + public final Setting strictAirFriction = num("StrictAirFriction", 159.0, 80.0, 260.0); + + public final Setting setbackProtection = bool("SetbackProtection", true); + public final Setting setbackThreshold = num("SetbackThreshold", 0.08, 0.01, 0.3); + public final Setting cooldownTicks = num("CooldownTicks", 12.0, 1.0, 60.0); + + public final Setting explosionBoost = bool("ExplosionBoost", false); + public final Setting explosionBoostMultiplier = num("ExplosionMultiplier", 1.15, 0.1, 3.0); + public final Setting explosionBoostDuration = num("ExplosionDuration", 10.0, 1.0, 60.0); + public final Setting explosionBoostMax = num("ExplosionMax", 1.2, 0.1, 5.0); + public final Setting explosionBoostDecay = num("ExplosionDecay", 0.90, 0.1, 1.0); + public final Setting explosionDetectThreshold = num("ExplosionDetect", 0.75, 0.1, 5.0); + + private int stage = 1; + private int strictTicks = 0; + private int cooldown = 0; + private int jumpDelayTicks = 0; + + private double moveSpeed = 0.0; + private double lastDistance = 0.0; + private double lastAppliedSpeed = 0.0; + + private boolean accelerated = false; + private boolean jumpedThisGround = false; + + private int activeExplosionTicks = 0; + private double activeExplosionBoost = 0.0; + private Vec3 previousHorizontalMotion = Vec3.ZERO; + + public Speed() { + super("Speed", "Strafe movement speed", Category.MOVEMENT); + } + + @Override + public void onEnable() { + resetState(); + } + + @Override + public void onDisable() { + LocalPlayer player = mc.player; + + if (player != null && instantStop.getValue()) { + stopHorizontalMovement(player); + } + + resetState(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + resetState(); + return; + } + + if (jumpDelayTicks > 0) { + jumpDelayTicks--; + } + + if (!player.onGround()) { + jumpedThisGround = false; + } + + updateLastDistance(player); + updateExplosionBoost(player); + updateSetbackProtection(player); + + if (cooldown > 0) { + cooldown--; + + if (instantStop.getValue() && !isMoving(player)) { + stopHorizontalMovement(player); + } + + return; + } + + if (isMovementBlocked(player, level)) { + resetMovementStateOnly(); + return; + } + + if (!isMoving(player)) { + if (instantStop.getValue() && activeExplosionTicks <= 0) { + stopHorizontalMovement(player); + } + + resetMovementStateOnly(); + return; + } + + player.setSprinting(true); + + switch (speedMode.getValue()) { + case Strafe -> applyStrafeSpeed(player); + case Strict -> applyStrictSpeed(player, false); + case StrafeVanilla -> applyStrafeVanillaSpeed(player); + case StrictFast -> applyStrictSpeed(player, true); + } + } + + private void applyStrafeSpeed(LocalPlayer player) { + double baseSpeed = getBaseMoveSpeed(player); + + if (player.onGround()) { + stage = 2; + + if (autoJump.getValue()) { + applyStrafeJump(player); + } + + double multiplier = strafeMultiplier.getValue(); + + if (accelerated) { + multiplier = Math.max(multiplier, 1.20); + } + + moveSpeed = baseSpeed * multiplier; + accelerated = !accelerated; + } else if (stage == 2) { + double adjusted = 0.78 * (lastDistance - baseSpeed); + moveSpeed = lastDistance - adjusted; + stage = 3; + } else { + moveSpeed = Math.max(baseSpeed, lastDistance - lastDistance / strafeAirFriction.getValue()); + stage++; + } + + moveSpeed = Math.max(moveSpeed, baseSpeed); + moveSpeed = applyExplosionBoost(player, moveSpeed); + moveSpeed = capSpeed(moveSpeed); + applyHorizontalSpeed(player, moveSpeed); + } + + private void applyStrictSpeed(LocalPlayer player, boolean fast) { + double baseSpeed = getBaseMoveSpeed(player); + + if (player.onGround()) { + stage = 2; + + if (autoJump.getValue()) { + applyVanillaJump(player); + } + + moveSpeed = baseSpeed * (fast ? strictFastMultiplier.getValue() : strictMultiplier.getValue()); + } else if (stage == 2) { + double adjusted = 0.66 * (lastDistance - baseSpeed); + moveSpeed = lastDistance - adjusted; + stage = 3; + } else { + moveSpeed = Math.max(baseSpeed, lastDistance - lastDistance / strictAirFriction.getValue()); + stage++; + } + + moveSpeed = Math.max(moveSpeed, baseSpeed); + moveSpeed = applyStrictLimit(player, moveSpeed, fast); + moveSpeed = applyExplosionBoost(player, moveSpeed); + moveSpeed = capSpeed(moveSpeed); + applyHorizontalSpeed(player, moveSpeed); + } + + private void applyStrafeVanillaSpeed(LocalPlayer player) { + double baseSpeed = getBaseMoveSpeed(player); + + if (player.onGround()) { + stage = 2; + + if (autoJump.getValue()) { + applyVanillaJump(player); + } + + moveSpeed = baseSpeed; + } else if (stage == 2) { + moveSpeed = Math.max(baseSpeed, lastDistance); + stage = 3; + } else { + moveSpeed = Math.max(baseSpeed, lastDistance - lastDistance / 159.0); + stage++; + } + + moveSpeed = applyExplosionBoost(player, moveSpeed); + moveSpeed = capSpeed(moveSpeed); + applyHorizontalSpeed(player, moveSpeed); + } + + private double applyStrictLimit(LocalPlayer player, double speed, boolean fast) { + double limit = fast ? strictFastLimit.getValue() : strictLimit.getValue(); + + limit = applyPotionSpeed(player, limit); + + strictTicks++; + + if (strictTicks > 50) { + strictTicks = 0; + } + + if (strictTicks > 25) { + limit *= fast ? 1.08 : 1.04; + } + + return Math.min(speed, limit); + } + + private void applyStrafeJump(LocalPlayer player) { + if (jumpedThisGround) { + return; + } + + if (jumpDelayTicks > 0) { + return; + } + + double jumpMotion = getStrafeJumpMotion(player); + + applyJump(player, jumpMotion); + + jumpedThisGround = true; + jumpDelayTicks = Math.max(0, strafeJumpDelay.getValue().intValue()); + } + + private void applyVanillaJump(LocalPlayer player) { + if (jumpedThisGround) { + return; + } + + if (jumpDelayTicks > 0) { + return; + } + + applyJump(player, getVanillaJumpMotion(player)); + + jumpedThisGround = true; + jumpDelayTicks = Math.max(0, strafeJumpDelay.getValue().intValue()); + } + + private double getStrafeJumpMotion(LocalPlayer player) { + double jump = strafeJumpHeight.getValue(); + + if (!useSpeedEffects.getValue()) { + return jump; + } + + MobEffectInstance jumpBoost = player.getEffect(MobEffects.JUMP_BOOST); + + if (jumpBoost != null) { + jump += (jumpBoost.getAmplifier() + 1) * 0.1; + } + + return jump; + } + + private double getVanillaJumpMotion(LocalPlayer player) { + double jump = 0.42; + + if (!useSpeedEffects.getValue()) { + return jump; + } + + MobEffectInstance jumpBoost = player.getEffect(MobEffects.JUMP_BOOST); + + if (jumpBoost != null) { + jump += (jumpBoost.getAmplifier() + 1) * 0.1; + } + + return jump; + } + + private void applyJump(LocalPlayer player, double yMotion) { + Vec3 current = player.getDeltaMovement(); + + player.setDeltaMovement( + current.x, + yMotion, + current.z + ); + } + + private void applyHorizontalSpeed(LocalPlayer player, double speed) { + Vec3 horizontal = directionSpeed(player, speed); + Vec3 current = player.getDeltaMovement(); + + player.setDeltaMovement( + horizontal.x, + current.y, + horizontal.z + ); + + lastAppliedSpeed = speed; + } + + private void updateSetbackProtection(LocalPlayer player) { + if (!setbackProtection.getValue()) { + return; + } + + if (lastAppliedSpeed <= 0.0) { + return; + } + + if (cooldown > 0) { + return; + } + + double horizontalVelocity = getHorizontalVelocity(player); + + boolean suspiciousStop = + lastAppliedSpeed > 0.35 + && horizontalVelocity < setbackThreshold.getValue() + && lastDistance < setbackThreshold.getValue() + && isMoving(player); + + if (suspiciousStop) { + cooldown = Math.max(1, cooldownTicks.getValue().intValue()); + + resetMovementStateOnly(); + resetExplosionBoost(); + stopHorizontalMovement(player); + } + } + + private void updateExplosionBoost(LocalPlayer player) { + Vec3 currentHorizontalMotion = getHorizontalMotion(player.getDeltaMovement()); + + if (!explosionBoost.getValue()) { + resetExplosionBoost(); + previousHorizontalMotion = currentHorizontalMotion; + return; + } + + Vec3 movementDirection = getMovementDirection(player); + + if (movementDirection.lengthSqr() <= 1.0E-6) { + previousHorizontalMotion = currentHorizontalMotion; + + if (activeExplosionTicks > 0) { + activeExplosionTicks--; + activeExplosionBoost *= explosionBoostDecay.getValue(); + + if (activeExplosionTicks <= 0 || activeExplosionBoost <= 0.01) { + resetExplosionBoost(); + } + } + + return; + } + + Vec3 velocityIncrease = currentHorizontalMotion.subtract(previousHorizontalMotion); + + double currentHorizontalSpeed = getHorizontalSpeed(currentHorizontalMotion); + double forwardIncrease = velocityIncrease.dot(movementDirection); + double currentForwardVelocity = currentHorizontalMotion.dot(movementDirection); + double baseSpeed = getBaseMoveSpeed(player); + + boolean detectedExplosionVelocity = + currentHorizontalSpeed >= explosionDetectThreshold.getValue() + && forwardIncrease > baseSpeed * 0.35 + && currentForwardVelocity > Math.max(baseSpeed, lastAppliedSpeed * 0.75); + + if (detectedExplosionVelocity) { + double calculatedBoost = forwardIncrease * explosionBoostMultiplier.getValue(); + + activeExplosionTicks = Math.max(1, explosionBoostDuration.getValue().intValue()); + activeExplosionBoost = Math.min( + explosionBoostMax.getValue(), + Math.max(activeExplosionBoost, calculatedBoost) + ); + } + + previousHorizontalMotion = currentHorizontalMotion; + + if (activeExplosionTicks > 0) { + activeExplosionTicks--; + activeExplosionBoost *= explosionBoostDecay.getValue(); + + if (activeExplosionTicks <= 0 || activeExplosionBoost <= 0.01) { + resetExplosionBoost(); + } + } + } + + private double applyExplosionBoost(LocalPlayer player, double speed) { + if (!explosionBoost.getValue()) { + return speed; + } + + if (activeExplosionTicks <= 0) { + return speed; + } + + if (activeExplosionBoost <= 0.0) { + return speed; + } + + if (!isMoving(player)) { + return speed; + } + + return Math.min( + speed + activeExplosionBoost, + explosionBoostMax.getValue() + ); + } + + private boolean isMovementBlocked(LocalPlayer player, ClientLevel level) { + if (player.fallDistance >= 5.0F) { + return true; + } + + if (player.isShiftKeyDown()) { + return true; + } + + if (player.onClimbable()) { + return true; + } + + if (level.getBlockState(player.blockPosition()).getBlock() == Blocks.COBWEB) { + return true; + } + + if (player.getAbilities().flying) { + return true; + } + + if (player.isFallFlying()) { + return true; + } + + return (player.isInWater() || player.isInLava()) && !speedInWater.getValue(); + } + + private void updateLastDistance(LocalPlayer player) { + double deltaX = player.getX() - player.xOld; + double deltaZ = player.getZ() - player.zOld; + + lastDistance = Math.sqrt(deltaX * deltaX + deltaZ * deltaZ); + } + + private double getBaseMoveSpeed(LocalPlayer player) { + return applyPotionSpeed(player, 0.2873); + } + + private double applyPotionSpeed(LocalPlayer player, double base) { + if (!useSpeedEffects.getValue()) { + return base; + } + + MobEffectInstance speedEffect = player.getEffect(MobEffects.SPEED); + + if (speedEffect != null) { + base *= 1.0 + 0.2 * (speedEffect.getAmplifier() + 1); + } + + MobEffectInstance slownessEffect = player.getEffect(MobEffects.SLOWNESS); + + if (slownessEffect != null) { + base /= 1.0 + 0.2 * (slownessEffect.getAmplifier() + 1); + } + + return base; + } + + private double capSpeed(double speed) { + if (!speedCap.getValue()) { + return speed; + } + + if (explosionBoost.getValue() && activeExplosionTicks > 0) { + return Math.min(speed, Math.max(maxSpeed.getValue(), explosionBoostMax.getValue())); + } + + return Math.min(speed, maxSpeed.getValue()); + } + + private Vec3 directionSpeed(LocalPlayer player, double speed) { + Vec3 direction = getMovementDirection(player); + + if (direction.lengthSqr() <= 1.0E-6) { + return Vec3.ZERO; + } + + return direction.scale(speed); + } + + private Vec3 getMovementDirection(LocalPlayer player) { + float forward = player.zza; + float strafe = player.xxa; + + if (forward == 0.0F && strafe == 0.0F) { + return Vec3.ZERO; + } + + float yaw = player.getYRot(); + + if (forward != 0.0F) { + if (strafe > 0.0F) { + yaw += forward > 0.0F ? -45.0F : 45.0F; + } else if (strafe < 0.0F) { + yaw += forward > 0.0F ? 45.0F : -45.0F; + } + + strafe = 0.0F; + + if (forward > 0.0F) { + forward = 1.0F; + } else if (forward < 0.0F) { + forward = -1.0F; + } + } + + double radians = Math.toRadians(yaw + 90.0F); + double cos = Math.cos(radians); + double sin = Math.sin(radians); + + Vec3 direction = new Vec3( + forward * cos + strafe * sin, + 0.0, + forward * sin - strafe * cos + ); + + if (direction.lengthSqr() <= 1.0E-6) { + return Vec3.ZERO; + } + + return direction.normalize(); + } + + private boolean isMoving(LocalPlayer player) { + return Math.abs(player.zza) > 0.0001F || Math.abs(player.xxa) > 0.0001F; + } + + private double getHorizontalVelocity(LocalPlayer player) { + return getHorizontalSpeed(player.getDeltaMovement()); + } + + private Vec3 getHorizontalMotion(Vec3 velocity) { + return new Vec3( + velocity.x, + 0.0, + velocity.z + ); + } + + private double getHorizontalSpeed(Vec3 velocity) { + return Math.sqrt( + velocity.x * velocity.x + + velocity.z * velocity.z + ); + } + + private void stopHorizontalMovement(LocalPlayer player) { + Vec3 current = player.getDeltaMovement(); + + player.setDeltaMovement( + 0.0, + current.y, + 0.0 + ); + } + + private void resetState() { + stage = 1; + strictTicks = 0; + cooldown = 0; + jumpDelayTicks = 0; + + moveSpeed = 0.0; + lastDistance = 0.0; + lastAppliedSpeed = 0.0; + + accelerated = false; + jumpedThisGround = false; + + previousHorizontalMotion = Vec3.ZERO; + + resetExplosionBoost(); + } + + private void resetMovementStateOnly() { + stage = 1; + strictTicks = 0; + + moveSpeed = 0.0; + lastAppliedSpeed = 0.0; + + accelerated = false; + } + + private void resetExplosionBoost() { + activeExplosionTicks = 0; + activeExplosionBoost = 0.0; + } + + @Override + public String getDisplayInfo() { + if (cooldown > 0) { + return "Cooldown"; + } + + if (explosionBoost.getValue() && activeExplosionTicks > 0) { + return speedMode.getValue().name() + "+Explode"; + } + + return speedMode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Sprint.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Sprint.java new file mode 100644 index 0000000..1c6317e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Sprint.java @@ -0,0 +1,132 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.effect.MobEffects; + +public class Sprint extends Module { + + public enum Mode { + LEGIT, + RAGE + } + + private static final String ROT_ID = "sprint"; + private static final int ROT_PRIORITY = 2; + + private final Setting mode = mode("Mode", Mode.RAGE); + private final Setting rotate = bool("Rotate", false); + + public Sprint() { + super("Sprint", "Always sprints when possible", Category.MOVEMENT); + } + + @Override + public void onEnable() { + LocalPlayer player = mc.player; + if (player != null) { + player.setSprinting(shouldSprint(player)); + } + } + + @Override + public void onDisable() { + LocalPlayer player = mc.player; + if (player != null) { + player.setSprinting(false); + } + + nolongerhuman.rotationManager.endRotation(ROT_ID, ROT_PRIORITY); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + if (shouldSprint(player)) { + player.setSprinting(true); + + if (rotate.getValue() && (player.zza != 0.0F || player.xxa != 0.0F)) { + nolongerhuman.rotationManager.applyRotation( + ROT_ID, + ROT_PRIORITY, + movementYaw(player), + player.getXRot() + ); + } + } + } + + public boolean shouldSprint() { + LocalPlayer player = mc.player; + return player != null && shouldSprint(player); + } + + private boolean shouldSprint(LocalPlayer player) { + if (!canStartSprinting(player)) return false; + if (player.isInWater() && !player.isUnderWater()) return false; + if (player.isSwimming() && !player.onGround() + && !mc.options.keyShift.isDown() + && !player.isInWater()) { + return false; + } + + if (mode.getValue() == Mode.RAGE) { + if (player.isUnderWater()) { + return player.zza != 0.0F || player.xxa != 0.0F; + } + + return Math.abs(player.zza) >= 0.8F || Math.abs(player.xxa) >= 0.8F; + } + + if (Math.abs(player.zza) <= 0.8F) return false; + if (player.isUsingItem() && !noSlowItemsActive()) return false; + if (player.hasEffect(MobEffects.BLINDNESS)) return false; + if (player.isFallFlying()) return false; + if (player.horizontalCollision && !player.minorHorizontalCollision) return false; + + return player.zza > 1.0E-5F; + } + + private boolean noSlowItemsActive() { + Module module = nolongerhuman.moduleManager.getModuleByClass(NoSlow.class); + return module instanceof NoSlow noSlow && noSlow.isEnabled() && noSlow.items.getValue(); + } + + private boolean canStartSprinting(LocalPlayer player) { + return !player.isUsingItem() + && (player.getFoodData().getFoodLevel() > 6.0F || player.getAbilities().mayfly) + && !player.hasEffect(MobEffects.BLINDNESS) + && !player.isFallFlying() + && !player.isPassenger(); + } + + private float movementYaw(LocalPlayer player) { + float yaw = player.getYRot(); + float forward = Math.signum(player.zza); + float strafe = Math.signum(player.xxa); + + if (forward == 0.0F && strafe == 0.0F) { + return yaw; + } + + if (forward != 0.0F) { + if (strafe > 0.0F) { + yaw += forward > 0.0F ? -45.0F : 45.0F; + } else if (strafe < 0.0F) { + yaw += forward > 0.0F ? 45.0F : -45.0F; + } + + if (forward < 0.0F) { + yaw += 180.0F; + } + } else { + yaw += strafe > 0.0F ? -90.0F : 90.0F; + } + + return yaw; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Step.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Step.java new file mode 100644 index 0000000..00ffc8b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/Step.java @@ -0,0 +1,93 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.Attributes; + +public class Step extends Module { + + public enum Mode { + VANILLA, + NCP + } + + private static final double VANILLA_STEP_HEIGHT = 0.6; + + private final Setting mode = mode("Mode", Mode.VANILLA); + private final Setting height = num("Height", 1.2, 1.0, 6.0); + private final Setting useTimer = bool("UseTimer", true); + + private boolean resetTimer; + + public Step() { + super("Step", "Instantly climb a customizable number of blocks", Category.MOVEMENT); + } + + @Override + public void onDisable() { + LocalPlayer player = mc.player; + if (player != null) { + setStepHeight(player, VANILLA_STEP_HEIGHT); + } + + resetTimer = false; + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + if (player == null || mc.level == null) return; + + if (resetTimer) { + resetTimer = false; + } + + if (mode.getValue() == Mode.VANILLA) { + setStepHeight(player, height.getValue()); + return; + } + + setStepHeight(player, VANILLA_STEP_HEIGHT); + + double stepHeight = player.getY() - player.yo; + if (stepHeight <= 0.75 || stepHeight > height.getValue()) return; + + double[] offsets = getOffset(stepHeight); + if (offsets == null || offsets.length <= 1) return; + + if (useTimer.getValue()) { + resetTimer = true; + } + + for (double offset : offsets) { + player.connection.send(new ServerboundMovePlayerPacket.Pos( + player.xo, + player.yo + offset, + player.zo, + false, + player.horizontalCollision + )); + } + } + + private void setStepHeight(LocalPlayer player, double value) { + AttributeInstance attribute = player.getAttribute(Attributes.STEP_HEIGHT); + if (attribute != null) { + attribute.setBaseValue(value); + } + } + + private double[] getOffset(double height) { + return switch ((int) (height * 10000.0)) { + case 7500, 10000 -> new double[]{0.42, 0.753}; + case 8125, 8750 -> new double[]{0.39, 0.7}; + case 15000 -> new double[]{0.42, 0.75, 1.0, 1.16, 1.23, 1.2}; + case 20000 -> new double[]{0.42, 0.78, 0.63, 0.51, 0.9, 1.21, 1.45, 1.43}; + case 250000 -> new double[]{0.425, 0.821, 0.699, 0.599, 1.022, 1.372, 1.652, 1.869, 2.019, 1.907}; + default -> null; + }; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/TickShift.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/TickShift.java new file mode 100644 index 0000000..f21e06d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/movement/TickShift.java @@ -0,0 +1,133 @@ +package me.humanbeing.nolongerhuman.features.modules.movement; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.TickShiftUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; + +public class TickShift extends Module { + private final Setting maxTicks = num("Ticks", 15, 1, 50); + private final Setting ticksPerTick = num("TicksPerTick", 3, 1, 10); + private final Setting chargeSpeed = num("ChargeSpeed", 0.25, 0.01, 2.0); + private final Setting chargeAmount = num("ChargeAmount", 5, 1, 20); + private final Setting maxFallDistance = num("MaxFallDistance", 5.0, 0.0, 20.0); + private final Setting autoDisable = bool("AutoDisable", false); + + private int ticksLeft; + private float chargeProgress; + private boolean shifting; + + public TickShift() { + super("TickShift", "Runs extra client ticks while moving", Category.MOVEMENT); + } + + @Override + public void onEnable() { + ticksLeft = maxTicks.getValue(); + chargeProgress = 0.0F; + shifting = false; + } + + @Override + public void onDisable() { + ticksLeft = 0; + chargeProgress = 0.0F; + shifting = false; + } + + @Override + public void onTick() { + if (TickShiftUtil.isTickShifting()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + shifting = false; + return; + } + + if (shouldPause(player)) { + shifting = false; + recharge(); + return; + } + + if (!isPlayerMoving()) { + shifting = false; + recharge(); + return; + } + + if (ticksLeft <= 0) { + shifting = false; + + if (autoDisable.getValue()) { + disable(); + } + + return; + } + + int shiftedTicks = tickShift(player); + + shifting = shiftedTicks > 0; + + if (shifting) { + ticksLeft -= shiftedTicks; + chargeProgress = 0.0F; + } + + if (ticksLeft <= 0 && autoDisable.getValue()) { + disable(); + } + } + + private int tickShift(LocalPlayer player) { + int ticks = Math.min(ticksLeft, ticksPerTick.getValue()); + return TickShiftUtil.runExtraTicks(player, ticks); + } + + private boolean shouldPause(LocalPlayer player) { + return player.isSpectator() + || player.isInWater() + || player.isInLava() + || player.fallDistance >= maxFallDistance.getValue().floatValue(); + } + + private void recharge() { + int max = maxTicks.getValue(); + + if (ticksLeft >= max) { + ticksLeft = max; + chargeProgress = 0.0F; + return; + } + + chargeProgress += chargeSpeed.getValue().floatValue(); + + while (chargeProgress >= 1.0F) { + chargeProgress -= 1.0F; + ticksLeft = Math.min(ticksLeft + chargeAmount.getValue(), max); + } + } + + private boolean isPlayerMoving() { + return mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown() + || mc.options.keyJump.isDown(); + } + + public String getInfo() { + if (shifting) { + return ticksLeft + " shifting"; + } + + return String.valueOf(ticksLeft); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/AuraFarmer.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/AuraFarmer.java new file mode 100644 index 0000000..d4502e1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/AuraFarmer.java @@ -0,0 +1,125 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.item.Items; + +public class AuraFarmer extends Module { + + private static AuraFarmer INSTANCE; + + private static final String DEFAULT_SUFFIX = "ɴᴏʟᴏɴɢᴇʀʜᴜᴍᴀɴ"; + + public final Setting suffix = str("Suffix", DEFAULT_SUFFIX); + public final Setting separator = bool("Separator", true); + public final Setting ignoreMaps = bool("IgnoreMaps", true); + + private final String[] filters = { + ".", + "/", + ",", + ":", + "`", + "-" + }; + + public AuraFarmer() { + super("AuraFarmer", "Appends a suffix after your chat messages", Category.PLAYER); + INSTANCE = this; + } + + public static AuraFarmer getInstance() { + return INSTANCE; + } + + public static boolean shouldModifyChat(String message) { + AuraFarmer module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + return module.canModify(message); + } + + public static String modifyChat(String message) { + AuraFarmer module = INSTANCE; + + if (module == null) { + return message; + } + + return module.getText(message); + } + + private boolean canModify(String message) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + return false; + } + + if (message == null || message.isBlank()) { + return false; + } + + if (ignoreMaps.getValue()) { + if (player.getMainHandItem().is(Items.FILLED_MAP) + || player.getOffhandItem().is(Items.FILLED_MAP)) { + return false; + } + } + + for (String filter : filters) { + if (message.startsWith(filter)) { + return false; + } + } + + if (nolongerhuman.commandManager != null) { + String prefix = nolongerhuman.commandManager.getCommandPrefix(); + + if (prefix != null && !prefix.isBlank() && message.startsWith(prefix)) { + return false; + } + } + + String modified = getText(message); + + return modified.length() < 254 && !modified.equals(message); + } + + public String getText(String message) { + String cleanSuffix = suffix.getValue(); + + if (cleanSuffix == null || cleanSuffix.isBlank()) { + cleanSuffix = DEFAULT_SUFFIX; + } + + cleanSuffix = cleanSuffix.trim(); + + if (message.endsWith(cleanSuffix)) { + return message; + } + + if (separator.getValue()) { + return message + " | " + cleanSuffix; + } + + return message + " " + cleanSuffix; + } + + @Override + public String getDisplayInfo() { + String value = suffix.getValue(); + return value == null || value.isBlank() ? DEFAULT_SUFFIX : value; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/AutoLog.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/AutoLog.java new file mode 100644 index 0000000..046cc90 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/AutoLog.java @@ -0,0 +1,78 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.ItemStack; + +public class AutoLog extends Module { + private final Setting healthCheck = bool("HealthCheck", false); + private final Setting health = num("Health", 10.0, 0.0, 20.0); + + private final Setting totemCheck = bool("TotemCheck", true); + private final Setting totemCount = num("Totems", 2, 0, 9); + + private final Setting selfDisable = bool("SelfDisable", true); + + public AutoLog() { + super("AutoLog", "Disconnects when safety conditions are met", Category.PLAYER); + } + + @Override + public void onTick() { + if (mc.player == null || mc.level == null || mc.getConnection() == null) { + return; + } + + if (healthCheck.getValue() && mc.player.getHealth() <= health.getValue().floatValue()) { + disconnect("Health was lower than or equal to " + health.getValue().intValue() + "."); + return; + } + + if (totemCheck.getValue() && countTotems() <= totemCount.getValue()) { + disconnect("Couldn't find enough totems in your inventory."); + } + } + + private int countTotems() { + if (mc.player == null) { + return 0; + } + + int count = 0; + + for (int i = 0; i < mc.player.getInventory().getContainerSize(); i++) { + ItemStack stack = mc.player.getInventory().getItem(i); + + if (stack.is(Items.TOTEM_OF_UNDYING)) { + count += stack.getCount(); + } + } + + return count; + } + + private void disconnect(String reason) { + if (mc.getConnection() != null) { + mc.getConnection().getConnection().disconnect(Component.literal(reason)); + } + + if (selfDisable.getValue()) { + disable(); + } + } + + @Override + public String getDisplayInfo() { + if (healthCheck.getValue()) { + return "Health"; + } + + if (totemCheck.getValue()) { + return "Totems"; + } + + return "Off"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/ClipboardScreenshot.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/ClipboardScreenshot.java new file mode 100644 index 0000000..311c480 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/ClipboardScreenshot.java @@ -0,0 +1,365 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.network.chat.Component; + +import javax.imageio.ImageIO; +import java.awt.GraphicsEnvironment; +import java.awt.HeadlessException; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Locale; +import java.util.Optional; +import java.util.stream.Stream; + +public class ClipboardScreenshot extends Module { + private final Setting notify = bool("Notify", true); + private final Setting checkDelay = num("CheckDelay", 2, 1, 20); + private final Setting copyDelay = num("CopyDelay", 4, 1, 40); + + private Path screenshotsDirectory; + private Path pendingScreenshot; + + private long newestKnownTime; + private int checkTicks; + private int pendingTicks; + private boolean awtClipboardUnavailable; + + public ClipboardScreenshot() { + super("ClipboardScreenshot", "Copies Minecraft screenshots to your clipboard", Category.PLAYER); + } + + @Override + public void onEnable() { + screenshotsDirectory = getScreenshotsDirectory(); + pendingScreenshot = null; + newestKnownTime = getNewestScreenshotTime(screenshotsDirectory); + checkTicks = 0; + pendingTicks = 0; + awtClipboardUnavailable = GraphicsEnvironment.isHeadless(); + } + + @Override + public void onDisable() { + pendingScreenshot = null; + checkTicks = 0; + pendingTicks = 0; + } + + @Override + public void onTick() { + if (screenshotsDirectory == null) { + screenshotsDirectory = getScreenshotsDirectory(); + } + + if (screenshotsDirectory == null) { + return; + } + + if (pendingScreenshot != null) { + handlePendingScreenshot(); + return; + } + + if (checkTicks < checkDelay.getValue()) { + checkTicks++; + return; + } + + checkTicks = 0; + + Optional newest = getNewestScreenshot(screenshotsDirectory); + + if (newest.isEmpty()) { + return; + } + + Path screenshot = newest.get(); + long modifiedTime = getModifiedTime(screenshot); + + if (modifiedTime <= newestKnownTime) { + return; + } + + newestKnownTime = modifiedTime; + pendingScreenshot = screenshot; + pendingTicks = copyDelay.getValue(); + } + + private void handlePendingScreenshot() { + if (pendingTicks > 0) { + pendingTicks--; + return; + } + + Path screenshot = pendingScreenshot; + pendingScreenshot = null; + + if (screenshot == null) { + return; + } + + if (!Files.isRegularFile(screenshot)) { + return; + } + + boolean copied = copyScreenshotToClipboard(screenshot); + + if (copied) { + sendNotify("Copied screenshot to clipboard."); + } else { + sendNotify("Failed to copy screenshot to clipboard."); + } + } + + private boolean copyScreenshotToClipboard(Path screenshot) { + if (!awtClipboardUnavailable && copyUsingAwt(screenshot)) { + return true; + } + + awtClipboardUnavailable = true; + + return copyUsingPlatformFallback(screenshot); + } + + private boolean copyUsingAwt(Path screenshot) { + BufferedImage image; + + try { + image = ImageIO.read(screenshot.toFile()); + } catch (IOException ignored) { + return false; + } + + if (image == null) { + return false; + } + + try { + Toolkit.getDefaultToolkit() + .getSystemClipboard() + .setContents(new ImageTransferable(image), null); + + return true; + } catch (HeadlessException ignored) { + return false; + } catch (IllegalStateException ignored) { + return false; + } catch (Throwable ignored) { + return false; + } + } + + private boolean copyUsingPlatformFallback(Path screenshot) { + String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT); + + if (os.contains("win")) { + return copyUsingPowerShell(screenshot); + } + + return false; + } + + private boolean copyUsingPowerShell(Path screenshot) { + Path absolutePath = screenshot.toAbsolutePath(); + String escapedPath = absolutePath.toString().replace("'", "''"); + + String script = """ + Add-Type -AssemblyName System.Windows.Forms; + Add-Type -AssemblyName System.Drawing; + $image = [System.Drawing.Image]::FromFile('%s'); + [System.Windows.Forms.Clipboard]::SetImage($image); + $image.Dispose(); + """.formatted(escapedPath); + + ProcessBuilder builder = new ProcessBuilder( + "powershell.exe", + "-NoProfile", + "-Sta", + "-ExecutionPolicy", + "Bypass", + "-Command", + script + ); + + builder.redirectErrorStream(true); + + try { + Process process = builder.start(); + int exitCode = process.waitFor(); + + return exitCode == 0; + } catch (IOException ignored) { + return false; + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + return false; + } + } + + private Path getScreenshotsDirectory() { + Path gameDirectory = getGameDirectory(); + + if (gameDirectory == null) { + return null; + } + + Path screenshots = gameDirectory.resolve("screenshots"); + + try { + Files.createDirectories(screenshots); + } catch (IOException ignored) { + return null; + } + + return screenshots; + } + + private Path getGameDirectory() { + File direct = getGameDirectoryDirectly(); + + if (direct != null) { + return direct.toPath(); + } + + File reflected = getGameDirectoryReflectively(); + + if (reflected != null) { + return reflected.toPath(); + } + + return null; + } + + private File getGameDirectoryDirectly() { + try { + return mc.gameDirectory; + } catch (Throwable ignored) { + return null; + } + } + + private File getGameDirectoryReflectively() { + for (Class clazz = mc.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) { + continue; + } + + if (field.getType() != File.class) { + continue; + } + + String name = field.getName().toLowerCase(Locale.ROOT); + + if (!name.contains("game") && !name.contains("directory") && !name.contains("dir")) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(mc); + + if (value instanceof File file) { + return file; + } + } catch (IllegalAccessException ignored) { + } + } + } + + return null; + } + + private Optional getNewestScreenshot(Path directory) { + if (directory == null || !Files.isDirectory(directory)) { + return Optional.empty(); + } + + try (Stream stream = Files.list(directory)) { + return stream + .filter(Files::isRegularFile) + .filter(this::isPngFile) + .max(Comparator.comparingLong(this::getModifiedTime)); + } catch (IOException ignored) { + return Optional.empty(); + } + } + + private long getNewestScreenshotTime(Path directory) { + Optional newest = getNewestScreenshot(directory); + + return newest.map(this::getModifiedTime).orElse(0L); + } + + private boolean isPngFile(Path path) { + String fileName = path.getFileName().toString().toLowerCase(Locale.ROOT); + + return fileName.endsWith(".png"); + } + + private long getModifiedTime(Path path) { + try { + return Files.getLastModifiedTime(path).toMillis(); + } catch (IOException ignored) { + return 0L; + } + } + + private void sendNotify(String message) { + if (!notify.getValue()) { + return; + } + + if (mc.player == null) { + return; + } + + mc.player.displayClientMessage(Component.literal(message), false); + } + + @Override + public String getDisplayInfo() { + return awtClipboardUnavailable ? "Fallback" : "Clipboard"; + } + + private static final class ImageTransferable implements Transferable { + private final Image image; + + private ImageTransferable(Image image) { + this.image = image; + } + + @Override + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[]{DataFlavor.imageFlavor}; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return DataFlavor.imageFlavor.equals(flavor); + } + + @Override + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { + if (!isDataFlavorSupported(flavor)) { + throw new UnsupportedFlavorException(flavor); + } + + return image; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Criticals.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Criticals.java new file mode 100644 index 0000000..a902555 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Criticals.java @@ -0,0 +1,117 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import net.minecraft.network.protocol.game.ServerboundInteractPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.phys.Vec3; + +import java.lang.reflect.Field; + +public class Criticals extends Module { + private static final Field ENTITY_ID_FIELD; + + static { + Field field = null; + + try { + field = ServerboundInteractPacket.class.getDeclaredField("entityId"); + field.setAccessible(true); + } catch (Throwable ignored) { + } + + ENTITY_ID_FIELD = field; + } + + public Criticals() { + super("Criticals", "Makes attacks deal critical hits", Category.PLAYER); + } + + @Subscribe + private void onPacketSend(PacketEvent.Send event) { + if (nullCheck()) return; + + if (!(event.getPacket() instanceof ServerboundInteractPacket packet)) { + return; + } + + if (!isAttackPacket(packet)) { + return; + } + + Entity entity = getEntity(packet); + + if (entity == null) return; + if (entity instanceof EndCrystal) return; + if (!(entity instanceof LivingEntity)) return; + + if (!mc.player.onGround()) return; + if (mc.player.isInWater()) return; + if (mc.player.isInLava()) return; + if (mc.player.isPassenger()) return; + + boolean horizontalCollision = mc.player.horizontalCollision; + + mc.player.connection.send(new ServerboundMovePlayerPacket.Pos( + mc.player.getX(), + mc.player.getY() + 0.1F, + mc.player.getZ(), + false, + horizontalCollision + )); + + mc.player.connection.send(new ServerboundMovePlayerPacket.Pos( + mc.player.getX(), + mc.player.getY(), + mc.player.getZ(), + false, + horizontalCollision + )); + + mc.player.crit(entity); + } + + private boolean isAttackPacket(ServerboundInteractPacket packet) { + final boolean[] attacking = {false}; + + packet.dispatch(new ServerboundInteractPacket.Handler() { + @Override + public void onInteraction(InteractionHand hand) { + } + + @Override + public void onInteraction(InteractionHand hand, Vec3 location) { + } + + @Override + public void onAttack() { + attacking[0] = true; + } + }); + + return attacking[0]; + } + + private Entity getEntity(ServerboundInteractPacket packet) { + if (ENTITY_ID_FIELD == null || mc.level == null) { + return null; + } + + try { + int entityId = ENTITY_ID_FIELD.getInt(packet); + return mc.level.getEntity(entityId); + } catch (Throwable ignored) { + return null; + } + } + + @Override + public String getDisplayInfo() { + return "Packet"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/FakeLag.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/FakeLag.java new file mode 100644 index 0000000..ed30d9c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/FakeLag.java @@ -0,0 +1,312 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import com.mojang.authlib.GameProfile; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.player.RemotePlayer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; + +public class FakeLag extends Module { + public enum Mode { + Pulse, + Blink + } + + private final Setting mode = mode("Mode", Mode.Pulse); + private final Setting factor = num("Factor", 2.0, 1.0, 5.0); + private final Setting render = bool("Render", true); + private final Setting trailColor = color("TrailColor", new Color(0, 255, 255, 180)); + private final Setting ghostColor = color("GhostColor", new Color(0, 255, 255, 55)); + + private final List pulsePackets = new ArrayList<>(); + private final List> blinkPackets = new ArrayList<>(); + private final CopyOnWriteArrayList trail = new CopyOnWriteArrayList<>(); + + private boolean sending; + private long lastPulseTime; + private long lastSafetyReset; + + private RemotePlayer fakePlayer; + private Vec3 startPos; + + public FakeLag() { + super("FakeLag", "Chokes movement packets", Category.PLAYER); + } + + @Override + public void onEnable() { + pulsePackets.clear(); + blinkPackets.clear(); + trail.clear(); + + sending = false; + lastPulseTime = System.currentTimeMillis(); + lastSafetyReset = System.currentTimeMillis(); + startPos = null; + + if (mc.player == null || mc.level == null) { + return; + } + + if (mode.getValue() == Mode.Blink && render.getValue()) { + spawnFakePlayer(); + } + } + + @Override + public void onDisable() { + if (mode.getValue() == Mode.Pulse) { + flushPulsePackets(); + } + + if (mode.getValue() == Mode.Blink) { + flushBlinkPackets(); + removeFakePlayer(); + } + + pulsePackets.clear(); + blinkPackets.clear(); + trail.clear(); + startPos = null; + sending = false; + } + + @Override + public void onTick() { + if (mc.player == null || mc.level == null) { + return; + } + + if (mode.getValue() == Mode.Blink && render.getValue()) { + updateTrail(); + } + + if (mode.getValue() != Mode.Pulse) { + return; + } + + if (pulsePackets.isEmpty()) { + return; + } + + long delay = Math.round(factor.getValue() * 100.0D); + + if (System.currentTimeMillis() - lastPulseTime >= delay) { + flushPulsePackets(); + lastPulseTime = System.currentTimeMillis(); + } + } + + @Subscribe + public void onPacketSend(PacketEvent.Send event) { + if (mc.player == null || mc.level == null || sending) { + return; + } + + Packet packet = event.getPacket(); + + if (mode.getValue() == Mode.Blink) { + if (packet instanceof ServerboundMovePlayerPacket) { + event.cancel(); + + if (!blinkPackets.contains(packet)) { + blinkPackets.add(packet); + } + } + + return; + } + + if (!(packet instanceof ServerboundMovePlayerPacket movePacket)) { + return; + } + + if (!shouldChoke()) { + return; + } + + event.cancel(); + + synchronized (pulsePackets) { + pulsePackets.add(movePacket); + } + } + + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + if (mc.player == null || mc.level == null) { + return; + } + + if (mode.getValue() != Mode.Pulse) { + return; + } + + Packet packet = event.getPacket(); + String name = packet.getClass().getSimpleName().toLowerCase(); + + if (name.contains("position") + || name.contains("disconnect") + || name.contains("health")) { + flushPulsePackets(); + lastSafetyReset = System.currentTimeMillis(); + } + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue() || mode.getValue() != Mode.Blink) { + return; + } + + if (trail.size() < 2) { + return; + } + + for (Vec3 pos : trail) { + AABB box = AABB.ofSize(pos, 0.08D, 0.08D, 0.08D); + RenderUtil.drawBoxFilled(event.getMatrix(), box, trailColor.getValue()); + } + + if (startPos != null) { + AABB box = AABB.ofSize(startPos, 0.6D, 1.8D, 0.6D); + RenderUtil.drawBoxFilled(event.getMatrix(), box, ghostColor.getValue()); + RenderUtil.drawBox(event.getMatrix(), box, trailColor.getValue(), 1.0F); + } + } + + private void spawnFakePlayer() { + if (mc.player == null || mc.level == null) { + return; + } + + GameProfile profile = new GameProfile( + UUID.randomUUID(), + mc.player.getName().getString() + ); + + fakePlayer = new RemotePlayer(mc.level, profile); + fakePlayer.copyPosition(mc.player); + fakePlayer.setYRot(mc.player.getYRot()); + fakePlayer.setXRot(mc.player.getXRot()); + fakePlayer.setId(-420420); + + mc.level.addEntity(fakePlayer); + fakePlayer.tick(); + + startPos = mc.player.position(); + trail.add(startPos); + } + + private void removeFakePlayer() { + if (fakePlayer == null) { + return; + } + + fakePlayer.remove(Entity.RemovalReason.DISCARDED); + fakePlayer = null; + } + + private void updateTrail() { + if (mc.player == null) { + return; + } + + Vec3 current = new Vec3( + mc.player.getX(), + mc.player.getBoundingBox().minY, + mc.player.getZ() + ); + + if (startPos == null) { + startPos = current; + trail.add(current); + return; + } + + Vec3 last = trail.isEmpty() ? null : trail.getLast(); + + if (last == null || last.distanceToSqr(current) > 0.0025D) { + trail.add(current); + } + + while (trail.size() > 250) { + trail.removeFirst(); + } + } + + private void flushPulsePackets() { + if (mc.getConnection() == null) { + return; + } + + synchronized (pulsePackets) { + sending = true; + + for (ServerboundMovePlayerPacket packet : pulsePackets) { + mc.getConnection().send(packet); + } + + pulsePackets.clear(); + sending = false; + } + } + + private void flushBlinkPackets() { + if (mc.getConnection() == null) { + blinkPackets.clear(); + return; + } + + sending = true; + + for (Packet packet : blinkPackets) { + if (packet != null) { + mc.getConnection().send(packet); + } + } + + blinkPackets.clear(); + sending = false; + } + + private boolean shouldChoke() { + if (mc.player == null) { + return false; + } + + if (System.currentTimeMillis() - lastSafetyReset < 1000L) { + return false; + } + + double speed = Math.hypot( + mc.player.getX() - mc.player.xOld, + mc.player.getZ() - mc.player.zOld + ) * 72.0D; + + return speed >= 5.0D || mc.player.fallDistance > 0.0F; + } + + @Override + public String getDisplayInfo() { + if (mode.getValue() == Mode.Pulse) { + return shouldChoke() ? "Pulsing" : "Waiting"; + } + + return "Blink"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/HitboxDesync.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/HitboxDesync.java new file mode 100644 index 0000000..cfddab0 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/HitboxDesync.java @@ -0,0 +1,96 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.Vec3; + +public class HitboxDesync extends Module { + public static HitboxDesync INSTANCE; + + private final Setting alternating = bool("Alternating", true); + private final Setting minimal = bool("Minimal", true); + private final Setting specific = bool("Specific", true); + private final Setting disableSelf = bool("DisableSelf", false); + private final Setting disableOnJump = bool("DisableOnJump", false); + + private long lastTimeReset; + private double previousY; + + public HitboxDesync() { + super("HitboxDesync", "Offsets your hitbox position inside blocks", Category.PLAYER); + INSTANCE = this; + } + + @Override + public void onEnable() { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + disable(); + return; + } + + previousY = player.getY(); + lastTimeReset = System.currentTimeMillis(); + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + + if (player == null || mc.level == null) { + disable(); + return; + } + + if (disableOnJump.getValue() && player.getY() != previousY) { + disable(); + return; + } + + if (disableSelf.getValue() && !alternating.getValue()) { + disable(); + return; + } + + applyDesync(player); + } + + private void applyDesync(LocalPlayer player) { + long currentTime = System.currentTimeMillis(); + long timeout = specific.getValue() ? 500L : 1500L; + + boolean elapsed = currentTime - lastTimeReset >= timeout; + + BlockPos blockPos = player.blockPosition(); + Vec3 center = Vec3.atCenterOf(blockPos); + + double offset = minimal.getValue() ? 0.001D : 0.002D; + + boolean shouldAlternate = elapsed && alternating.getValue() && !player.isShiftKeyDown(); + + boolean positiveX = center.x - player.getX() > 0.0D; + boolean positiveZ = center.z - player.getZ() > 0.0D; + + double x = center.x + + (shouldAlternate ? offset * (positiveX ? 1.0D : -1.0D) : 0.0D) + + 0.20000000009497754D * (positiveX ? -1.0D : 1.0D); + + double z = center.z + + (shouldAlternate ? offset * (positiveZ ? 1.0D : -1.0D) : 0.0D) + + 0.2000000000949811D * (positiveZ ? -1.0D : 1.0D); + + player.setPos(x, player.getY(), z); + + if (elapsed) { + lastTimeReset = currentTime; + } + } + + @Override + public String getDisplayInfo() { + return alternating.getValue() ? "Alternating" : "Static"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyExperience.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyExperience.java new file mode 100644 index 0000000..d6d51ea --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyExperience.java @@ -0,0 +1,322 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.FULL_SCOPE; +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.HOTBAR_SCOPE; + +public class KeyExperience extends Module { + + public enum AntiWaste { + None, + Avoid, + Disable + } + + public enum Swing { + Normal, + Packet, + Both, + None + } + + private static final EquipmentSlot[] ARMOR_SLOTS = { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + + private final Setting inventory = bool("Inventory", true); + private final Setting silentSwap = bool("SilentSwap", true); + + private final Setting delay = num("Delay", 1, 0, 20); + private final Setting amount = num("Amount", 1, 1, 15); + + private final Setting antiWaste = mode("AntiWaste", AntiWaste.Disable); + private final Setting itemDisable = bool("ItemDisable", true); + + private final Setting rotate = bool("Rotate", false); + private final Setting pitch = num("Pitch", 90.0f, -90.0f, 90.0f); + + private final Setting swing = mode("Swing", Swing.Normal); + + private int ticks = 0; + + public KeyExperience() { + super("KeyExperience", "Throws experience bottles when enabled", Category.PLAYER); + } + + @Override + public void onEnable() { + ticks = 0; + + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + } + } + + @Override + public void onDisable() { + ticks = 0; + } + + @Override + public void onTick() { + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + int delayTicks = Math.max(0, delay.getValue()); + + if (ticks < delayTicks) { + ticks++; + return; + } + + ticks = 0; + + if (antiWaste.getValue() != AntiWaste.None && !needsExperience()) { + if (antiWaste.getValue() == AntiWaste.Disable) { + disable(); + } + + return; + } + + Result result = InventoryUtil.find( + Items.EXPERIENCE_BOTTLE, + inventory.getValue() ? FULL_SCOPE : HOTBAR_SCOPE + ); + + if (result == null || result.type() == ResultType.NONE) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + if (silentSwap.getValue() && canSilentSwap(result)) { + useSilent(result); + return; + } + + useNormal(result); + } + + private boolean canSilentSwap(Result result) { + return result.type() == ResultType.HOTBAR + || result.type() == ResultType.OFFHAND; + } + + private void useSilent(Result result) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + if (rotate.getValue()) { + rotateDown(); + } + + if (result.type() == ResultType.OFFHAND) { + if (!mc.player.getOffhandItem().is(Items.EXPERIENCE_BOTTLE)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + throwAmount(InteractionHand.OFF_HAND); + doSwing(InteractionHand.OFF_HAND); + return; + } + + int oldSlot = InventoryUtil.selected(); + int xpSlot = result.slot(); + + if (xpSlot < 0 || xpSlot > 8) { + useNormal(result); + return; + } + + sendHeldItemChange(xpSlot); + + throwAmount(InteractionHand.MAIN_HAND); + doSwing(InteractionHand.MAIN_HAND); + + sendHeldItemChange(oldSlot); + } + + private void useNormal(Result result) { + int oldSlot = InventoryUtil.selected(); + + if (!InventoryUtil.swap(result)) { + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + InteractionHand hand = getUseHand(result); + + if (!isHoldingExperience(hand)) { + InventoryUtil.swapBack(result, oldSlot); + + if (itemDisable.getValue()) { + disable(); + } + + return; + } + + if (rotate.getValue()) { + rotateDown(); + } + + throwAmount(hand); + doSwing(hand); + + InventoryUtil.swapBack(result, oldSlot); + } + + private void throwAmount(InteractionHand hand) { + int throwAmount = Math.max(1, amount.getValue()); + + for (int i = 0; i < throwAmount; i++) { + throwExperience(hand); + } + } + + private InteractionHand getUseHand(Result result) { + if (result.type() == ResultType.OFFHAND) { + return InteractionHand.OFF_HAND; + } + + return InteractionHand.MAIN_HAND; + } + + private boolean isHoldingExperience(InteractionHand hand) { + if (mc.player == null) { + return false; + } + + ItemStack stack = hand == InteractionHand.OFF_HAND + ? mc.player.getOffhandItem() + : mc.player.getMainHandItem(); + + return stack.is(Items.EXPERIENCE_BOTTLE); + } + + private void throwExperience(InteractionHand hand) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + mc.gameMode.useItem(mc.player, hand); + } + + private void sendHeldItemChange(int slot) { + if (mc.player == null) { + return; + } + + if (slot < 0 || slot > 8) { + return; + } + + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private void rotateDown() { + if (mc.player == null) { + return; + } + + RotationManager rotationManager = nolongerhuman.rotationManager; + + if (rotationManager == null) { + mc.player.setXRot(pitch.getValue()); + return; + } + + rotationManager.packetRotate(mc.player.getYRot(), pitch.getValue()); + } + + private void doSwing(InteractionHand hand) { + if (mc.player == null) { + return; + } + + switch (swing.getValue()) { + case Normal -> mc.player.swing(hand); + + case Packet -> mc.player.connection.send( + new ServerboundSwingPacket(hand) + ); + + case Both -> { + mc.player.swing(hand); + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + + case None -> { + } + } + } + + private boolean needsExperience() { + if (mc.player == null) { + return false; + } + + for (EquipmentSlot slot : ARMOR_SLOTS) { + ItemStack stack = mc.player.getItemBySlot(slot); + + if (stack.isEmpty()) { + continue; + } + + if (!stack.isDamageableItem()) { + continue; + } + + int maxDamage = stack.getMaxDamage(); + + if (maxDamage <= 0) { + continue; + } + + int remainingDurability = maxDamage - stack.getDamageValue(); + float durabilityPercent = (remainingDurability * 100.0f) / maxDamage; + + if (durabilityPercent < 100.0f) { + return true; + } + } + + return false; + } + + @Override + public String getDisplayInfo() { + return silentSwap.getValue() + ? antiWaste.getValue().name() + " Silent" + : antiWaste.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyFirework.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyFirework.java new file mode 100644 index 0000000..78aa08b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyFirework.java @@ -0,0 +1,185 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.FULL_SCOPE; +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.HOTBAR_SCOPE; + +public class KeyFirework extends Module { + public enum Swing { + Normal, + Packet, + Both, + None + } + + private final Setting inventory = bool("Inventory", false); + private final Setting silentSwap = bool("SilentSwap", true); + private final Setting itemDisable = bool("ItemDisable", true); + private final Setting swing = mode("Swing", Swing.Normal); + + public KeyFirework() { + super("KeyFirework", "Uses a firework rocket when enabled", Category.PLAYER); + } + + @Override + public void onEnable() { + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + Result result = InventoryUtil.find( + Items.FIREWORK_ROCKET, + inventory.getValue() ? FULL_SCOPE : HOTBAR_SCOPE + ); + + if (result == null || result.type() == ResultType.NONE) { + if (itemDisable.getValue()) { + disable(); + } + return; + } + + if (silentSwap.getValue() && canSilentSwap(result)) { + useSilent(result); + } else { + useNormal(result); + } + + disable(); + } + + private boolean canSilentSwap(Result result) { + return result.type() == ResultType.HOTBAR + || result.type() == ResultType.OFFHAND; + } + + private void useSilent(Result result) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + if (result.type() == ResultType.OFFHAND) { + if (!mc.player.getOffhandItem().is(Items.FIREWORK_ROCKET)) { + return; + } + + useFirework(InteractionHand.OFF_HAND); + doSwing(InteractionHand.OFF_HAND); + return; + } + + int oldSlot = InventoryUtil.selected(); + int fireworkSlot = result.slot(); + + if (fireworkSlot < 0 || fireworkSlot > 8) { + useNormal(result); + return; + } + + sendHeldItemChange(fireworkSlot); + useFirework(InteractionHand.MAIN_HAND); + doSwing(InteractionHand.MAIN_HAND); + sendHeldItemChange(oldSlot); + } + + private void useNormal(Result result) { + int oldSlot = InventoryUtil.selected(); + + if (!InventoryUtil.swap(result)) { + if (itemDisable.getValue()) { + disable(); + } + return; + } + + InteractionHand hand = getUseHand(result); + + if (!isHoldingFirework(hand)) { + InventoryUtil.swapBack(result, oldSlot); + + if (itemDisable.getValue()) { + disable(); + } + return; + } + + useFirework(hand); + doSwing(hand); + InventoryUtil.swapBack(result, oldSlot); + } + + private InteractionHand getUseHand(Result result) { + if (result.type() == ResultType.OFFHAND) { + return InteractionHand.OFF_HAND; + } + + return InteractionHand.MAIN_HAND; + } + + private boolean isHoldingFirework(InteractionHand hand) { + if (mc.player == null) { + return false; + } + + ItemStack stack = hand == InteractionHand.OFF_HAND + ? mc.player.getOffhandItem() + : mc.player.getMainHandItem(); + + return stack.is(Items.FIREWORK_ROCKET); + } + + private void useFirework(InteractionHand hand) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + mc.gameMode.useItem(mc.player, hand); + } + + private void sendHeldItemChange(int slot) { + if (mc.player == null) { + return; + } + + if (slot < 0 || slot > 8) { + return; + } + + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private void doSwing(InteractionHand hand) { + if (mc.player == null) { + return; + } + + switch (swing.getValue()) { + case Normal -> mc.player.swing(hand); + case Packet -> mc.player.connection.send( + new ServerboundSwingPacket(hand) + ); + case Both -> { + mc.player.swing(hand); + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + case None -> { + } + } + } + + @Override + public String getDisplayInfo() { + return silentSwap.getValue() ? "Silent" : "Normal"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyPearl.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyPearl.java new file mode 100644 index 0000000..748b50d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/KeyPearl.java @@ -0,0 +1,178 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.FULL_SCOPE; +import static me.humanbeing.nolongerhuman.util.inventory.InventoryUtil.HOTBAR_SCOPE; + +public class KeyPearl extends Module { + public enum Swing { + Normal, + Packet, + Both, + None + } + + private final Setting inventory = bool("Inventory", false); + private final Setting silentSwap = bool("SilentSwap", true); + private final Setting itemDisable = bool("ItemDisable", true); + private final Setting swing = mode("Swing", Swing.Normal); + + public KeyPearl() { + super("KeyPearl", "Throws an ender pearl when enabled", Category.PLAYER); + } + + @Override + public void onEnable() { + if (nullCheck() || mc.player == null || mc.level == null || mc.gameMode == null) { + disable(); + return; + } + + Result result = InventoryUtil.find( + Items.ENDER_PEARL, + inventory.getValue() ? FULL_SCOPE : HOTBAR_SCOPE + ); + + if (result == null || result.type() == ResultType.NONE) { + if (itemDisable.getValue()) { + disable(); + } + return; + } + + if (silentSwap.getValue() && canSilentSwap(result)) { + useSilent(result); + } else { + useNormal(result); + } + + disable(); + } + + private boolean canSilentSwap(Result result) { + return result.type() == ResultType.HOTBAR + || result.type() == ResultType.OFFHAND; + } + + private void useSilent(Result result) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + if (result.type() == ResultType.OFFHAND) { + if (!mc.player.getOffhandItem().is(Items.ENDER_PEARL)) { + return; + } + + throwPearl(InteractionHand.OFF_HAND); + doSwing(InteractionHand.OFF_HAND); + return; + } + + int oldSlot = InventoryUtil.selected(); + int pearlSlot = result.slot(); + + if (pearlSlot < 0 || pearlSlot > 8) { + useNormal(result); + return; + } + + sendHeldItemChange(pearlSlot); + throwPearl(InteractionHand.MAIN_HAND); + doSwing(InteractionHand.MAIN_HAND); + sendHeldItemChange(oldSlot); + } + + private void useNormal(Result result) { + int oldSlot = InventoryUtil.selected(); + + if (!InventoryUtil.swap(result)) { + return; + } + + InteractionHand hand = getUseHand(result); + + if (!isHoldingPearl(hand)) { + InventoryUtil.swapBack(result, oldSlot); + return; + } + + throwPearl(hand); + doSwing(hand); + InventoryUtil.swapBack(result, oldSlot); + } + + private InteractionHand getUseHand(Result result) { + if (result.type() == ResultType.OFFHAND) { + return InteractionHand.OFF_HAND; + } + + return InteractionHand.MAIN_HAND; + } + + private boolean isHoldingPearl(InteractionHand hand) { + if (mc.player == null) { + return false; + } + + ItemStack stack = hand == InteractionHand.OFF_HAND + ? mc.player.getOffhandItem() + : mc.player.getMainHandItem(); + + return stack.is(Items.ENDER_PEARL); + } + + private void throwPearl(InteractionHand hand) { + if (mc.player == null || mc.gameMode == null) { + return; + } + + mc.gameMode.useItem(mc.player, hand); + } + + private void sendHeldItemChange(int slot) { + if (mc.player == null) { + return; + } + + if (slot < 0 || slot > 8) { + return; + } + + mc.player.connection.send(new ServerboundSetCarriedItemPacket(slot)); + } + + private void doSwing(InteractionHand hand) { + if (mc.player == null) { + return; + } + + switch (swing.getValue()) { + case Normal -> mc.player.swing(hand); + case Packet -> mc.player.connection.send( + new ServerboundSwingPacket(hand) + ); + case Both -> { + mc.player.swing(hand); + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + case None -> { + } + } + } + + @Override + public String getDisplayInfo() { + return silentSwap.getValue() ? "Silent" : "Normal"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoEntityTrace.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoEntityTrace.java new file mode 100644 index 0000000..c5ed61b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoEntityTrace.java @@ -0,0 +1,64 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +public class NoEntityTrace extends Module { + private final Setting pickaxeOnly = bool("PickaxeOnly", false); + + private final Setting ignoreGapples = bool("IgnoreGapples", true); + private final Setting ignoreCrystals = bool("IgnoreCrystals", true); + private final Setting ignoreXP = bool("IgnoreXP", true); + private final Setting ignorePearls = bool("IgnorePearls", true); + + public NoEntityTrace() { + super("NoEntityTrace", "Allows you to interact with blocks through entities", Category.PLAYER); + } + + public boolean shouldIgnore() { + if (!isEnabled()) return false; + if (mc.player == null) return false; + + ItemStack stack = mc.player.getMainHandItem(); + + if (pickaxeOnly.getValue()) { + return isPickaxe(stack.getItem()); + } + + if (ignoreGapples.getValue() + && (stack.is(Items.GOLDEN_APPLE) || stack.is(Items.ENCHANTED_GOLDEN_APPLE))) { + return false; + } + + if (ignoreCrystals.getValue() && stack.is(Items.END_CRYSTAL)) { + return false; + } + + if (ignoreXP.getValue() && stack.is(Items.EXPERIENCE_BOTTLE)) { + return false; + } + + if (ignorePearls.getValue() && stack.is(Items.ENDER_PEARL)) { + return false; + } + + return true; + } + + private boolean isPickaxe(Item item) { + return item == Items.WOODEN_PICKAXE + || item == Items.STONE_PICKAXE + || item == Items.IRON_PICKAXE + || item == Items.GOLDEN_PICKAXE + || item == Items.DIAMOND_PICKAXE + || item == Items.NETHERITE_PICKAXE; + } + + @Override + public String getDisplayInfo() { + return pickaxeOnly.getValue() ? "Pickaxe" : "All"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoInteract.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoInteract.java new file mode 100644 index 0000000..fccde27 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoInteract.java @@ -0,0 +1,212 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.core.BlockPos; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AbstractFurnaceBlock; +import net.minecraft.world.level.block.BarrelBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.level.block.DropperBlock; +import net.minecraft.world.level.block.HopperBlock; +import net.minecraft.world.level.block.RespawnAnchorBlock; +import net.minecraft.world.level.block.ShulkerBoxBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; + +public class NoInteract extends Module { + public enum Mode { + Sneak, + Disable + } + + private final Setting mode = mode("Mode", Mode.Sneak); + private final Setting gapple = bool("Gapple", false); + + public NoInteract() { + super("NoInteract", "Prevents you from interacting with storage blocks and respawn anchors", Category.PLAYER); + } + + public boolean shouldDisableInteract() { + if (!canCheckInteraction()) { + return false; + } + + BlockPos pos = getLookedBlockPos(); + + if (pos == null) { + return false; + } + + if (isRespawnAnchor(pos)) { + return true; + } + + return mode.getValue() == Mode.Disable && isStorageBlock(pos); + } + + public boolean shouldSneakInteract() { + if (!canCheckInteraction()) { + return false; + } + + BlockPos pos = getLookedBlockPos(); + + if (pos == null) { + return false; + } + + if (isRespawnAnchor(pos)) { + return false; + } + + return mode.getValue() == Mode.Sneak && isStorageBlock(pos); + } + + private boolean canCheckInteraction() { + if (!isEnabled()) { + return false; + } + + if (mc.player == null || mc.level == null) { + return false; + } + + if (!gapple.getValue()) { + return true; + } + + return mc.player.getMainHandItem().is(Items.ENCHANTED_GOLDEN_APPLE) + || mc.player.getMainHandItem().is(Items.GOLDEN_APPLE); + } + + private BlockPos getLookedBlockPos() { + if (!(mc.hitResult instanceof BlockHitResult hitResult)) { + return null; + } + + if (hitResult.getType() != HitResult.Type.BLOCK) { + return null; + } + + return hitResult.getBlockPos(); + } + + private boolean isRespawnAnchor(BlockPos pos) { + Level level = mc.level; + + if (level == null || pos == null) { + return false; + } + + BlockState state = level.getBlockState(pos); + Block block = state.getBlock(); + + return block == Blocks.RESPAWN_ANCHOR || block instanceof RespawnAnchorBlock; + } + + private boolean isStorageBlock(BlockPos pos) { + Level level = mc.level; + + if (level == null || pos == null) { + return false; + } + + BlockState state = level.getBlockState(pos); + Block block = state.getBlock(); + + if (block instanceof ChestBlock) { + return true; + } + + if (block instanceof BarrelBlock) { + return true; + } + + if (block instanceof ShulkerBoxBlock) { + return true; + } + + if (block instanceof HopperBlock) { + return true; + } + + if (block instanceof DispenserBlock) { + return true; + } + + if (block instanceof DropperBlock) { + return true; + } + + if (block instanceof AbstractFurnaceBlock) { + return true; + } + + if (block == Blocks.ENDER_CHEST) { + return true; + } + + if (block == Blocks.TRAPPED_CHEST) { + return true; + } + + if (block == Blocks.CHEST) { + return true; + } + + if (block == Blocks.BARREL) { + return true; + } + + if (block == Blocks.SHULKER_BOX + || block == Blocks.WHITE_SHULKER_BOX + || block == Blocks.ORANGE_SHULKER_BOX + || block == Blocks.MAGENTA_SHULKER_BOX + || block == Blocks.LIGHT_BLUE_SHULKER_BOX + || block == Blocks.YELLOW_SHULKER_BOX + || block == Blocks.LIME_SHULKER_BOX + || block == Blocks.PINK_SHULKER_BOX + || block == Blocks.GRAY_SHULKER_BOX + || block == Blocks.LIGHT_GRAY_SHULKER_BOX + || block == Blocks.CYAN_SHULKER_BOX + || block == Blocks.PURPLE_SHULKER_BOX + || block == Blocks.BLUE_SHULKER_BOX + || block == Blocks.BROWN_SHULKER_BOX + || block == Blocks.GREEN_SHULKER_BOX + || block == Blocks.RED_SHULKER_BOX + || block == Blocks.BLACK_SHULKER_BOX) { + return true; + } + + BlockEntity blockEntity = level.getBlockEntity(pos); + + if (blockEntity == null) { + return false; + } + + String blockEntityName = blockEntity.getClass().getSimpleName().toLowerCase(); + + return blockEntityName.contains("chest") + || blockEntityName.contains("barrel") + || blockEntityName.contains("shulker") + || blockEntityName.contains("hopper") + || blockEntityName.contains("dispenser") + || blockEntityName.contains("dropper") + || blockEntityName.contains("furnace") + || blockEntityName.contains("smoker") + || blockEntityName.contains("blastfurnace") + || blockEntityName.contains("brewing"); + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoRotate.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoRotate.java new file mode 100644 index 0000000..0f5cc00 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/NoRotate.java @@ -0,0 +1,157 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Locale; +import java.util.Set; + +public class NoRotate extends Module { + private final Setting inBlocks = bool("InBlocks", false); + private final Setting spoof = bool("Spoof", false); + + public NoRotate() { + super("NoRotate", "Prevents the server from forcing rotations on you", Category.PLAYER); + } + + @SuppressWarnings("unused") + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + if (nullCheck()) return; + if (mc.player == null || mc.level == null) return; + + if (!(event.getPacket() instanceof ClientboundPlayerPositionPacket packet)) { + return; + } + + if (inBlocks.getValue() && !isInBlock()) { + return; + } + + if (spoof.getValue() && nolongerhuman.rotationManager != null) { + Vec3 look = mc.player.getEyePosition().add(mc.player.getLookAngle()); + nolongerhuman.rotationManager.packetRotateTo(look); + } + + Object change = getChange(packet); + + if (change == null) { + return; + } + + setRotation(change, mc.player.getYRot(), mc.player.getXRot()); + removeRotationFlags(packet); + } + + private boolean isInBlock() { + if (mc.player == null || mc.level == null) return false; + + BlockState state = mc.level.getBlockState(mc.player.blockPosition()); + + return !state.canBeReplaced(); + } + + private Object getChange(ClientboundPlayerPositionPacket packet) { + try { + Method method = packet.getClass().getDeclaredMethod("change"); + method.setAccessible(true); + return method.invoke(packet); + } catch (Throwable ignored) { + } + + return null; + } + + private void setRotation(Object change, float yaw, float pitch) { + boolean setYaw = false; + boolean setPitch = false; + + for (Field field : change.getClass().getDeclaredFields()) { + if (field.getType() != float.class) { + continue; + } + + String name = field.getName().toLowerCase(Locale.ROOT); + + try { + field.setAccessible(true); + + if (!setYaw && (name.contains("yaw") || name.contains("yrot") || name.contains("y_rot"))) { + field.setFloat(change, yaw); + setYaw = true; + continue; + } + + if (!setPitch && (name.contains("pitch") || name.contains("xrot") || name.contains("x_rot"))) { + field.setFloat(change, pitch); + setPitch = true; + } + } catch (Throwable ignored) { + } + } + + if (setYaw && setPitch) { + return; + } + + Field[] fields = change.getClass().getDeclaredFields(); + Field lastFloatA = null; + Field lastFloatB = null; + + for (Field field : fields) { + if (field.getType() == float.class) { + lastFloatA = lastFloatB; + lastFloatB = field; + } + } + + try { + if (!setYaw && lastFloatA != null) { + lastFloatA.setAccessible(true); + lastFloatA.setFloat(change, yaw); + } + + if (!setPitch && lastFloatB != null) { + lastFloatB.setAccessible(true); + lastFloatB.setFloat(change, pitch); + } + } catch (Throwable ignored) { + } + } + + private void removeRotationFlags(ClientboundPlayerPositionPacket packet) { + try { + Method method = packet.getClass().getDeclaredMethod("relatives"); + method.setAccessible(true); + + Object result = method.invoke(packet); + + if (!(result instanceof Set set)) { + return; + } + + set.removeIf(flag -> { + String name = String.valueOf(flag).toUpperCase(Locale.ROOT); + + return name.contains("X_ROT") + || name.contains("Y_ROT") + || name.contains("XROT") + || name.contains("YROT"); + }); + } catch (Throwable ignored) { + } + } + + @Override + public String getDisplayInfo() { + return spoof.getValue() ? "Spoof" : "Cancel"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Replenish.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Replenish.java new file mode 100644 index 0000000..62c988d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Replenish.java @@ -0,0 +1,226 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.gui.screens.inventory.CreativeModeInventoryScreen; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.ItemStack; + +public class Replenish extends Module { + public enum SwitchMode { + Pickup, + Swap, + Quick + } + + private final Setting switchMode = mode("Switch", SwitchMode.Swap); + private final Setting threshold = num("Threshold", 32, 8, 64); + private final Setting minimumCount = num("MinimumCount", 8, 1, 64); + private final Setting delay = num("Delay", 2, 0, 20); + + private int ticks; + + public Replenish() { + super("Replenish", "Automatically refills low hotbar stacks", Category.PLAYER); + } + + @Override + public void onEnable() { + ticks = 0; + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || gameMode == null) { + return; + } + + if (mc.screen instanceof InventoryScreen || mc.screen instanceof CreativeModeInventoryScreen) { + return; + } + + if (ticks > 0) { + ticks--; + return; + } + + Inventory inventory = player.getInventory(); + + for (int hotbar = 0; hotbar <= 8; hotbar++) { + ItemStack hotbarStack = inventory.getItem(hotbar); + + if (!shouldRefill(hotbarStack)) { + continue; + } + + int sourceSlot = findInventoryStack(inventory, hotbarStack); + + if (sourceSlot == -1) { + continue; + } + + if (replenish(player, gameMode, sourceSlot, hotbar)) { + ticks = delay.getValue(); + return; + } + } + } + + private boolean shouldRefill(ItemStack stack) { + if (stack.isEmpty()) { + return false; + } + + if (!stack.isStackable()) { + return false; + } + + int refillThreshold = scaledCount(threshold.getValue(), stack.getMaxStackSize()); + + return stack.getCount() <= refillThreshold && stack.getCount() < stack.getMaxStackSize(); + } + + private int findInventoryStack(Inventory inventory, ItemStack target) { + int minimum = scaledCount(minimumCount.getValue(), target.getMaxStackSize()); + + for (int i = 9; i <= 35; i++) { + ItemStack stack = inventory.getItem(i); + + if (stack.isEmpty()) { + continue; + } + + if (stack.getCount() < minimum) { + continue; + } + + if (!ItemStack.isSameItemSameComponents(stack, target)) { + continue; + } + + return i; + } + + return -1; + } + + private boolean replenish( + LocalPlayer player, + MultiPlayerGameMode gameMode, + int inventoryIndex, + int hotbarIndex + ) { + return switch (switchMode.getValue()) { + case Pickup -> replenishPickup(player, gameMode, inventoryIndex, hotbarIndex); + case Swap -> replenishSwap(player, gameMode, inventoryIndex, hotbarIndex); + case Quick -> replenishQuick(player, gameMode, inventoryIndex, hotbarIndex); + }; + } + + private boolean replenishPickup( + LocalPlayer player, + MultiPlayerGameMode gameMode, + int inventoryIndex, + int hotbarIndex + ) { + int sourceSlot = inventoryIndexToContainerSlot(inventoryIndex); + int hotbarSlot = inventoryIndexToContainerSlot(hotbarIndex); + + if (sourceSlot == -1 || hotbarSlot == -1) { + return false; + } + + int containerId = player.containerMenu.containerId; + + gameMode.handleInventoryMouseClick( + containerId, + sourceSlot, + 0, + ClickType.PICKUP, + player + ); + + gameMode.handleInventoryMouseClick( + containerId, + hotbarSlot, + 0, + ClickType.PICKUP, + player + ); + + gameMode.handleInventoryMouseClick( + containerId, + sourceSlot, + 0, + ClickType.PICKUP, + player + ); + + return true; + } + + private boolean replenishSwap( + LocalPlayer player, + MultiPlayerGameMode gameMode, + int inventoryIndex, + int hotbarIndex + ) { + int sourceSlot = inventoryIndexToContainerSlot(inventoryIndex); + + if (sourceSlot == -1) { + return false; + } + + gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + sourceSlot, + hotbarIndex, + ClickType.SWAP, + player + ); + + return true; + } + + private boolean replenishQuick( + LocalPlayer player, + MultiPlayerGameMode gameMode, + int inventoryIndex, + int hotbarIndex + ) { + + return replenishPickup(player, gameMode, inventoryIndex, hotbarIndex); + } + + private int scaledCount(int value, int maxStackSize) { + return Math.max(1, Math.round(value / 64.0F * maxStackSize)); + } + + private int inventoryIndexToContainerSlot(int inventoryIndex) { + if (inventoryIndex >= 0 && inventoryIndex <= 8) { + return 36 + inventoryIndex; + } + + if (inventoryIndex >= 9 && inventoryIndex <= 35) { + return inventoryIndex; + } + + return -1; + } + + @Override + public String getDisplayInfo() { + return String.valueOf(threshold.getValue()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Scaffold.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Scaffold.java new file mode 100644 index 0000000..a9c1917 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Scaffold.java @@ -0,0 +1,456 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.RotationManager; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +public class Scaffold extends Module { + public enum SwitchMode { + Normal, + Silent, + None + } + + public enum PlaceMode { + Native, + NCP + } + + private static final String ROT_ID = "scaffold"; + private static final int ROT_PRIORITY = 4; + + private final Setting multitask = bool("MultiTask", true); + private final Setting switchMode = mode("Switch", SwitchMode.Silent); + private final Setting placeMode = mode("PlaceMode", PlaceMode.NCP); + private final Setting range = num("Range", 5.0F, 1.0F, 6.0F); + private final Setting delay = num("Delay", 0, 0, 20); + private final Setting rotate = bool("Rotate", true); + private final Setting swing = bool("Swing", true); + private final Setting strict = bool("Strict", true); + private final Setting airPlace = bool("AirPlace", false); + private final Setting tower = bool("Tower", false); + private final Setting towerSpeed = num("TowerSpeed", 0.42D, 0.1D, 1.0D); + + private final Setting render = bool("Render", true); + private final Setting fillColor = color("FillColor", new Color(90, 160, 255, 65)); + private final Setting outlineColor = color("OutlineColor", new Color(90, 160, 255, 230)); + private final Setting lineWidth = num("LineWidth", 1.0F, 0.1F, 4.0F); + + private final Timer timer = new Timer(); + private final List renderPositions = new ArrayList<>(); + + private int ticks; + private int invSwapSlot = -1; + + public Scaffold() { + super("Scaffold", "Places blocks directly below you", Category.PLAYER); + } + + @Override + public void onEnable() { + ticks = delay.getValue(); + invSwapSlot = -1; + renderPositions.clear(); + timer.reset(); + } + + @Override + public void onDisable() { + ticks = 0; + invSwapSlot = -1; + renderPositions.clear(); + clearRotations(); + } + + @Override + public void onTick() { + if (nullCheck()) { + return; + } + + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + MultiPlayerGameMode gameMode = mc.gameMode; + + if (player == null || level == null || gameMode == null) { + return; + } + + if (!multitask.getValue() && player.isUsingItem()) { + return; + } + + handleTower(player); + + if (ticks < delay.getValue()) { + ticks++; + return; + } + + if (!timer.passedMs(1L)) { + return; + } + + BlockPos placePos = getBlockDirectlyBelowPlayer(player); + + renderPositions.clear(); + renderPositions.add(placePos); + + if (!isValidSpot(player, level, placePos)) { + ticks = 0; + timer.reset(); + return; + } + + int slot = findBlockSlot(player, level); + + if (slot == -1) { + ticks = 0; + timer.reset(); + return; + } + + int oldSlot = player.getInventory().getSelectedSlot(); + + if (!doSwitch(player, gameMode, slot, oldSlot)) { + ticks = 0; + timer.reset(); + return; + } + + tryPlace(player, level, gameMode, placePos); + + switchBack(player, gameMode, oldSlot); + resetSpoofIfNeeded(); + + ticks = 0; + timer.reset(); + } + + private BlockPos getBlockDirectlyBelowPlayer(LocalPlayer player) { + return player.blockPosition().below(); + } + + private boolean tryPlace( + LocalPlayer player, + ClientLevel level, + MultiPlayerGameMode gameMode, + BlockPos pos + ) { + if (rotationFailed(Vec3.atCenterOf(pos))) { + return false; + } + + if (!place(player, gameMode, pos)) { + return false; + } + + return !level.getBlockState(pos).isAir(); + } + + private boolean place(LocalPlayer player, MultiPlayerGameMode gameMode, BlockPos pos) { + BlockHitResult hitResult = buildHitResult(player, mc.level, pos); + + if (hitResult == null) { + return false; + } + + gameMode.useItemOn(player, InteractionHand.MAIN_HAND, hitResult); + + if (swing.getValue()) { + player.swing(InteractionHand.MAIN_HAND); + } + + return true; + } + + private BlockHitResult buildHitResult(LocalPlayer player, ClientLevel level, BlockPos pos) { + if (level == null) { + return null; + } + + if (airPlace.getValue()) { + return new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false); + } + + Vec3 eye = player.getEyePosition(); + + Direction bestSide = null; + BlockPos bestNeighbor = pos; + Vec3 bestHit = Vec3.atCenterOf(pos); + double bestDist = Double.MAX_VALUE; + + for (Direction dir : Direction.values()) { + BlockPos neighbor = pos.relative(dir); + BlockState state = level.getBlockState(neighbor); + + if (state.isAir() || state.canBeReplaced()) { + continue; + } + + if (state.getCollisionShape(level, neighbor).isEmpty()) { + continue; + } + + Direction side = dir.getOpposite(); + + Vec3 hit = Vec3.atCenterOf(neighbor).add( + side.getStepX() * 0.5D, + side.getStepY() * 0.5D, + side.getStepZ() * 0.5D + ); + + double dist = eye.distanceTo(hit); + + if (dist < bestDist) { + bestDist = dist; + bestSide = side; + bestNeighbor = neighbor; + bestHit = hit; + } + + if (placeMode.getValue() == PlaceMode.Native && !strict.getValue()) { + break; + } + } + + if (bestSide == null) { + return null; + } + + return new BlockHitResult(bestHit, bestSide, bestNeighbor, false); + } + + private boolean isValidSpot(LocalPlayer player, ClientLevel level, BlockPos pos) { + if (level.isOutsideBuildHeight(pos)) { + return false; + } + + BlockState state = level.getBlockState(pos); + + if (!state.isAir() && !state.canBeReplaced()) { + return false; + } + + if (player.getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) > range.getValue() * range.getValue()) { + return false; + } + + AABB box = new AABB(pos); + + if (!level.getEntitiesOfClass(Entity.class, box, entity -> !(entity instanceof ItemEntity)).isEmpty()) { + return false; + } + + return airPlace.getValue() || buildHitResult(player, level, pos) != null; + } + + private int findBlockSlot(LocalPlayer player, ClientLevel level) { + int selected = player.getInventory().getSelectedSlot(); + + if (isValidScaffoldStack(player.getInventory().getItem(selected), level)) { + return selected; + } + + for (int i = 0; i < 9; i++) { + if (isValidScaffoldStack(player.getInventory().getItem(i), level)) { + return i; + } + } + + for (int i = 9; i < 36; i++) { + if (isValidScaffoldStack(player.getInventory().getItem(i), level)) { + return i; + } + } + + return -1; + } + + private boolean isValidScaffoldStack(ItemStack stack, ClientLevel level) { + if (stack.isEmpty()) { + return false; + } + + if (!(stack.getItem() instanceof BlockItem blockItem)) { + return false; + } + + BlockState state = blockItem.getBlock().defaultBlockState(); + + if (state.isAir()) { + return false; + } + + return !state.getCollisionShape(level, BlockPos.ZERO).isEmpty(); + } + + private boolean doSwitch( + LocalPlayer player, + MultiPlayerGameMode gameMode, + int slot, + int currentHotbarSlot + ) { + if (slot < 0 || slot > 35) { + return false; + } + + int targetSlot = slot; + + if (targetSlot > 8) { + gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + targetSlot, + currentHotbarSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = targetSlot; + targetSlot = currentHotbarSlot; + } + + return switch (switchMode.getValue()) { + case Normal, Silent -> { + player.getInventory().setSelectedSlot(targetSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(targetSlot)); + yield true; + } + + case None -> player.getInventory().getSelectedSlot() == targetSlot; + }; + } + + private void switchBack(LocalPlayer player, MultiPlayerGameMode gameMode, int oldSlot) { + boolean shouldRestoreSlot = switchMode.getValue() == SwitchMode.Silent || invSwapSlot != -1; + + if (shouldRestoreSlot) { + player.getInventory().setSelectedSlot(oldSlot); + player.connection.send(new ServerboundSetCarriedItemPacket(oldSlot)); + } + + if (invSwapSlot == -1) { + return; + } + + gameMode.handleInventoryMouseClick( + player.containerMenu.containerId, + invSwapSlot, + oldSlot, + ClickType.SWAP, + player + ); + + invSwapSlot = -1; + } + + private void handleTower(LocalPlayer player) { + if (!tower.getValue()) { + return; + } + + if (!mc.options.keyJump.isDown()) { + return; + } + + if (mc.options.keyUp.isDown() + || mc.options.keyDown.isDown() + || mc.options.keyLeft.isDown() + || mc.options.keyRight.isDown()) { + return; + } + + player.setDeltaMovement( + player.getDeltaMovement().x, + towerSpeed.getValue(), + player.getDeltaMovement().z + ); + } + + private boolean rotationFailed(Vec3 pos) { + return rotate.getValue() && !applyRotations(pos); + } + + private boolean applyRotations(Vec3 pos) { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return true; + } + + return rm.applyRotationTo(ROT_ID, ROT_PRIORITY, pos); + } + + private void resetSpoofIfNeeded() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + RotationManager.RotationMethod method = rm.getConfig().getRotationMethod(); + + if (method == RotationManager.RotationMethod.SPOOF + || method == RotationManager.RotationMethod.SMOOTH_SPOOF + || method == RotationManager.RotationMethod.GCD + || method == RotationManager.RotationMethod.NOISE) { + rm.resetSpoofedRotations(); + } + } + + private void clearRotations() { + RotationManager rm = nolongerhuman.rotationManager; + + if (rm == null) { + return; + } + + rm.cancel(ROT_ID); + rm.clearRotations(ROT_PRIORITY); + rm.resetSpoofedRotations(); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (!render.getValue() || renderPositions.isEmpty()) { + return; + } + + PoseStack stack = event.getMatrix(); + + for (BlockPos pos : renderPositions) { + RenderUtil.drawBoxFilled(stack, pos, fillColor.getValue()); + RenderUtil.drawBox(stack, pos, outlineColor.getValue(), lineWidth.getValue()); + } + } + + @Override + public String getDisplayInfo() { + return switchMode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Velocity.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Velocity.java new file mode 100644 index 0000000..7ec0e1e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/player/Velocity.java @@ -0,0 +1,87 @@ +package me.humanbeing.nolongerhuman.features.modules.player; + +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import net.minecraft.client.Minecraft; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.world.entity.Entity; + +public class Velocity extends Module { + + private static Velocity INSTANCE; + + public Velocity() { + super("Velocity", "Cancels all knockback", Category.PLAYER); + INSTANCE = this; + } + + @Subscribe + @SuppressWarnings("unused") + private void onPacketReceive(PacketEvent.Receive event) { + Minecraft mc = Minecraft.getInstance(); + + if (mc.player == null || mc.level == null) { + return; + } + + + if (event.getPacket() instanceof ClientboundSetEntityMotionPacket motion) { + if (motion.getId() == mc.player.getId()) { + event.cancel(); + } + + return; + } + + + if (event.getPacket() instanceof ClientboundExplodePacket explosion) { + if (explosion.playerKnockback().isPresent()) { + event.cancel(); + } + } + } + + + @SuppressWarnings("unused") + public static boolean shouldCancelCollision(Entity self, Entity other) { + Velocity module = INSTANCE; + + if (module == null || !module.isEnabled()) { + return false; + } + + Minecraft mc = Minecraft.getInstance(); + + if (mc.player == null) { + return false; + } + + return self == mc.player || other == mc.player; + } + + @SuppressWarnings("unused") + public static boolean shouldCancelPush(Entity entity) { + Velocity module = INSTANCE; + + if (module == null || !module.isEnabled()) { + return false; + } + + Minecraft mc = Minecraft.getInstance(); + + if (mc.player == null) { + return false; + } + + return entity == mc.player; + } + + + @SuppressWarnings("unused") + public static boolean shouldCancelVelocity() { + Velocity module = INSTANCE; + return module != null && module.isEnabled(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Ambience.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Ambience.java new file mode 100644 index 0000000..5f9426c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Ambience.java @@ -0,0 +1,492 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.network.protocol.Packet; + +import java.awt.Color; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class Ambience extends Module { + public static Ambience INSTANCE; + + public enum WeatherMode { + Normal, + Clear, + Ash, + Rain, + Thunder + } + + public final Setting timeChanger = bool("TimeChanger", true); + public final Setting time = num("Time", 1000, 0, 24000); + + public final Setting weather = mode("Weather", WeatherMode.Clear); + + public final Setting customBackground = bool("CustomBackground", false); + public final Setting backgroundColor = color("BackgroundColor", new Color(0, 0, 0, 255)); + + public final Setting customFog = bool("CustomFog", true); + public final Setting fogColor = color("FogColor", new Color(0, 255, 255, 255)); + + public final Setting customSky = bool("CustomSky", true); + public final Setting skyColor = color("SkyColor", new Color(0, 255, 255, 255)); + + private long oldTime = 0L; + private float oldRainLevel = 0.0F; + private float oldThunderLevel = 0.0F; + + public Ambience() { + super("Ambience", "Changes time, weather, background, fog, and sky color", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + ClientLevel level = mc.level; + + if (level == null) { + return; + } + + oldTime = level.getDayTime(); + oldRainLevel = level.getRainLevel(1.0F); + oldThunderLevel = level.getThunderLevel(1.0F); + } + + @Override + public void onDisable() { + ClientLevel level = mc.level; + + if (level == null) { + return; + } + + if (timeChanger.getValue()) { + setClientTime(level, oldTime); + } + + if (weather.getValue() != WeatherMode.Normal) { + level.setRainLevel(oldRainLevel); + level.setThunderLevel(oldThunderLevel); + } + } + + @Override + public void onTick() { + ClientLevel level = mc.level; + + if (level == null) { + return; + } + + if (timeChanger.getValue()) { + setClientTime(level, getWantedTime()); + } + + applyWeather(level); + } + + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + Packet packet = event.getPacket(); + + if (packet == null) { + return; + } + + if (timeChanger.getValue() && isTimePacket(packet)) { + oldTime = readPacketLong(packet, oldTime); + event.cancel(); + return; + } + + if (weather.getValue() != WeatherMode.Normal && isWeatherPacket(packet)) { + event.cancel(); + } + } + + private long getWantedTime() { + return time.getValue().longValue() * 1000L; + } + + private void applyWeather(ClientLevel level) { + switch (weather.getValue()) { + case Normal -> { + } + + case Clear, Ash -> { + level.setRainLevel(0.0F); + level.setThunderLevel(0.0F); + } + + case Rain -> { + level.setRainLevel(1.0F); + level.setThunderLevel(0.0F); + } + + case Thunder -> { + level.setRainLevel(1.0F); + level.setThunderLevel(1.0F); + } + } + } + + private void setClientTime(ClientLevel level, long value) { + Object levelData = getLevelData(level); + + if (levelData != null) { + if (callLongSetter(levelData, value)) { + return; + } + + if (writeTimeFields(levelData, value, true)) { + return; + } + } + + if (callLongSetter(level, value)) { + return; + } + + if (writeTimeFields(level, value, false)) { + return; + } + + Object reflectedLevelData = findLevelDataObject(level); + + if (reflectedLevelData != null) { + if (callLongSetter(reflectedLevelData, value)) { + return; + } + + writeTimeFields(reflectedLevelData, value, true); + } + } + + private Object getLevelData(ClientLevel level) { + try { + return level.getLevelData(); + } catch (Throwable ignored) { + return null; + } + } + + private Object findLevelDataObject(ClientLevel level) { + for (Class clazz = level.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(level); + + if (value == null) { + continue; + } + + String typeName = value.getClass().getName().toLowerCase(); + + if (typeName.contains("leveldata") + || typeName.contains("clientleveldata") + || typeName.contains("properties") + || hasDayTimeGetter(value)) { + return value; + } + } catch (Throwable ignored) { + } + } + } + + return null; + } + + private boolean hasDayTimeGetter(Object object) { + String[] methodNames = { + "getDayTime", + "dayTime", + "getTime", + "time", + "getGameTime", + "gameTime" + }; + + for (String methodName : methodNames) { + if (findNoArgMethod(object.getClass(), methodName) != null) { + return true; + } + } + + return false; + } + + private boolean callLongSetter(Object object, long value) { + String[] methodNames = { + "setDayTime", + "setGameTime", + "setTime", + "setTimeOfDay", + "dayTime", + "gameTime", + "time" + }; + + for (String methodName : methodNames) { + Method method = findLongSetter(object.getClass(), methodName); + + if (method == null) { + continue; + } + + try { + method.setAccessible(true); + method.invoke(object, value); + return true; + } catch (Throwable ignored) { + } + } + + return false; + } + + private Method findLongSetter(Class startClass, String methodName) { + for (Class clazz = startClass; clazz != null; clazz = clazz.getSuperclass()) { + for (Method method : clazz.getDeclaredMethods()) { + if (!method.getName().equals(methodName)) { + continue; + } + + if (method.getParameterCount() != 1) { + continue; + } + + Class parameter = method.getParameterTypes()[0]; + + if (parameter == long.class || parameter == Long.class) { + return method; + } + } + } + + return null; + } + + private Method findNoArgMethod(Class startClass, String methodName) { + for (Class clazz = startClass; clazz != null; clazz = clazz.getSuperclass()) { + for (Method method : clazz.getDeclaredMethods()) { + if (!method.getName().equals(methodName)) { + continue; + } + + if (method.getParameterCount() == 0) { + return method; + } + } + } + + return null; + } + + private boolean writeTimeFields(Object object, long value, boolean allowAllLongFields) { + boolean wrote = false; + + for (Class clazz = object.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + + Class type = field.getType(); + + if (type != long.class && type != Long.class) { + continue; + } + + String name = field.getName().toLowerCase(); + + if (!allowAllLongFields && !isTimeFieldName(name)) { + continue; + } + + if (name.contains("seed")) { + continue; + } + + try { + field.setAccessible(true); + + if (type == long.class) { + field.setLong(object, value); + } else { + field.set(object, value); + } + + wrote = true; + } catch (Throwable ignored) { + } + } + } + + return wrote; + } + + private boolean isTimeFieldName(String name) { + return name.contains("daytime") + || name.contains("day_time") + || name.contains("gametime") + || name.contains("game_time") + || name.contains("timeofday") + || name.contains("time_of_day") + || name.equals("time"); + } + + private boolean isTimePacket(Packet packet) { + String name = packet.getClass().getSimpleName().toLowerCase(); + + return name.contains("settime") + || name.contains("timeupdate") + || name.contains("time"); + } + + private boolean isWeatherPacket(Packet packet) { + String name = packet.getClass().getSimpleName().toLowerCase(); + + if (!name.contains("gameevent") && !name.contains("gamestate")) { + return false; + } + + String packetText = packet.toString().toLowerCase(); + + if (packetText.contains("rain") || packetText.contains("thunder")) { + return true; + } + + Object eventType = callNoArg(packet, "getEvent"); + + if (eventType == null) { + eventType = callNoArg(packet, "event"); + } + + if (eventType == null) { + eventType = callNoArg(packet, "type"); + } + + if (eventType == null) { + return true; + } + + String eventText = eventType.toString().toLowerCase(); + + return eventText.contains("rain") + || eventText.contains("thunder") + || eventText.contains("raining"); + } + + private long readPacketLong(Packet packet, long fallback) { + String[] methods = { + "getDayTime", + "dayTime", + "getTime", + "time", + "getGameTime", + "gameTime" + }; + + for (String methodName : methods) { + Object value = callNoArg(packet, methodName); + + if (value instanceof Number number) { + return number.longValue(); + } + } + + return fallback; + } + + private Object callNoArg(Object object, String methodName) { + Method method = findNoArgMethod(object.getClass(), methodName); + + if (method == null) { + return null; + } + + try { + method.setAccessible(true); + return method.invoke(object); + } catch (Throwable ignored) { + return null; + } + } + + public static boolean isEnabledModule() { + return INSTANCE != null && INSTANCE.isEnabled(); + } + + public static boolean shouldUseBackgroundColor() { + return isEnabledModule() && INSTANCE.customBackground.getValue(); + } + + public static boolean shouldUseFogColor() { + return isEnabledModule() && INSTANCE.customFog.getValue(); + } + + public static boolean shouldUseSkyColor() { + return isEnabledModule() && INSTANCE.customSky.getValue(); + } + + public static Color getBackgroundColor() { + return INSTANCE == null ? Color.BLACK : INSTANCE.backgroundColor.getValue(); + } + + public static Color getFogColor() { + return INSTANCE == null ? Color.WHITE : INSTANCE.fogColor.getValue(); + } + + public static Color getSkyColor() { + return INSTANCE == null ? Color.WHITE : INSTANCE.skyColor.getValue(); + } + + public static int toArgb(Color color) { + return color.getAlpha() << 24 + | color.getRed() << 16 + | color.getGreen() << 8 + | color.getBlue(); + } + + public static float red(Color color) { + return color.getRed() / 255.0F; + } + + public static float green(Color color) { + return color.getGreen() / 255.0F; + } + + public static float blue(Color color) { + return color.getBlue() / 255.0F; + } + + public static float alpha(Color color) { + return color.getAlpha() / 255.0F; + } + + @Override + public String getDisplayInfo() { + if (weather.getValue() != WeatherMode.Normal) { + return weather.getValue().name(); + } + + if (timeChanger.getValue()) { + return String.valueOf(time.getValue()); + } + + return "Color"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/AttackAnimations.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/AttackAnimations.java new file mode 100644 index 0000000..a10aaea --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/AttackAnimations.java @@ -0,0 +1,308 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.phys.EntityHitResult; +import net.minecraft.world.phys.HitResult; + +public class AttackAnimations extends Module { + + public enum Mode { + Cancel, + Classic, + Slide, + Spin, + Push, + Tilt, + Swipe, + Flip + } + + private static AttackAnimations INSTANCE; + + public final Setting mode = mode("Mode", Mode.Classic); + public final Setting intensity = num("Intensity", 1.0, 0.1, 3.0); + public final Setting speed = num("Speed", 1.0, 0.1, 3.0); + public final Setting overrideViewModel = bool("OverrideViewModel", true); + + public AttackAnimations() { + super("AttackAnimations", "Changes first person attack animations", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + } + + public static boolean shouldCancelVanillaAttack(HumanoidArm arm) { + AttackAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!isMainHandArm(arm)) { + return false; + } + + if (module.mode.getValue() != Mode.Cancel) { + return false; + } + + return isAttackAnimationActive(); + } + + public static boolean shouldReplaceVanillaAttack(HumanoidArm arm) { + AttackAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!isMainHandArm(arm)) { + return false; + } + + if (module.mode.getValue() == Mode.Cancel) { + return true; + } + + return isAttackAnimationActive() && module.overrideViewModel.getValue(); + } + + public static boolean isViewModelOverrideActive(ItemDisplayContext displayContext) { + AttackAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!module.overrideViewModel.getValue()) { + return false; + } + + if (!isMainHandContext(displayContext)) { + return false; + } + + return isAttackAnimationActive(); + } + + public static void applyAnimation(PoseStack poseStack, ItemDisplayContext displayContext) { + AttackAnimations module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (poseStack == null) { + return; + } + + if (!isMainHandContext(displayContext)) { + return; + } + + if (!isAttackAnimationActive()) { + return; + } + + Mode currentMode = module.mode.getValue(); + + if (currentMode == Mode.Cancel) { + return; + } + + module.apply(poseStack, displayContext, currentMode); + } + + public static boolean isAttackAnimationActive() { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + if (BreakAnimations.isBreakAnimationActive()) { + return false; + } + + if (player.isUsingItem()) { + return false; + } + + float swing = player.getAttackAnim(1.0f); + + if (swing > 0.0f) { + return true; + } + + if (!mc.options.keyAttack.isDown()) { + return false; + } + + HitResult hitResult = mc.hitResult; + + return hitResult instanceof EntityHitResult + || hitResult == null + || hitResult.getType() == HitResult.Type.MISS; + } + + private void apply(PoseStack poseStack, ItemDisplayContext displayContext, Mode currentMode) { + float progress = attackProgress(); + float swing = (float) Math.sin(progress * Math.PI); + float hand = handSign(displayContext); + float amount = intensity.getValue().floatValue(); + + switch (currentMode) { + case Classic -> { + poseStack.translate( + hand * -0.16f * amount * swing, + 0.08f * amount * swing, + -0.20f * amount * swing + ); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * -35.0f * amount * swing)); + poseStack.mulPose(Axis.XP.rotationDegrees(-22.0f * amount * swing)); + } + + case Slide -> { + poseStack.translate( + hand * -0.35f * amount * swing, + 0.04f * amount * swing, + -0.10f * amount * swing + ); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * -14.0f * amount * swing)); + } + + case Spin -> { + poseStack.translate( + hand * -0.10f * amount * swing, + 0.05f * amount * swing, + -0.12f * amount * swing + ); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * -220.0f * amount * swing)); + } + + case Push -> { + poseStack.translate( + 0.0f, + 0.0f, + -0.40f * amount * swing + ); + poseStack.mulPose(Axis.XP.rotationDegrees(-18.0f * amount * swing)); + } + + case Tilt -> { + poseStack.translate( + hand * -0.10f * amount * swing, + 0.02f * amount * swing, + -0.12f * amount * swing + ); + poseStack.mulPose(Axis.XP.rotationDegrees(-30.0f * amount * swing)); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * -42.0f * amount * swing)); + } + + case Swipe -> { + poseStack.translate( + hand * -0.28f * amount * swing, + 0.08f * amount * swing, + -0.16f * amount * swing + ); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * -55.0f * amount * swing)); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * -28.0f * amount * swing)); + } + + case Flip -> { + poseStack.translate( + hand * -0.08f * amount * swing, + 0.04f * amount * swing, + -0.16f * amount * swing + ); + poseStack.mulPose(Axis.XP.rotationDegrees(160.0f * amount * swing)); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * -35.0f * amount * swing)); + } + + case Cancel -> { + } + } + } + + private float attackProgress() { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player != null) { + float swing = player.getAttackAnim(1.0f); + + if (swing > 0.0f) { + return Math.min(1.0f, swing * speed.getValue().floatValue()); + } + } + + double duration = Math.max(50.0, 260.0 / speed.getValue()); + long time = System.currentTimeMillis(); + + return (float) ((time % (long) duration) / duration); + } + + private static float handSign(ItemDisplayContext displayContext) { + return displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND ? -1.0f : 1.0f; + } + + private static boolean isMainHandContext(ItemDisplayContext displayContext) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + HumanoidArm mainArm = player.getMainArm(); + + if (displayContext == ItemDisplayContext.FIRST_PERSON_RIGHT_HAND) { + return mainArm == HumanoidArm.RIGHT; + } + + if (displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND) { + return mainArm == HumanoidArm.LEFT; + } + + return false; + } + + private static boolean isMainHandArm(HumanoidArm arm) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + return player != null && arm == player.getMainArm(); + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/AuraCircles.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/AuraCircles.java new file mode 100644 index 0000000..6007ebe --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/AuraCircles.java @@ -0,0 +1,340 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.Layers; +import net.minecraft.client.Camera; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class AuraCircles extends Module { + private static AuraCircles INSTANCE; + + public final Setting color = color("Color", new Color(255, 90, 120, 220)); + + public final Setting glow = bool("Glow", true); + public final Setting glowColor = color("GlowColor", new Color(255, 90, 120, 120)); + public final Setting glowSize = num("GlowSize", 0.22f, 0.01f, 2.0f); + public final Setting glowPasses = num("GlowPasses", 5, 1, 16); + + public final Setting radius = num("Radius", 0.85f, 0.1f, 4.0f); + public final Setting heightOffset = num("HeightOffset", 0.15f, -2.0f, 2.0f); + public final Setting dropDistance = num("DropDistance", 1.35f, 0.0f, 5.0f); + public final Setting lineWidth = num("LineWidth", 2.0f, 0.1f, 6.0f); + public final Setting fadeInMs = num("FadeIn", 80, 1, 1000); + public final Setting fadeOutMs = num("FadeOut", 650, 1, 3000); + public final Setting segments = num("Segments", 72, 12, 180); + public final Setting maxCircles = num("MaxCircles", 32, 1, 100); + + private final List circles = new ArrayList<>(); + + public AuraCircles() { + super("AuraCircles", "Renders fading circles when Aura attacks entities", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onDisable() { + circles.clear(); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (mc.player == null || mc.level == null) { + circles.clear(); + return; + } + + if (circles.isEmpty()) { + return; + } + + Camera camera = mc.getEntityRenderDispatcher().camera; + + if (camera == null) { + return; + } + + Vec3 cameraPos = camera.position(); + long now = System.currentTimeMillis(); + long lifetime = getLifetime(); + + Iterator iterator = circles.iterator(); + + while (iterator.hasNext()) { + Circle circle = iterator.next(); + long age = now - circle.startTime(); + + if (age >= lifetime) { + iterator.remove(); + continue; + } + + drawCircle(event.getMatrix(), cameraPos, circle, age); + } + } + + private void drawCircle(PoseStack stack, Vec3 cameraPos, Circle circle, long age) { + int fadeIn = Math.max(1, fadeInMs.getValue()); + int fadeOut = Math.max(1, fadeOutMs.getValue()); + + double alphaMultiplier; + double yOffset; + + if (age <= fadeIn) { + double progress = clamp((double) age / (double) fadeIn, 0.0D, 1.0D); + + alphaMultiplier = easeOut(progress); + yOffset = 0.0D; + } else { + double progress = clamp((double) (age - fadeIn) / (double) fadeOut, 0.0D, 1.0D); + + alphaMultiplier = 1.0D - easeIn(progress); + yOffset = -dropDistance.getValue() * easeOut(progress); + } + + if (alphaMultiplier <= 0.01D) { + return; + } + + Color renderColor = withAlphaMultiplier(color.getValue(), alphaMultiplier); + Color renderGlowColor = withAlphaMultiplier(glowColor.getValue(), alphaMultiplier); + + double renderRadius = circle.radius(); + + if (age <= fadeIn) { + double progress = clamp((double) age / (double) fadeIn, 0.0D, 1.0D); + renderRadius *= 0.65D + 0.35D * easeOut(progress); + } + + Vec3 center = circle.center().add(0.0D, yOffset, 0.0D); + int circleSegments = Math.max(12, segments.getValue()); + + drawGlow( + stack, + cameraPos, + center, + renderRadius, + renderGlowColor, + lineWidth.getValue(), + circleSegments + ); + + drawFlatCircle( + stack, + cameraPos, + center, + renderRadius, + renderColor, + lineWidth.getValue(), + circleSegments + ); + } + + private void drawGlow( + PoseStack stack, + Vec3 cameraPos, + Vec3 center, + double radius, + Color color, + float width, + int segments + ) { + if (!glow.getValue()) { + return; + } + + if (color.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, glowPasses.getValue()); + double size = Math.max(0.0D, glowSize.getValue()); + + if (size <= 0.0D) { + return; + } + + for (int i = passes; i >= 1; i--) { + double progress = i / (double) passes; + double offset = size * progress; + double alphaFactor = (1.0D - progress) * 0.60D + 0.12D; + + Color passColor = withAlphaMultiplier(color, alphaFactor); + float passWidth = width + (float) (i * 0.25D); + + double outerRadius = radius + offset; + double innerRadius = radius - offset; + + drawFlatCircle( + stack, + cameraPos, + center, + outerRadius, + passColor, + passWidth, + segments + ); + + if (innerRadius > 0.01D) { + drawFlatCircle( + stack, + cameraPos, + center, + innerRadius, + passColor, + passWidth, + segments + ); + } + } + } + + private void drawFlatCircle( + PoseStack stack, + Vec3 cameraPos, + Vec3 center, + double radius, + Color color, + float width, + int segments + ) { + if (width <= 0.0F || radius <= 0.0D) { + return; + } + + float cx = (float) (center.x - cameraPos.x); + float cy = (float) (center.y - cameraPos.y); + float cz = (float) (center.z - cameraPos.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int rgb = color.getRGB(); + + for (int i = 0; i < segments; i++) { + double angle1 = (Math.PI * 2.0D * i) / segments; + double angle2 = (Math.PI * 2.0D * (i + 1)) / segments; + + float x1 = cx + (float) (Math.cos(angle1) * radius); + float z1 = cz + (float) (Math.sin(angle1) * radius); + float x2 = cx + (float) (Math.cos(angle2) * radius); + float z2 = cz + (float) (Math.sin(angle2) * radius); + + addLine(buffer, pose, rgb, width, x1, cy, z1, x2, cy, z2); + } + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void addLine( + BufferBuilder buffer, + PoseStack.Pose pose, + int color, + float width, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2 + ) { + float nx = x2 - x1; + float ny = y2 - y1; + float nz = z2 - z1; + + buffer.addVertex(pose, x1, y1, z1) + .setColor(color) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + + buffer.addVertex(pose, x2, y2, z2) + .setColor(color) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + } + + private long getLifetime() { + return Math.max(1, fadeInMs.getValue()) + Math.max(1, fadeOutMs.getValue()); + } + + private double easeIn(double progress) { + progress = clamp(progress, 0.0D, 1.0D); + return progress * progress * progress; + } + + private double easeOut(double progress) { + progress = clamp(progress, 0.0D, 1.0D); + + double inverse = 1.0D - progress; + + return 1.0D - inverse * inverse * inverse; + } + + private double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = clamp(multiplier, 0.0D, 1.0D); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + public static void spawn(Entity entity) { + AuraCircles module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (entity == null) { + return; + } + + module.addCircle(entity); + } + + private void addCircle(Entity entity) { + while (circles.size() >= maxCircles.getValue()) { + circles.remove(0); + } + + double entityRadius = Math.max(entity.getBbWidth(), radius.getValue()); + + Vec3 center = new Vec3( + entity.getX(), + entity.getY() + entity.getBbHeight() + heightOffset.getValue(), + entity.getZ() + ); + + circles.add(new Circle(center, entityRadius, System.currentTimeMillis())); + } + + private record Circle(Vec3 center, double radius, long startTime) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BlockHighlight.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BlockHighlight.java new file mode 100644 index 0000000..8ac6e3c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BlockHighlight.java @@ -0,0 +1,376 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.impl.render.RenderBlockOutlineEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.shapes.VoxelShape; + +import java.awt.Color; + +public class BlockHighlight extends Module { + public enum AnimationMode { + None, + Linear, + EaseIn, + EaseOut, + EaseInOut, + Elastic, + Fade + } + + public final Setting fill = bool("Fill", true); + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 70)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + + public final Setting glow = bool("Glow", true); + public final Setting glowColor = color("GlowColor", new Color(255, 255, 255, 115)); + public final Setting glowSize = num("GlowSize", 0.20f, 0.01f, 1.0f); + public final Setting glowPasses = num("GlowPasses", 5, 1, 16); + + public final Setting lineWidth = num("LineWidth", 1.0f, 0.1f, 5.0f); + public final Setting animation = mode("Animation", AnimationMode.EaseOut); + public final Setting animationTime = num("AnimTime", 150, 0, 1000); + + private AABB startBox = null; + private AABB currentBox = null; + private AABB targetBox = null; + private AABB fadeOutBox = null; + private AABB fadeInBox = null; + private BlockPos lastPos = null; + private long animationStart = 0L; + + public BlockHighlight() { + super("BlockHighlight", "Draws box at the block that you are looking at", Category.RENDER); + } + + @Override + public void onDisable() { + resetAnimation(); + } + + @Subscribe + public void onRender3D(Render3DEvent event) { + if (mc.level == null || mc.hitResult == null) { + resetAnimation(); + return; + } + + if (!(mc.hitResult instanceof BlockHitResult result)) { + resetAnimation(); + return; + } + + if (result.getType() == HitResult.Type.MISS) { + resetAnimation(); + return; + } + + BlockPos pos = result.getBlockPos(); + VoxelShape shape = mc.level.getBlockState(pos).getShape(mc.level, pos); + + if (shape.isEmpty()) { + resetAnimation(); + return; + } + + AABB box = shape.bounds().move(pos); + + updateAnimation(pos, box); + + if (animation.getValue() == AnimationMode.Fade) { + renderFade(event.getMatrix()); + return; + } + + AABB renderBox = getRenderBox(); + + if (renderBox == null) { + return; + } + + draw(renderBox, event.getMatrix(), fillColor.getValue(), outlineColor.getValue()); + } + + @Subscribe + public void onRenderBlockOutline(RenderBlockOutlineEvent event) { + event.cancel(); + } + + private void updateAnimation(BlockPos pos, AABB newTarget) { + AnimationMode mode = animation.getValue(); + + if (mode == AnimationMode.None || animationTime.getValue() <= 0) { + startBox = newTarget; + currentBox = newTarget; + targetBox = newTarget; + fadeOutBox = null; + fadeInBox = newTarget; + lastPos = pos; + animationStart = System.currentTimeMillis(); + return; + } + + if (targetBox == null || lastPos == null || !lastPos.equals(pos)) { + if (mode == AnimationMode.Fade) { + fadeOutBox = targetBox; + fadeInBox = newTarget; + startBox = newTarget; + currentBox = newTarget; + targetBox = newTarget; + } else { + startBox = currentBox == null ? newTarget : currentBox; + targetBox = newTarget; + fadeOutBox = null; + fadeInBox = null; + } + + lastPos = pos; + animationStart = System.currentTimeMillis(); + } + } + + private AABB getRenderBox() { + if (targetBox == null) { + return null; + } + + if (animation.getValue() == AnimationMode.None || animationTime.getValue() <= 0) { + currentBox = targetBox; + return currentBox; + } + + if (startBox == null) { + startBox = targetBox; + } + + long now = System.currentTimeMillis(); + double progress = (double) (now - animationStart) / (double) animationTime.getValue(); + + progress = clamp(progress, 0.0D, 1.0D); + + double eased = ease(progress, animation.getValue()); + + currentBox = lerp(startBox, targetBox, eased); + + if (progress >= 1.0D) { + currentBox = targetBox; + startBox = targetBox; + } + + return currentBox; + } + + private void renderFade(PoseStack stack) { + if (targetBox == null) { + return; + } + + if (animationTime.getValue() <= 0) { + draw(targetBox, stack, fillColor.getValue(), outlineColor.getValue()); + fadeOutBox = null; + fadeInBox = targetBox; + currentBox = targetBox; + return; + } + + long now = System.currentTimeMillis(); + double progress = (double) (now - animationStart) / (double) animationTime.getValue(); + + progress = clamp(progress, 0.0D, 1.0D); + + double eased = ease(progress, AnimationMode.EaseOut); + double fadeOutAlpha = 1.0D - eased; + + if (fadeOutBox != null && fadeOutAlpha > 0.01D) { + draw( + fadeOutBox, + stack, + withAlphaMultiplier(fillColor.getValue(), fadeOutAlpha), + withAlphaMultiplier(outlineColor.getValue(), fadeOutAlpha), + withAlphaMultiplier(glowColor.getValue(), fadeOutAlpha) + ); + } + + if (fadeInBox != null && eased > 0.01D) { + draw( + fadeInBox, + stack, + withAlphaMultiplier(fillColor.getValue(), eased), + withAlphaMultiplier(outlineColor.getValue(), eased), + withAlphaMultiplier(glowColor.getValue(), eased) + ); + } + + if (progress >= 1.0D) { + fadeOutBox = null; + fadeInBox = targetBox; + currentBox = targetBox; + } + } + + private void draw(AABB box, PoseStack stack, Color fillColor, Color outlineColor) { + draw(box, stack, fillColor, outlineColor, glowColor.getValue()); + } + + private void draw(AABB box, PoseStack stack, Color fillColor, Color outlineColor, Color currentGlowColor) { + drawInwardGlow(stack, box, currentGlowColor); + + if (fill.getValue()) { + RenderUtil.drawBoxFilled(stack, box, fillColor); + } + + RenderUtil.drawBox(stack, box, outlineColor, lineWidth.getValue()); + } + + private void drawInwardGlow(PoseStack stack, AABB box, Color color) { + if (!glow.getValue()) { + return; + } + + if (color.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, glowPasses.getValue()); + double maxInset = getMaxInset(box); + double wantedInset = Math.min(glowSize.getValue(), maxInset); + + if (wantedInset <= 0.0D) { + return; + } + + for (int i = 0; i < passes; i++) { + double progress = passes <= 1 ? 0.0D : i / (double) (passes - 1); + double inset = wantedInset * progress; + + AABB glowBox = insetBox(box, inset); + + if (glowBox == null) { + continue; + } + + double alphaFactor = (1.0D - progress) * 0.55D + 0.10D; + Color passFill = withAlphaMultiplier(color, alphaFactor * 0.45D); + Color passOutline = withAlphaMultiplier(color, alphaFactor); + + RenderUtil.drawBoxFilled(stack, glowBox, passFill); + RenderUtil.drawBox(stack, glowBox, passOutline, lineWidth.getValue() + (float) ((passes - i) * 0.12D)); + } + } + + private double getMaxInset(AABB box) { + double width = box.maxX - box.minX; + double height = box.maxY - box.minY; + double depth = box.maxZ - box.minZ; + + return Math.max(0.0D, Math.min(width, Math.min(height, depth)) * 0.5D - 0.001D); + } + + private AABB insetBox(AABB box, double inset) { + double minX = box.minX + inset; + double minY = box.minY + inset; + double minZ = box.minZ + inset; + double maxX = box.maxX - inset; + double maxY = box.maxY - inset; + double maxZ = box.maxZ - inset; + + if (maxX <= minX || maxY <= minY || maxZ <= minZ) { + return null; + } + + return new AABB( + minX, + minY, + minZ, + maxX, + maxY, + maxZ + ); + } + + private AABB lerp(AABB from, AABB to, double progress) { + return new AABB( + lerp(from.minX, to.minX, progress), + lerp(from.minY, to.minY, progress), + lerp(from.minZ, to.minZ, progress), + lerp(from.maxX, to.maxX, progress), + lerp(from.maxY, to.maxY, progress), + lerp(from.maxZ, to.maxZ, progress) + ); + } + + private double lerp(double from, double to, double progress) { + return from + (to - from) * progress; + } + + private double ease(double progress, AnimationMode mode) { + progress = clamp(progress, 0.0D, 1.0D); + + return switch (mode) { + case None, Linear, Fade -> progress; + case EaseIn -> progress * progress * progress; + case EaseOut -> { + double inverse = 1.0D - progress; + yield 1.0D - inverse * inverse * inverse; + } + case EaseInOut -> { + if (progress < 0.5D) { + yield 4.0D * progress * progress * progress; + } + + double value = -2.0D * progress + 2.0D; + yield 1.0D - (value * value * value) / 2.0D; + } + case Elastic -> { + if (progress == 0.0D || progress == 1.0D) { + yield progress; + } + + double c4 = (2.0D * Math.PI) / 3.0D; + + yield Math.pow(2.0D, -10.0D * progress) * Math.sin((progress * 10.0D - 0.75D) * c4) + 1.0D; + } + }; + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = clamp(multiplier, 0.0D, 1.0D); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + private double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private void resetAnimation() { + startBox = null; + currentBox = null; + targetBox = null; + fadeOutBox = null; + fadeInBox = null; + lastPos = null; + animationStart = 0L; + } + + @Override + public String getDisplayInfo() { + return animation.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BreakAnimations.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BreakAnimations.java new file mode 100644 index 0000000..811e5cb --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BreakAnimations.java @@ -0,0 +1,286 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.phys.HitResult; + +public class BreakAnimations extends Module { + + public enum Mode { + Cancel, + Chop, + Saw, + Drill, + Shake, + Pull, + Spin, + Push + } + + private static BreakAnimations INSTANCE; + + public final Setting mode = mode("Mode", Mode.Chop); + public final Setting intensity = num("Intensity", 1.0, 0.1, 3.0); + public final Setting speed = num("Speed", 1.0, 0.1, 3.0); + public final Setting overrideViewModel = bool("OverrideViewModel", true); + + public BreakAnimations() { + super("BreakAnimations", "Changes first person block breaking animations", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + } + + public static boolean shouldCancelVanillaBreak(HumanoidArm arm) { + BreakAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!isMainHandArm(arm)) { + return false; + } + + if (module.mode.getValue() != Mode.Cancel) { + return false; + } + + return isBreakAnimationActive(); + } + + public static boolean shouldReplaceVanillaBreak(HumanoidArm arm) { + BreakAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!isMainHandArm(arm)) { + return false; + } + + if (module.mode.getValue() == Mode.Cancel) { + return true; + } + + return isBreakAnimationActive() && module.overrideViewModel.getValue(); + } + + public static boolean isViewModelOverrideActive(ItemDisplayContext displayContext) { + BreakAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!module.overrideViewModel.getValue()) { + return false; + } + + if (!isMainHandContext(displayContext)) { + return false; + } + + return isBreakAnimationActive(); + } + + public static void applyAnimation(PoseStack poseStack, ItemDisplayContext displayContext) { + BreakAnimations module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (poseStack == null) { + return; + } + + if (!isMainHandContext(displayContext)) { + return; + } + + if (!isBreakAnimationActive()) { + return; + } + + Mode currentMode = module.mode.getValue(); + + if (currentMode == Mode.Cancel) { + return; + } + + module.apply(poseStack, displayContext, currentMode); + } + + public static boolean isBreakAnimationActive() { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + if (!mc.options.keyAttack.isDown()) { + return false; + } + + if (player.isUsingItem()) { + return false; + } + + HitResult hitResult = mc.hitResult; + + return hitResult != null && hitResult.getType() == HitResult.Type.BLOCK; + } + + private void apply(PoseStack poseStack, ItemDisplayContext displayContext, Mode currentMode) { + float progress = animationProgress(300.0); + float swing = (float) Math.sin(progress * Math.PI * 2.0); + float absSwing = Math.abs(swing); + float hand = handSign(displayContext); + float amount = intensity.getValue().floatValue(); + + switch (currentMode) { + case Chop -> { + poseStack.translate( + hand * -0.08f * amount * absSwing, + -0.03f * amount * absSwing, + -0.18f * amount * absSwing + ); + poseStack.mulPose(Axis.XP.rotationDegrees(-38.0f * amount * absSwing)); + } + + case Saw -> { + poseStack.translate( + hand * 0.16f * amount * swing, + 0.0f, + -0.08f * amount * absSwing + ); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * 10.0f * amount * swing)); + } + + case Drill -> { + poseStack.translate( + 0.0f, + 0.0f, + -0.16f * amount * absSwing + ); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * 360.0f * amount * progress)); + } + + case Shake -> { + poseStack.translate( + hand * 0.06f * amount * swing, + 0.04f * amount * -swing, + -0.10f * amount * absSwing + ); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * 12.0f * amount * swing)); + } + + case Pull -> { + poseStack.translate( + hand * -0.05f * amount * absSwing, + 0.05f * amount * absSwing, + 0.18f * amount * absSwing + ); + poseStack.mulPose(Axis.XP.rotationDegrees(22.0f * amount * absSwing)); + } + + case Spin -> { + poseStack.translate( + hand * -0.04f * amount * absSwing, + -0.02f * amount * absSwing, + -0.14f * amount * absSwing + ); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * 180.0f * amount * progress)); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * 180.0f * amount * progress)); + } + + case Push -> { + poseStack.translate( + 0.0f, + 0.0f, + -0.26f * amount * absSwing + ); + poseStack.scale( + 1.0f + 0.05f * amount * absSwing, + 1.0f + 0.05f * amount * absSwing, + 1.0f + 0.05f * amount * absSwing + ); + } + + case Cancel -> { + } + } + } + + private float animationProgress(double baseDurationMs) { + double duration = Math.max(50.0, baseDurationMs / speed.getValue()); + long time = System.currentTimeMillis(); + + return (float) ((time % (long) duration) / duration); + } + + private static float handSign(ItemDisplayContext displayContext) { + return displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND ? -1.0f : 1.0f; + } + + private static boolean isMainHandContext(ItemDisplayContext displayContext) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + HumanoidArm mainArm = player.getMainArm(); + + if (displayContext == ItemDisplayContext.FIRST_PERSON_RIGHT_HAND) { + return mainArm == HumanoidArm.RIGHT; + } + + if (displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND) { + return mainArm == HumanoidArm.LEFT; + } + + return false; + } + + private static boolean isMainHandArm(HumanoidArm arm) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + return player != null && arm == player.getMainArm(); + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BreakESP.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BreakESP.java new file mode 100644 index 0000000..ae27e60 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/BreakESP.java @@ -0,0 +1,146 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.BlockDestructionProgress; +import net.minecraft.world.phys.AABB; + +import java.awt.Color; +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.Map; + +@SuppressWarnings("unused") +public class BreakESP extends Module { + + public static BreakESP INSTANCE; + + private static final Field LEVEL_RENDERER_DESTROY_FIELD; + + static { + Field found = null; + + for (String name : new String[]{"destructionProgress", "destroyingBlocks"}) { + try { + Field field = LevelRenderer.class.getDeclaredField(name); + field.setAccessible(true); + found = field; + break; + } catch (Throwable ignored) { + } + } + + if (found == null) { + for (Field field : LevelRenderer.class.getDeclaredFields()) { + if (!Map.class.isAssignableFrom(field.getType())) { + continue; + } + + try { + field.setAccessible(true); + found = field; + break; + } catch (Throwable ignored) { + } + } + } + + LEVEL_RENDERER_DESTROY_FIELD = found; + } + + private final Setting outline = color("Box", new Color(255, 255, 255, 255)); + private final Setting fill = color("Fill", new Color(255, 255, 255, 100)); + private final Setting renderBox = bool("Outline", true); + private final Setting renderFill = bool("Fill", true); + private final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + private final Setting shrink = bool("Shrink", true); + + public BreakESP() { + super("BreakESP", "Shows blocks being mined", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onRender3D(Render3DEvent event) { + if (nullCheck()) return; + if (LEVEL_RENDERER_DESTROY_FIELD == null) return; + + try { + Object raw = LEVEL_RENDERER_DESTROY_FIELD.get(mc.levelRenderer); + + if (!(raw instanceof Map map)) { + return; + } + + for (Object value : map.values()) { + renderValue(event, value); + } + } catch (Throwable ignored) { + } + } + + private void renderValue(Render3DEvent event, Object value) { + if (value instanceof BlockDestructionProgress progress) { + renderProgress(event, progress); + return; + } + + if (value instanceof Collection collection) { + for (Object object : collection) { + if (object instanceof BlockDestructionProgress progress) { + renderProgress(event, progress); + } + } + } + } + + private void renderProgress(Render3DEvent event, BlockDestructionProgress progress) { + BlockPos pos = progress.getPos(); + int stage = progress.getProgress(); + + if (stage < 0) { + return; + } + + double inset = getInset(stage); + AABB box = new AABB(pos).deflate(inset, inset, inset); + + if (renderFill.getValue()) { + RenderUtil.drawBoxFilled(event.getMatrix(), box, fill.getValue()); + } + + if (renderBox.getValue()) { + RenderUtil.drawBox(event.getMatrix(), box, outline.getValue(), lineWidth.getValue()); + } + } + + private double getInset(int stage) { + if (!shrink.getValue()) { + return 0.0; + } + + double progress = Math.max(0.0, Math.min(1.0, stage / 9.0)); + return 0.5 * (1.0 - progress); + } + + @Override + public String getDisplayInfo() { + if (renderFill.getValue() && renderBox.getValue()) { + return "Both"; + } + + if (renderFill.getValue()) { + return "Fill"; + } + + if (renderBox.getValue()) { + return "Outline"; + } + + return "Off"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CityESP.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CityESP.java new file mode 100644 index 0000000..d779ac3 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CityESP.java @@ -0,0 +1,96 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.AABB; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +public class CityESP extends Module { + + private final Setting color = color("Color", new Color(255, 255, 255, 100)); + private final Setting box = bool("Box", true); + private final Setting outline = bool("Outline", true); + private final Setting burrow = bool("Burrow", true); + private final Setting surround = bool("Surround", true); + private final Setting range = num("Range", 10.0, 1.0, 32.0); + private final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + + private final List renderList = new ArrayList<>(); + + public CityESP() { + super("CityESP", "Shows enemy burrow and surround blocks", Category.RENDER); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (nullCheck() || mc.player == null || mc.level == null) return; + + ClientLevel level = mc.level; + renderList.clear(); + + for (Player player : level.players()) { + if (player == mc.player) continue; + if (!player.isAlive()) continue; + if (nolongerhuman.friendManager.isFriend(player)) continue; + if (mc.player.distanceTo(player) > range.getValue()) continue; + + if (burrow.getValue()) { + addIfCityBlock(player.blockPosition()); + + addIfCityBlock(BlockPos.containing( + player.getX(), + player.getY() + 0.5, + player.getZ() + )); + } + + if (surround.getValue()) { + BlockPos base = player.blockPosition(); + + for (Direction direction : Direction.Plane.HORIZONTAL) { + addIfCityBlock(base.relative(direction)); + } + } + } + + for (BlockPos pos : renderList) { + AABB aabb = new AABB(pos); + + if (box.getValue()) { + RenderUtil.drawBoxFilled(event.getMatrix(), aabb, color.getValue()); + } + + if (outline.getValue()) { + RenderUtil.drawBox(event.getMatrix(), aabb, color.getValue(), lineWidth.getValue()); + } + } + } + + private void addIfCityBlock(BlockPos pos) { + if (mc.level == null) return; + if (renderList.contains(pos)) return; + + Block block = mc.level.getBlockState(pos).getBlock(); + + if (block == Blocks.OBSIDIAN || block == Blocks.ENDER_CHEST || block == Blocks.CRYING_OBSIDIAN) { + renderList.add(pos.immutable()); + } + } + + @Override + public String getDisplayInfo() { + return String.valueOf(renderList.size()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CrystalChams.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CrystalChams.java new file mode 100644 index 0000000..f482872 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CrystalChams.java @@ -0,0 +1,408 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.CrystalChamsRenderer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; + +import java.awt.Color; + +public class CrystalChams extends Module { + public enum RenderMode { + Fill, + Wire, + Both + } + + private static CrystalChams INSTANCE; + + private final Setting mode = mode("Mode", RenderMode.Both); + + private final Setting range = num("Range", 64.0, 4.0, 256.0); + private final Setting aliveOnly = bool("AliveOnly", true); + private final Setting throughWalls = bool("ThroughWalls", true); + private final Setting vanillaModel = bool("VanillaModel", true); + private final Setting core = bool("Core", false); + + private final Setting outerFillColor = color("OuterFillColor", new Color(255, 255, 255, 70)); + private final Setting outerWireColor = color("OuterWireColor", new Color(255, 255, 255, 255)); + private final Setting coreFillColor = color("CoreFillColor", new Color(255, 255, 255, 136)); + private final Setting coreWireColor = color("CoreWireColor", new Color(255, 255, 255, 255)); + + private final Setting lineWidth = num("LineWidth", 1.5F, 0.1F, 5.0F); + + private final Setting fade = bool("Fade", false); + private final Setting fadeStart = num("FadeStart", 32.0, 1.0, 256.0); + + private final Setting pulse = bool("Pulse", false); + private final Setting pulseMinAlpha = num("PulseMinAlpha", 45, 0, 255); + private final Setting pulseMaxAlpha = num("PulseMaxAlpha", 115, 0, 255); + private final Setting pulseSpeed = num("PulseSpeed", 1.0, 0.1, 5.0); + + private final Setting gradient = bool("Gradient", false); + private final Setting gradientColorA = color("GradientColorA", new Color(255, 255, 255, 255)); + private final Setting gradientColorB = color("GradientColorB", new Color(147, 147, 147, 255)); + private final Setting gradientSpeed = num("GradientSpeed", 0.75, 0.05, 5.0); + private final Setting gradientScale = num("GradientScale", 1.35, 0.1, 5.0); + private final Setting gradientStrength = num("GradientStrength", 1.0, 0.0, 1.0); + + private final Setting ripple = bool("Ripple", false); + private final Setting rippleColorA = color("RippleColorA", new Color(253, 254, 255, 255)); + private final Setting rippleColorB = color("RippleColorB", new Color(179, 179, 179, 255)); + private final Setting rippleSpeed = num("RippleSpeed", 1.0, 0.05, 5.0); + private final Setting rippleScale = num("RippleScale", 3.0, 0.1, 10.0); + private final Setting rippleStrength = num("RippleStrength", 1.0, 0.0, 1.0); + + private final Setting shine = bool("Shine", false); + private final Setting shineColor = color("ShineColor", new Color(255, 255, 255, 170)); + private final Setting shineSpeed = num("ShineSpeed", 1.2, 0.05, 5.0); + private final Setting shineWidth = num("ShineWidth", 0.28, 0.05, 1.0); + private final Setting shineStrength = num("ShineStrength", 0.65, 0.0, 1.0); + + private final Setting alternating = bool("Alternating", false); + private final Setting alternatingColor = color("AlternatingColor", new Color(255, 255, 255, 255)); + private final Setting alternatingSpeed = num("AlternatingSpeed", 1.0, 0.05, 5.0); + private final Setting alternatingScale = num("AlternatingScale", 8.0, 1.0, 30.0); + private final Setting alternatingStrength = num("AlternatingStrength", 0.85, 0.0, 1.0); + + private final Setting waves = bool("Waves", false); + private final Setting waveColorA = color("WaveColorA", new Color(255, 255, 255, 255)); + private final Setting waveColorB = color("WaveColorB", new Color(120, 120, 120, 255)); + private final Setting waveSpeed = num("WaveSpeed", 1.0, 0.05, 5.0); + private final Setting waveScale = num("WaveScale", 2.0, 0.1, 10.0); + private final Setting waveStrength = num("WaveStrength", 1.0, 0.0, 1.0); + + private final Setting glint = bool("Glint", false); + private final Setting glintColor = color("GlintColor", new Color(255, 255, 255, 210)); + private final Setting glintSpeed = num("GlintSpeed", 1.8, 0.05, 8.0); + private final Setting glintWidth = num("GlintWidth", 0.18, 0.03, 1.0); + private final Setting glintStrength = num("GlintStrength", 0.85, 0.0, 1.0); + + private final Setting glow = bool("Glow", false); + private final Setting glowColor = color("GlowColor", new Color(255, 255, 255, 180)); + private final Setting glowSpeed = num("GlowSpeed", 0.8, 0.05, 5.0); + private final Setting glowStrength = num("GlowStrength", 0.65, 0.0, 1.0); + + private final Setting smoke = bool("Smoke", false); + private final Setting smokeColorA = color("SmokeColorA", new Color(255, 255, 255, 180)); + private final Setting smokeColorB = color("SmokeColorB", new Color(70, 70, 70, 180)); + private final Setting smokeSpeed = num("SmokeSpeed", 0.55, 0.05, 5.0); + private final Setting smokeScale = num("SmokeScale", 3.0, 0.1, 12.0); + private final Setting smokeStrength = num("SmokeStrength", 0.75, 0.0, 1.0); + + private final Setting water = bool("Water", false); + private final Setting waterColorA = color("WaterColorA", new Color(90, 180, 255, 220)); + private final Setting waterColorB = color("WaterColorB", new Color(210, 245, 255, 220)); + private final Setting waterSpeed = num("WaterSpeed", 1.0, 0.05, 5.0); + private final Setting waterScale = num("WaterScale", 2.5, 0.1, 12.0); + private final Setting waterStrength = num("WaterStrength", 0.85, 0.0, 1.0); + + private final Setting blurry = bool("Blurry", false); + private final Setting blurryColor = color("BlurryColor", new Color(255, 255, 255, 120)); + private final Setting blurryStrength = num("BlurryStrength", 0.45, 0.0, 1.0); + + private final Setting snow = bool("Snow", false); + private final Setting snowColor = color("SnowColor", new Color(255, 255, 255, 255)); + private final Setting snowSpeed = num("SnowSpeed", 0.75, 0.05, 5.0); + private final Setting snowScale = num("SnowScale", 9.0, 1.0, 35.0); + private final Setting snowStrength = num("SnowStrength", 0.9, 0.0, 1.0); + + private final Setting aurora = bool("Aurora", false); + private final Setting auroraColorA = color("AuroraColorA", new Color(90, 255, 180, 230)); + private final Setting auroraColorB = color("AuroraColorB", new Color(150, 90, 255, 230)); + private final Setting auroraSpeed = num("AuroraSpeed", 0.45, 0.05, 5.0); + private final Setting auroraScale = num("AuroraScale", 2.2, 0.1, 12.0); + private final Setting auroraStrength = num("AuroraStrength", 0.85, 0.0, 1.0); + + private final Setting plasma = bool("Plasma", false); + private final Setting plasmaColorA = color("PlasmaColorA", new Color(255, 90, 220, 240)); + private final Setting plasmaColorB = color("PlasmaColorB", new Color(90, 200, 255, 240)); + private final Setting plasmaSpeed = num("PlasmaSpeed", 0.9, 0.05, 5.0); + private final Setting plasmaScale = num("PlasmaScale", 3.0, 0.1, 12.0); + private final Setting plasmaStrength = num("PlasmaStrength", 0.9, 0.0, 1.0); + + private final Setting scanlines = bool("Scanlines", false); + private final Setting scanlineColor = color("ScanlineColor", new Color(255, 255, 255, 180)); + private final Setting scanlineSpeed = num("ScanlineSpeed", 1.2, 0.05, 8.0); + private final Setting scanlineScale = num("ScanlineScale", 8.0, 1.0, 30.0); + private final Setting scanlineStrength = num("ScanlineStrength", 0.65, 0.0, 1.0); + + private final Setting electric = bool("Electric", false); + private final Setting electricColor = color("ElectricColor", new Color(120, 220, 255, 240)); + private final Setting electricSpeed = num("ElectricSpeed", 1.5, 0.05, 8.0); + private final Setting electricScale = num("ElectricScale", 5.0, 0.1, 18.0); + private final Setting electricStrength = num("ElectricStrength", 0.85, 0.0, 1.0); + + private final Setting rainbow = bool("Rainbow", false); + private final Setting rainbowSpeed = num("RainbowSpeed", 0.35, 0.01, 3.0); + private final Setting rainbowScale = num("RainbowScale", 1.5, 0.1, 10.0); + private final Setting rainbowSaturation = num("RainbowSaturation", 0.85, 0.0, 1.0); + private final Setting rainbowStrength = num("RainbowStrength", 0.8, 0.0, 1.0); + + public CrystalChams() { + super("CrystalChams", "Renders end crystal chams through walls", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onRender3D(Render3DEvent event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + PoseStack stack = event.getMatrix(); + double rangeSq = range.getValue() * range.getValue(); + + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof EndCrystal crystal)) { + continue; + } + + if (!shouldRenderChamsFor(player, crystal, rangeSq)) { + continue; + } + + boolean drawFill = mode.getValue() == RenderMode.Fill || mode.getValue() == RenderMode.Both; + boolean drawWire = mode.getValue() == RenderMode.Wire || mode.getValue() == RenderMode.Both; + + Color outerFill = getColor(player, crystal, outerFillColor.getValue(), true); + Color outerWire = getColor(player, crystal, outerWireColor.getValue(), false); + Color coreFill = getColor(player, crystal, coreFillColor.getValue(), true); + Color coreWire = getColor(player, crystal, coreWireColor.getValue(), false); + + CrystalChamsRenderer.renderCrystal( + stack, + crystal, + event.getDelta(), + outerFill, + outerWire, + coreFill, + coreWire, + lineWidth.getValue(), + drawWire && (outerWire.getAlpha() > 0 || coreWire.getAlpha() > 0), + drawFill && (outerFill.getAlpha() > 0 || coreFill.getAlpha() > 0), + core.getValue(), + throughWalls.getValue(), + + gradient.getValue(), + gradientColorA.getValue(), + gradientColorB.getValue(), + gradientSpeed.getValue().floatValue(), + gradientScale.getValue().floatValue(), + gradientStrength.getValue().floatValue(), + + ripple.getValue(), + rippleColorA.getValue(), + rippleColorB.getValue(), + rippleSpeed.getValue().floatValue(), + rippleScale.getValue().floatValue(), + rippleStrength.getValue().floatValue(), + + shine.getValue(), + shineColor.getValue(), + shineSpeed.getValue().floatValue(), + shineWidth.getValue().floatValue(), + shineStrength.getValue().floatValue(), + + alternating.getValue(), + alternatingColor.getValue(), + alternatingSpeed.getValue().floatValue(), + alternatingScale.getValue().floatValue(), + alternatingStrength.getValue().floatValue(), + + waves.getValue(), + waveColorA.getValue(), + waveColorB.getValue(), + waveSpeed.getValue().floatValue(), + waveScale.getValue().floatValue(), + waveStrength.getValue().floatValue(), + + glint.getValue(), + glintColor.getValue(), + glintSpeed.getValue().floatValue(), + glintWidth.getValue().floatValue(), + glintStrength.getValue().floatValue(), + + glow.getValue(), + glowColor.getValue(), + glowSpeed.getValue().floatValue(), + glowStrength.getValue().floatValue(), + + smoke.getValue(), + smokeColorA.getValue(), + smokeColorB.getValue(), + smokeSpeed.getValue().floatValue(), + smokeScale.getValue().floatValue(), + smokeStrength.getValue().floatValue(), + + water.getValue(), + waterColorA.getValue(), + waterColorB.getValue(), + waterSpeed.getValue().floatValue(), + waterScale.getValue().floatValue(), + waterStrength.getValue().floatValue(), + + blurry.getValue(), + blurryColor.getValue(), + blurryStrength.getValue().floatValue(), + + snow.getValue(), + snowColor.getValue(), + snowSpeed.getValue().floatValue(), + snowScale.getValue().floatValue(), + snowStrength.getValue().floatValue(), + + aurora.getValue(), + auroraColorA.getValue(), + auroraColorB.getValue(), + auroraSpeed.getValue().floatValue(), + auroraScale.getValue().floatValue(), + auroraStrength.getValue().floatValue(), + + plasma.getValue(), + plasmaColorA.getValue(), + plasmaColorB.getValue(), + plasmaSpeed.getValue().floatValue(), + plasmaScale.getValue().floatValue(), + plasmaStrength.getValue().floatValue(), + + scanlines.getValue(), + scanlineColor.getValue(), + scanlineSpeed.getValue().floatValue(), + scanlineScale.getValue().floatValue(), + scanlineStrength.getValue().floatValue(), + + electric.getValue(), + electricColor.getValue(), + electricSpeed.getValue().floatValue(), + electricScale.getValue().floatValue(), + electricStrength.getValue().floatValue(), + + rainbow.getValue(), + rainbowSpeed.getValue().floatValue(), + rainbowScale.getValue().floatValue(), + rainbowSaturation.getValue().floatValue(), + rainbowStrength.getValue().floatValue() + ); + } + } + + private boolean shouldRenderChamsFor(LocalPlayer player, EndCrystal crystal, double rangeSq) { + if (crystal == null) { + return false; + } + + if (aliveOnly.getValue() && !crystal.isAlive()) { + return false; + } + + return player.distanceToSqr(crystal) <= rangeSq; + } + + private boolean shouldCancelVanillaModel(EndCrystal crystal) { + if (!isEnabled()) { + return false; + } + + if (vanillaModel.getValue()) { + return false; + } + + if (crystal == null) { + return false; + } + + if (aliveOnly.getValue() && !crystal.isAlive()) { + return false; + } + + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + return player.distanceTo(crystal) <= range.getValue(); + } + + public static boolean shouldCancelVanillaCrystalRender(EndCrystal crystal) { + return INSTANCE != null && INSTANCE.shouldCancelVanillaModel(crystal); + } + + private Color getColor(LocalPlayer player, EndCrystal crystal, Color base, boolean applyPulse) { + int alpha = base.getAlpha(); + + if (applyPulse && pulse.getValue()) { + alpha = getPulseAlpha(alpha); + } + + if (fade.getValue()) { + alpha = applyDistanceFade(player, crystal, alpha); + } + + return withAlpha(base, alpha); + } + + private int getPulseAlpha(int originalAlpha) { + int min = Math.min(pulseMinAlpha.getValue(), pulseMaxAlpha.getValue()); + int max = Math.max(pulseMinAlpha.getValue(), pulseMaxAlpha.getValue()); + + max = Math.min(max, originalAlpha); + + if (min > max) { + min = max; + } + + double time = System.currentTimeMillis() / 1000.0D; + double wave = (Math.sin(time * pulseSpeed.getValue() * Math.PI * 2.0D) + 1.0D) / 2.0D; + + return clampAlpha((int) Math.round(min + (max - min) * wave)); + } + + private int applyDistanceFade(LocalPlayer player, EndCrystal crystal, int alpha) { + double distance = player.distanceTo(crystal); + double start = Math.max(1.0D, fadeStart.getValue()); + double end = Math.max(start + 1.0D, range.getValue()); + + if (distance <= start) { + return clampAlpha(alpha); + } + + if (distance >= end) { + return 0; + } + + double factor = 1.0D - ((distance - start) / (end - start)); + return clampAlpha((int) Math.round(alpha * factor)); + } + + private Color withAlpha(Color color, int alpha) { + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + clampAlpha(alpha) + ); + } + + private int clampAlpha(int alpha) { + return Math.max(0, Math.min(255, alpha)); + } + + public static CrystalChams getInstance() { + return INSTANCE; + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CrystalCircles.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CrystalCircles.java new file mode 100644 index 0000000..2a10b3c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/CrystalCircles.java @@ -0,0 +1,339 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.Layers; +import net.minecraft.client.Camera; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class CrystalCircles extends Module { + private static CrystalCircles INSTANCE; + + public final Setting color = color("Color", new Color(120, 180, 255, 220)); + + public final Setting glow = bool("Glow", true); + public final Setting glowColor = color("GlowColor", new Color(120, 180, 255, 120)); + public final Setting glowSize = num("GlowSize", 0.22f, 0.01f, 2.0f); + public final Setting glowPasses = num("GlowPasses", 5, 1, 16); + + public final Setting radius = num("Radius", 0.75f, 0.1f, 3.0f); + public final Setting startHeight = num("StartHeight", 2.0f, 0.0f, 4.0f); + public final Setting dropDistance = num("DropDistance", 1.35f, 0.0f, 5.0f); + public final Setting lineWidth = num("LineWidth", 2.0f, 0.1f, 6.0f); + public final Setting fadeInMs = num("FadeIn", 80, 1, 1000); + public final Setting fadeOutMs = num("FadeOut", 650, 1, 3000); + public final Setting segments = num("Segments", 72, 12, 180); + public final Setting maxCircles = num("MaxCircles", 24, 1, 100); + + private final List circles = new ArrayList<>(); + + public CrystalCircles() { + super("CrystalCircles", "Renders fading circles when crystals are attacked", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onDisable() { + circles.clear(); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (mc.player == null || mc.level == null) { + circles.clear(); + return; + } + + if (circles.isEmpty()) { + return; + } + + Camera camera = mc.getEntityRenderDispatcher().camera; + + if (camera == null) { + return; + } + + Vec3 cameraPos = camera.position(); + long now = System.currentTimeMillis(); + long lifetime = getLifetime(); + + Iterator iterator = circles.iterator(); + + while (iterator.hasNext()) { + Circle circle = iterator.next(); + long age = now - circle.startTime(); + + if (age >= lifetime) { + iterator.remove(); + continue; + } + + drawCircle(event.getMatrix(), cameraPos, circle, age); + } + } + + private void drawCircle(PoseStack stack, Vec3 cameraPos, Circle circle, long age) { + int fadeIn = Math.max(1, fadeInMs.getValue()); + int fadeOut = Math.max(1, fadeOutMs.getValue()); + + double alphaMultiplier; + double yOffset; + + if (age <= fadeIn) { + double progress = clamp((double) age / (double) fadeIn, 0.0D, 1.0D); + + alphaMultiplier = easeOut(progress); + yOffset = 0.0D; + } else { + double progress = clamp((double) (age - fadeIn) / (double) fadeOut, 0.0D, 1.0D); + + alphaMultiplier = 1.0D - easeIn(progress); + yOffset = -dropDistance.getValue() * easeOut(progress); + } + + if (alphaMultiplier <= 0.01D) { + return; + } + + Color renderColor = withAlphaMultiplier(color.getValue(), alphaMultiplier); + Color renderGlowColor = withAlphaMultiplier(glowColor.getValue(), alphaMultiplier); + + double renderRadius = radius.getValue(); + + if (age <= fadeIn) { + double progress = clamp((double) age / (double) fadeIn, 0.0D, 1.0D); + renderRadius *= 0.65D + 0.35D * easeOut(progress); + } + + Vec3 center = circle.center().add(0.0D, yOffset, 0.0D); + int circleSegments = Math.max(12, segments.getValue()); + + drawGlow( + stack, + cameraPos, + center, + renderRadius, + renderGlowColor, + lineWidth.getValue(), + circleSegments + ); + + drawFlatCircle( + stack, + cameraPos, + center, + renderRadius, + renderColor, + lineWidth.getValue(), + circleSegments + ); + } + + private void drawGlow( + PoseStack stack, + Vec3 cameraPos, + Vec3 center, + double radius, + Color color, + float width, + int segments + ) { + if (!glow.getValue()) { + return; + } + + if (color.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, glowPasses.getValue()); + double size = Math.max(0.0D, glowSize.getValue()); + + if (size <= 0.0D) { + return; + } + + for (int i = passes; i >= 1; i--) { + double progress = i / (double) passes; + double offset = size * progress; + double alphaFactor = (1.0D - progress) * 0.60D + 0.12D; + + Color passColor = withAlphaMultiplier(color, alphaFactor); + float passWidth = width + (float) (i * 0.25D); + + double outerRadius = radius + offset; + double innerRadius = radius - offset; + + drawFlatCircle( + stack, + cameraPos, + center, + outerRadius, + passColor, + passWidth, + segments + ); + + if (innerRadius > 0.01D) { + drawFlatCircle( + stack, + cameraPos, + center, + innerRadius, + passColor, + passWidth, + segments + ); + } + } + } + + private void drawFlatCircle( + PoseStack stack, + Vec3 cameraPos, + Vec3 center, + double radius, + Color color, + float width, + int segments + ) { + if (width <= 0.0F || radius <= 0.0D) { + return; + } + + float cx = (float) (center.x - cameraPos.x); + float cy = (float) (center.y - cameraPos.y); + float cz = (float) (center.z - cameraPos.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int rgb = color.getRGB(); + + for (int i = 0; i < segments; i++) { + double angle1 = (Math.PI * 2.0D * i) / segments; + double angle2 = (Math.PI * 2.0D * (i + 1)) / segments; + + float x1 = cx + (float) (Math.cos(angle1) * radius); + float z1 = cz + (float) (Math.sin(angle1) * radius); + float x2 = cx + (float) (Math.cos(angle2) * radius); + float z2 = cz + (float) (Math.sin(angle2) * radius); + + addLine(buffer, pose, rgb, width, x1, cy, z1, x2, cy, z2); + } + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void addLine( + BufferBuilder buffer, + PoseStack.Pose pose, + int color, + float width, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2 + ) { + float nx = x2 - x1; + float ny = y2 - y1; + float nz = z2 - z1; + + buffer.addVertex(pose, x1, y1, z1) + .setColor(color) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + + buffer.addVertex(pose, x2, y2, z2) + .setColor(color) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + } + + private long getLifetime() { + return Math.max(1, fadeInMs.getValue()) + Math.max(1, fadeOutMs.getValue()); + } + + private double easeIn(double progress) { + progress = clamp(progress, 0.0D, 1.0D); + return progress * progress * progress; + } + + private double easeOut(double progress) { + progress = clamp(progress, 0.0D, 1.0D); + + double inverse = 1.0D - progress; + + return 1.0D - inverse * inverse * inverse; + } + + private double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = clamp(multiplier, 0.0D, 1.0D); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + @SuppressWarnings("unused") + public static void spawn(EndCrystal crystal) { + CrystalCircles module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (crystal == null) { + return; + } + + module.addCircle(crystal); + } + + private void addCircle(EndCrystal crystal) { + while (circles.size() >= maxCircles.getValue()) { + circles.remove(0); + } + + Vec3 center = new Vec3( + crystal.getX(), + crystal.getY() + startHeight.getValue(), + crystal.getZ() + ); + + circles.add(new Circle(center, System.currentTimeMillis())); + } + + private record Circle(Vec3 center, long startTime) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Freecam.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Freecam.java new file mode 100644 index 0000000..7471daa --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Freecam.java @@ -0,0 +1,190 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.phys.Vec2; +import net.minecraft.world.phys.Vec3; + +public class Freecam extends Module { + public static Freecam INSTANCE; + + private final Setting speed = num("Speed", 2.0, 0.1, 10.0); + private final Setting rotate = bool("Rotate", true); + + private Vec3 cameraPosition = Vec3.ZERO; + private Vec3 lastCameraPosition = Vec3.ZERO; + private Vec3 frozenPlayerPosition = Vec3.ZERO; + + private float yaw; + private float pitch; + + public Freecam() { + super("Freecam", "Allows you to move the camera separately from the player", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + cameraPosition = mc.gameRenderer.getMainCamera().position(); + lastCameraPosition = cameraPosition; + frozenPlayerPosition = player.position(); + + yaw = player.getYRot(); + pitch = player.getXRot(); + + freezePlayer(player); + } + + @Override + public void onDisable() { + LocalPlayer player = mc.player; + + if (player != null) { + player.setDeltaMovement(Vec3.ZERO); + } + } + + @Override + public void onTick() { + LocalPlayer player = mc.player; + + if (player == null) { + return; + } + + freezePlayer(player); + updateCameraPosition(); + } + + private void freezePlayer(LocalPlayer player) { + player.setDeltaMovement(Vec3.ZERO); + player.setPos( + frozenPlayerPosition.x, + frozenPlayerPosition.y, + frozenPlayerPosition.z + ); + player.fallDistance = 0.0F; + } + + private void updateCameraPosition() { + lastCameraPosition = cameraPosition; + + double moveSpeed = speed.getValue() / 10.0D; + + double forward = getMovementMultiplier( + mc.options.keyUp.isDown(), + mc.options.keyDown.isDown() + ); + + double strafe = getMovementMultiplier( + mc.options.keyLeft.isDown(), + mc.options.keyRight.isDown() + ); + + double vertical = getMovementMultiplier( + mc.options.keyJump.isDown(), + mc.options.keyShift.isDown() + ); + + Vec2 horizontal = getHorizontalMotion(moveSpeed, forward, strafe); + + cameraPosition = cameraPosition.add( + horizontal.x, + vertical * moveSpeed, + horizontal.y + ); + } + + private double getMovementMultiplier(boolean positive, boolean negative) { + if (positive == negative) { + return 0.0D; + } + + return positive ? 1.0D : -1.0D; + } + + private Vec2 getHorizontalMotion(double moveSpeed, double forward, double strafe) { + if (forward == 0.0D && strafe == 0.0D) { + return Vec2.ZERO; + } + + double adjustedForward = forward; + double adjustedStrafe = strafe; + + if (adjustedForward != 0.0D && adjustedStrafe != 0.0D) { + adjustedForward *= Math.sin(Math.PI / 4.0D); + adjustedStrafe *= Math.cos(Math.PI / 4.0D); + } + + double radians = Math.toRadians(yaw); + + float x = (float) (adjustedForward * moveSpeed * -Math.sin(radians) + + adjustedStrafe * moveSpeed * Math.cos(radians)); + + float z = (float) (adjustedForward * moveSpeed * Math.cos(radians) + - adjustedStrafe * moveSpeed * -Math.sin(radians)); + + return new Vec2(x, z); + } + + public void changeLookDirection(double cursorDeltaX, double cursorDeltaY) { + if (!rotate.getValue()) { + return; + } + + yaw += (float) cursorDeltaX * 0.15F; + pitch += (float) cursorDeltaY * 0.15F; + pitch = Mth.clamp(pitch, -90.0F, 90.0F); + } + + public Vec3 getInterpolatedCameraPosition(float tickDelta) { + return lastCameraPosition.lerp(cameraPosition, tickDelta); + } + + public float getCameraYaw() { + return yaw; + } + + public float getCameraPitch() { + return pitch; + } + + public static boolean shouldHandleCamera() { + return INSTANCE != null && INSTANCE.isEnabled(); + } + + public static Vec3 getPosition(float tickDelta) { + if (INSTANCE == null) { + return Vec3.ZERO; + } + + return INSTANCE.getInterpolatedCameraPosition(tickDelta); + } + + public static float getYaw() { + return INSTANCE == null ? 0.0F : INSTANCE.getCameraYaw(); + } + + public static float getPitch() { + return INSTANCE == null ? 0.0F : INSTANCE.getCameraPitch(); + } + + public static void handleMouse(double cursorDeltaX, double cursorDeltaY) { + if (INSTANCE != null) { + INSTANCE.changeLookDirection(cursorDeltaX, cursorDeltaY); + } + } + + @Override + public String getDisplayInfo() { + return String.format("%.1f", speed.getValue()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/FullBright.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/FullBright.java new file mode 100644 index 0000000..dadf65d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/FullBright.java @@ -0,0 +1,226 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +public class FullBright extends Module { + + public enum Mode { + GAMMA, + POTION + } + + private static final double MAX_GAMMA = 1000.0D; + + public final Setting mode = mode("Mode", Mode.GAMMA); + + private boolean gammaApplied = false; + private boolean potionApplied = false; + private double originalGamma = 1.0D; + private Mode appliedMode = null; + + public FullBright() { + super("FullBright", "Makes everything bright", Category.RENDER); + } + + @Override + public void onEnable() { + apply(mode.getValue()); + } + + @Override + public void onTick() { + Mode currentMode = mode.getValue(); + + if (appliedMode != currentMode) { + apply(currentMode); + return; + } + + if (currentMode == Mode.GAMMA && gammaApplied) { + setGammaRaw(MAX_GAMMA); + return; + } + + if (currentMode == Mode.POTION && mc.player != null && !mc.player.hasEffect(MobEffects.NIGHT_VISION)) { + applyPotion(); + } + } + + @Override + public void onDisable() { + restore(); + } + + private void apply(Mode targetMode) { + restore(); + + if (targetMode == Mode.GAMMA) { + originalGamma = getCurrentGamma(); + setGammaRaw(MAX_GAMMA); + gammaApplied = true; + } + + if (targetMode == Mode.POTION) { + applyPotion(); + } + + appliedMode = targetMode; + } + + private void restore() { + if (appliedMode == null) { + return; + } + + if (appliedMode == Mode.GAMMA) { + if (gammaApplied) { + setGammaRaw(originalGamma); + } + + gammaApplied = false; + } + + if (appliedMode == Mode.POTION) { + removePotion(); + } + + appliedMode = null; + } + + private void applyPotion() { + if (mc.player == null) { + return; + } + + mc.player.addEffect(new MobEffectInstance( + MobEffects.NIGHT_VISION, + MobEffectInstance.INFINITE_DURATION, + 0, + false, + false, + false + )); + + potionApplied = true; + } + + private void removePotion() { + if (!potionApplied) { + return; + } + + if (mc.player != null && mc.player.hasEffect(MobEffects.NIGHT_VISION)) { + mc.player.removeEffect(MobEffects.NIGHT_VISION); + } + + potionApplied = false; + } + + private double getCurrentGamma() { + try { + Object value = mc.options.gamma().get(); + + if (value instanceof Number number) { + return number.doubleValue(); + } + } catch (Throwable ignored) { + } + + return 1.0D; + } + + private void setGammaRaw(double value) { + Object gammaOption = mc.options.gamma(); + + if (writeNamedValueField(gammaOption, value)) { + return; + } + + writeMatchingNumericField(gammaOption, value); + } + + private boolean writeNamedValueField(Object gammaOption, double value) { + for (Class clazz = gammaOption.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + try { + Field field = clazz.getDeclaredField("value"); + field.setAccessible(true); + + if (writeFieldValue(gammaOption, field, value)) { + return true; + } + } catch (NoSuchFieldException ignored) { + } catch (Throwable ignored) { + return false; + } + } + + return false; + } + + private boolean writeMatchingNumericField(Object gammaOption, double value) { + double current = getCurrentGamma(); + + for (Class clazz = gammaOption.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + + try { + field.setAccessible(true); + + Object fieldValue = field.get(gammaOption); + + if (fieldValue instanceof Number number + && Double.compare(number.doubleValue(), current) == 0) { + return writeFieldValue(gammaOption, field, value); + } + } catch (Throwable ignored) { + } + } + } + + return false; + } + + private boolean writeFieldValue(Object owner, Field field, double value) { + try { + Class type = field.getType(); + Object currentValue = field.get(owner); + + if (type == double.class) { + field.setDouble(owner, value); + return true; + } + + if (type == float.class) { + field.setFloat(owner, (float) value); + return true; + } + + if (currentValue instanceof Double || type == Double.class || type == Object.class) { + field.set(owner, value); + return true; + } + + if (currentValue instanceof Float || type == Float.class) { + field.set(owner, (float) value); + return true; + } + } catch (Throwable ignored) { + } + + return false; + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/HoleESP.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/HoleESP.java new file mode 100644 index 0000000..9078a2a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/HoleESP.java @@ -0,0 +1,1135 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.manager.HoleManager; +import me.humanbeing.nolongerhuman.util.render.Layers; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class HoleESP extends Module { + public final Setting bedrockColor = color("BedrockOutline", 0, 255, 0, 180); + public final Setting bedrockFill = color("BedrockFill", 0, 255, 0, 20); + public final Setting bedrockWireframe = color("BedrockWireframe", 0, 255, 0, 125); + public final Setting bedrockGradient = color("BedrockGradient", 100, 255, 100, 45); + public final Setting bedrockLineGradient = color("BedrockLineGradient", 120, 255, 120, 210); + public final Setting bedrockWireGradient = color("BedrockWireGradient", 120, 255, 120, 170); + public final Setting bedrockGlow = color("BedrockGlow", 100, 255, 100, 35); + + public final Setting unsafeColor = color("UnsafeOutline", 255, 0, 0, 180); + public final Setting unsafeFill = color("UnsafeFill", 255, 0, 0, 20); + public final Setting unsafeWireframe = color("UnsafeWireframe", 255, 0, 0, 125); + public final Setting unsafeGradient = color("UnsafeGradient", 255, 100, 100, 45); + public final Setting unsafeLineGradient = color("UnsafeLineGradient", 255, 120, 120, 210); + public final Setting unsafeWireGradient = color("UnsafeWireGradient", 255, 120, 120, 170); + public final Setting unsafeGlow = color("UnsafeGlow", 255, 100, 100, 35); + + public final Setting mixedColor = color("MixedOutline", 255, 165, 0, 180); + public final Setting mixedFill = color("MixedFill", 255, 165, 0, 20); + public final Setting mixedWireframe = color("MixedWireframe", 255, 165, 0, 125); + public final Setting mixedGradient = color("MixedGradient", 255, 210, 80, 45); + public final Setting mixedLineGradient = color("MixedLineGradient", 255, 220, 100, 210); + public final Setting mixedWireGradient = color("MixedWireGradient", 255, 220, 100, 170); + public final Setting mixedGlow = color("MixedGlow", 255, 210, 80, 35); + + public final Setting partialColor = color("PartialOutline", 255, 255, 255, 180); + public final Setting partialFill = color("PartialFill", 255, 255, 255, 20); + public final Setting partialWireframe = color("PartialWireframe", 255, 255, 255, 125); + public final Setting partialGradient = color("PartialGradient", 220, 220, 220, 55); + public final Setting partialLineGradient = color("PartialLineGradient", 220, 220, 220, 210); + public final Setting partialWireGradient = color("PartialWireGradient", 220, 220, 220, 170); + public final Setting partialGlow = color("PartialGlow", 255, 255, 255, 35); + + public final Setting doubles = bool("DoubleHoles", true); + public final Setting quads = bool("QuadHoles", true); + public final Setting partial = bool("Partial", true); + + public final Setting range = num("Range", 8.0f, 1.0f, 32.0f); + public final Setting verticalRange = num("VerticalRange", 4.0f, 0.0f, 32.0f); + public final Setting fadeDistance = num("FadeDistance", 3.0f, 0.0f, 32.0f); + public final Setting lineWidth = num("LineWidth", 1.5f, 0.0f, 5.0f); + public final Setting height = num("Height", 0.0f, 0.0f, 10.0f); + + public final Setting gradient = bool("Gradient", true); + public final Setting lineGradient = bool("LineGradient", false); + public final Setting wireframeGradient = bool("WireframeGradient", false); + public final Setting gradientSpeed = num("GradientSpeed", 1.0f, 0.0f, 10.0f); + public final Setting gradientScale = num("GradientScale", 1.25f, 0.1f, 6.0f); + + public final Setting glow = bool("Glow", false); + public final Setting glowSize = num("GlowSize", 0.18f, 0.01f, 1.0f); + public final Setting glowPasses = num("GlowPasses", 4, 1, 24); + + public final Setting wireframe = bool("Wireframe", false); + + private volatile List cached = new ArrayList<>(); + + public HoleESP() { + super("HoleESP", "Render safe, unsafe, mixed and partial holes", Category.RENDER); + } + + @Override + public void onTick() { + if (nullCheck()) { + cached = new ArrayList<>(); + return; + } + + if (mc.player == null || mc.level == null || nolongerhuman.holeManager == null) { + cached = new ArrayList<>(); + return; + } + + ClientLevel level = mc.level; + BlockPos origin = mc.player.blockPosition(); + + List boxes = new ArrayList<>(); + Set visited = new HashSet<>(); + + if (quads.getValue()) { + addQuadHoles(boxes, level, origin, visited); + } + + if (doubles.getValue()) { + addDoubleHoles(boxes, level, origin, visited); + } + + addSingleHoles(boxes, origin, visited); + + if (partial.getValue()) { + addPartialHoles(boxes, origin, visited); + } + + cached = boxes; + } + + private void addQuadHoles( + List out, + Level level, + BlockPos origin, + Set visited + ) { + int horizontalRange = Math.round(range.getValue()); + int vertical = Math.round(verticalRange.getValue()); + + for (int x = -horizontalRange; x <= horizontalRange; x++) { + for (int y = -vertical; y <= vertical; y++) { + for (int z = -horizontalRange; z <= horizontalRange; z++) { + BlockPos base = origin.offset(x, y, z); + + if (outOfRenderRange(origin, base)) { + continue; + } + + BlockPos east = base.east(); + BlockPos south = base.south(); + BlockPos diagonal = base.east().south(); + + if (visited.contains(base) + || visited.contains(east) + || visited.contains(south) + || visited.contains(diagonal)) { + continue; + } + + HoleManager.HoleType type = nolongerhuman.holeManager.getQuadHoleType(level, base); + + if (type == null) { + continue; + } + + visited.add(base); + visited.add(east); + visited.add(south); + visited.add(diagonal); + + AABB box = new AABB( + base.getX(), + base.getY(), + base.getZ(), + base.getX() + 2, + base.getY() + renderHeight(), + base.getZ() + 2 + ); + + out.add(new HoleBox(box, kindOf(type))); + } + } + } + } + + private void addDoubleHoles( + List out, + Level level, + BlockPos origin, + Set visited + ) { + int horizontalRange = Math.round(range.getValue()); + int vertical = Math.round(verticalRange.getValue()); + + for (int x = -horizontalRange; x <= horizontalRange; x++) { + for (int y = -vertical; y <= vertical; y++) { + for (int z = -horizontalRange; z <= horizontalRange; z++) { + BlockPos base = origin.offset(x, y, z); + + if (outOfRenderRange(origin, base)) { + continue; + } + + if (visited.contains(base)) { + continue; + } + + tryAddDouble(out, level, origin, visited, base, Direction.EAST); + tryAddDouble(out, level, origin, visited, base, Direction.SOUTH); + } + } + } + } + + private void tryAddDouble( + List out, + Level level, + BlockPos origin, + Set visited, + BlockPos base, + Direction direction + ) { + BlockPos other = base.relative(direction); + + if (visited.contains(base) || visited.contains(other)) { + return; + } + + if (outOfRenderRange(origin, other)) { + return; + } + + HoleManager.HoleType type = nolongerhuman.holeManager.getDoubleHoleType(level, base, other); + + if (type == null) { + return; + } + + visited.add(base); + visited.add(other); + + int minX = Math.min(base.getX(), other.getX()); + int minZ = Math.min(base.getZ(), other.getZ()); + int maxX = Math.max(base.getX(), other.getX()); + int maxZ = Math.max(base.getZ(), other.getZ()); + + AABB box = new AABB( + minX, + base.getY(), + minZ, + maxX + 1, + base.getY() + renderHeight(), + maxZ + 1 + ); + + out.add(new HoleBox(box, kindOf(type))); + } + + private void addSingleHoles( + List out, + BlockPos origin, + Set visited + ) { + for (HoleManager.Hole hole : nolongerhuman.holeManager.getHoles()) { + if (hole.holeType() == HoleManager.HoleType.PARTIAL) { + continue; + } + + if (visited.contains(hole.pos())) { + continue; + } + + if (outOfRenderRange(origin, hole.pos())) { + continue; + } + + visited.add(hole.pos()); + + AABB box = new AABB( + hole.pos().getX(), + hole.pos().getY(), + hole.pos().getZ(), + hole.pos().getX() + 1, + hole.pos().getY() + renderHeight(), + hole.pos().getZ() + 1 + ); + + out.add(new HoleBox(box, kindOf(hole.holeType()))); + } + } + + private void addPartialHoles( + List out, + BlockPos origin, + Set visited + ) { + for (HoleManager.Hole hole : nolongerhuman.holeManager.getHoles()) { + if (hole.holeType() != HoleManager.HoleType.PARTIAL) { + continue; + } + + if (visited.contains(hole.pos())) { + continue; + } + + if (outOfRenderRange(origin, hole.pos())) { + continue; + } + + visited.add(hole.pos()); + + AABB box = new AABB( + hole.pos().getX(), + hole.pos().getY(), + hole.pos().getZ(), + hole.pos().getX() + 1, + hole.pos().getY() + renderHeight(), + hole.pos().getZ() + 1 + ); + + out.add(new HoleBox(box, HoleKind.PARTIAL)); + } + } + + private boolean outOfRenderRange(BlockPos origin, BlockPos pos) { + double horizontal = horizontalDistanceSq(origin, pos); + double vertical = Math.abs(origin.getY() - pos.getY()); + + return horizontal > range.getValue() * range.getValue() + || vertical > verticalRange.getValue(); + } + + private double horizontalDistanceSq(BlockPos a, BlockPos b) { + double dx = a.getX() - b.getX(); + double dz = a.getZ() - b.getZ(); + + return dx * dx + dz * dz; + } + + private double renderHeight() { + return Math.max(0.0f, height.getValue()); + } + + private boolean isFlat(AABB box) { + return Math.abs(box.maxY - box.minY) <= 0.0001; + } + + private HoleKind kindOf(HoleManager.HoleType type) { + return switch (type) { + case BEDROCK -> HoleKind.BEDROCK; + case UNSAFE -> HoleKind.UNSAFE; + case PARTIAL -> HoleKind.PARTIAL; + default -> HoleKind.MIXED; + }; + } + + @Override + public void onRender3D(Render3DEvent event) { + List boxes = cached; + + if (boxes.isEmpty()) { + return; + } + + for (HoleBox holeBox : boxes) { + draw(event, holeBox.box(), holeBox.kind()); + } + } + + private void draw(Render3DEvent event, AABB box, HoleKind kind) { + Color outline = getOutlineColor(kind); + Color fill = getFillColor(kind); + Color wireframeColor = getWireframeColor(kind); + Color fillGradientColor = getFillGradientColor(kind); + Color lineGradientColor = getLineGradientColor(kind); + Color wireGradientColor = getWireGradientColor(kind); + Color glowColor = getGlowColor(kind); + + float fade = getFadeAlpha(box); + + if (fade <= 0.0f) { + return; + } + + outline = applyFade(outline, fade); + fill = applyFade(fill, fade); + wireframeColor = applyFade(wireframeColor, fade); + fillGradientColor = applyFade(fillGradientColor, fade); + lineGradientColor = applyFade(lineGradientColor, fade); + wireGradientColor = applyFade(wireGradientColor, fade); + glowColor = applyFade(glowColor, fade); + + if (glow.getValue()) { + drawInwardGlow( + event.getMatrix(), + box, + fill, + fillGradientColor, + outline, + lineGradientColor, + wireframeColor, + wireGradientColor, + glowColor + ); + } + + if (isFlat(box)) { + if (gradient.getValue()) { + drawFlatGradientSquare(event.getMatrix(), box, fill, fillGradientColor); + } else { + drawFlatSquare(event.getMatrix(), box, fill); + } + + if (lineGradient.getValue()) { + drawFlatOutlineGradient(event.getMatrix(), box, outline, lineGradientColor, lineWidth.getValue()); + } else { + drawFlatOutline(event.getMatrix(), box, outline, lineWidth.getValue()); + } + + if (wireframe.getValue()) { + if (wireframeGradient.getValue()) { + drawFlatXGradient(event.getMatrix(), box, wireframeColor, wireGradientColor, lineWidth.getValue()); + } else { + drawFlatX(event.getMatrix(), box, wireframeColor, lineWidth.getValue()); + } + } + + return; + } + + if (gradient.getValue()) { + drawGradientBoxFilled(event.getMatrix(), box, fill, fillGradientColor); + } else { + RenderUtil.drawBoxFilled(event.getMatrix(), box, fill); + } + + if (lineGradient.getValue()) { + drawBoxOutlineGradient(event.getMatrix(), box, outline, lineGradientColor, lineWidth.getValue()); + } else { + RenderUtil.drawBox(event.getMatrix(), box, outline, lineWidth.getValue()); + } + + if (wireframe.getValue()) { + if (wireframeGradient.getValue()) { + drawBoxXGradient(event.getMatrix(), box, wireframeColor, wireGradientColor, lineWidth.getValue()); + } else { + drawBoxX(event.getMatrix(), box, wireframeColor, lineWidth.getValue()); + } + } + } + + private Color getOutlineColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockColor.getValue(); + case UNSAFE -> unsafeColor.getValue(); + case PARTIAL -> partialColor.getValue(); + case MIXED -> mixedColor.getValue(); + }; + } + + private Color getFillColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockFill.getValue(); + case UNSAFE -> unsafeFill.getValue(); + case PARTIAL -> partialFill.getValue(); + case MIXED -> mixedFill.getValue(); + }; + } + + private Color getWireframeColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockWireframe.getValue(); + case UNSAFE -> unsafeWireframe.getValue(); + case PARTIAL -> partialWireframe.getValue(); + case MIXED -> mixedWireframe.getValue(); + }; + } + + private Color getFillGradientColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockGradient.getValue(); + case UNSAFE -> unsafeGradient.getValue(); + case PARTIAL -> partialGradient.getValue(); + case MIXED -> mixedGradient.getValue(); + }; + } + + private Color getLineGradientColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockLineGradient.getValue(); + case UNSAFE -> unsafeLineGradient.getValue(); + case PARTIAL -> partialLineGradient.getValue(); + case MIXED -> mixedLineGradient.getValue(); + }; + } + + private Color getWireGradientColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockWireGradient.getValue(); + case UNSAFE -> unsafeWireGradient.getValue(); + case PARTIAL -> partialWireGradient.getValue(); + case MIXED -> mixedWireGradient.getValue(); + }; + } + + private Color getGlowColor(HoleKind kind) { + return switch (kind) { + case BEDROCK -> bedrockGlow.getValue(); + case UNSAFE -> unsafeGlow.getValue(); + case PARTIAL -> partialGlow.getValue(); + case MIXED -> mixedGlow.getValue(); + }; + } + + private void drawInwardGlow( + PoseStack stack, + AABB box, + Color fillColor, + Color fillGradientColor, + Color outlineColor, + Color lineGradientColor, + Color wireframeColor, + Color wireGradientColor, + Color glowColor + ) { + if (glowColor.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, glowPasses.getValue()); + double maxInset = getMaxGlowInset(box); + double wantedInset = Math.min(glowSize.getValue(), maxInset); + + if (wantedInset <= 0.0D) { + return; + } + + float baseWidth = Math.max(lineWidth.getValue(), 1.0f); + + for (int i = 0; i < passes; i++) { + float progress = passes <= 1 ? 0.0f : i / (float) (passes - 1); + double inset = wantedInset * progress; + + AABB glowBox = insetBox(box, inset); + + if (glowBox == null) { + continue; + } + + float alphaFactor = (1.0f - progress) * 0.55f + 0.12f; + + Color passGlow = scaleAlpha(glowColor, alphaFactor); + Color passFill = scaleAlpha(fillColor, alphaFactor * 0.45f); + Color passFillGradient = scaleAlpha(fillGradientColor, alphaFactor); + Color passLine = scaleAlpha(outlineColor, alphaFactor); + Color passLineGradient = scaleAlpha(lineGradientColor, alphaFactor); + Color passWire = scaleAlpha(wireframeColor, alphaFactor); + Color passWireGradient = scaleAlpha(wireGradientColor, alphaFactor); + + float passWidth = baseWidth + (passes - i) * 0.18f; + + if (isFlat(box)) { + if (gradient.getValue()) { + drawFlatGradientSquare(stack, glowBox, passFill, passGlow.getAlpha() > 0 ? passGlow : passFillGradient); + } else { + drawFlatSquare(stack, glowBox, passFill); + } + + if (lineGradient.getValue()) { + drawFlatOutlineGradient(stack, glowBox, passLine, passLineGradient, passWidth); + } else { + drawFlatOutline(stack, glowBox, passGlow, passWidth); + } + + if (wireframe.getValue()) { + if (wireframeGradient.getValue()) { + drawFlatXGradient(stack, glowBox, passWire, passWireGradient, passWidth); + } else { + drawFlatX(stack, glowBox, passGlow, passWidth); + } + } + + continue; + } + + if (gradient.getValue()) { + drawGradientBoxFilled(stack, glowBox, passFill, passGlow.getAlpha() > 0 ? passGlow : passFillGradient); + } else { + RenderUtil.drawBoxFilled(stack, glowBox, passFill); + } + + if (lineGradient.getValue()) { + drawBoxOutlineGradient(stack, glowBox, passLine, passLineGradient, passWidth); + } else { + drawBoxOutline(stack, glowBox, passGlow, passWidth); + } + + if (wireframe.getValue()) { + if (wireframeGradient.getValue()) { + drawBoxXGradient(stack, glowBox, passWire, passWireGradient, passWidth); + } else { + drawBoxX(stack, glowBox, passGlow, passWidth); + } + } + } + } + + private double getMaxGlowInset(AABB box) { + double width = box.maxX - box.minX; + double depth = box.maxZ - box.minZ; + + return Math.max(0.0D, Math.min(width, depth) * 0.5D - 0.001D); + } + + private AABB insetBox(AABB box, double inset) { + double minX = box.minX + inset; + double minZ = box.minZ + inset; + double maxX = box.maxX - inset; + double maxZ = box.maxZ - inset; + + if (maxX <= minX || maxZ <= minZ) { + return null; + } + + return new AABB( + minX, + box.minY, + minZ, + maxX, + box.maxY, + maxZ + ); + } + + private void drawFlatGradientSquare(PoseStack stack, AABB box, Color baseColor, Color highlightColor) { + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float y = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + PoseStack.Pose pose = stack.last(); + + buffer.addVertex(pose.pose(), minX, y, minZ) + .setColor(getMovingGradientColor(box.minX, box.minZ, baseColor, highlightColor).getRGB()); + buffer.addVertex(pose.pose(), maxX, y, minZ) + .setColor(getMovingGradientColor(box.maxX, box.minZ, baseColor, highlightColor).getRGB()); + buffer.addVertex(pose.pose(), maxX, y, maxZ) + .setColor(getMovingGradientColor(box.maxX, box.maxZ, baseColor, highlightColor).getRGB()); + buffer.addVertex(pose.pose(), minX, y, maxZ) + .setColor(getMovingGradientColor(box.minX, box.maxZ, baseColor, highlightColor).getRGB()); + + Layers.quads().draw(buffer.buildOrThrow()); + } + + private void drawGradientBoxFilled(PoseStack stack, AABB box, Color baseColor, Color highlightColor) { + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float minY = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxY = (float) (box.maxY - camera.y); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + PoseStack.Pose pose = stack.last(); + + int c000 = getMovingGradientColor(box.minX, box.minZ, baseColor, highlightColor).getRGB(); + int c100 = getMovingGradientColor(box.maxX, box.minZ, baseColor, highlightColor).getRGB(); + int c110 = getMovingGradientColor(box.maxX, box.maxZ, baseColor, highlightColor).getRGB(); + int c010 = getMovingGradientColor(box.minX, box.maxZ, baseColor, highlightColor).getRGB(); + + addQuad(buffer, pose, minX, minY, minZ, maxX, minY, minZ, maxX, minY, maxZ, minX, minY, maxZ, c000, c100, c110, c010); + addQuad(buffer, pose, minX, maxY, minZ, minX, maxY, maxZ, maxX, maxY, maxZ, maxX, maxY, minZ, c000, c010, c110, c100); + + addQuad(buffer, pose, minX, minY, minZ, minX, maxY, minZ, maxX, maxY, minZ, maxX, minY, minZ, c000, c000, c100, c100); + addQuad(buffer, pose, maxX, minY, maxZ, maxX, maxY, maxZ, minX, maxY, maxZ, minX, minY, maxZ, c110, c110, c010, c010); + + addQuad(buffer, pose, minX, minY, maxZ, minX, maxY, maxZ, minX, maxY, minZ, minX, minY, minZ, c010, c010, c000, c000); + addQuad(buffer, pose, maxX, minY, minZ, maxX, maxY, minZ, maxX, maxY, maxZ, maxX, minY, maxZ, c100, c100, c110, c110); + + Layers.quads().draw(buffer.buildOrThrow()); + } + + private void addQuad( + BufferBuilder buffer, + PoseStack.Pose pose, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2, + float x3, + float y3, + float z3, + float x4, + float y4, + float z4, + int c1, + int c2, + int c3, + int c4 + ) { + buffer.addVertex(pose.pose(), x1, y1, z1).setColor(c1); + buffer.addVertex(pose.pose(), x2, y2, z2).setColor(c2); + buffer.addVertex(pose.pose(), x3, y3, z3).setColor(c3); + buffer.addVertex(pose.pose(), x4, y4, z4).setColor(c4); + } + + private Color getMovingGradientColor(double x, double z, Color baseColor, Color highlightColor) { + double time = System.currentTimeMillis() / 1000.0D; + double speed = gradientSpeed.getValue(); + double scale = Math.max(0.1D, gradientScale.getValue()); + + double wave = Math.sin((x + z) * scale + time * speed * 2.0D); + float factor = (float) ((wave + 1.0D) * 0.5D); + + factor = factor * factor * (3.0f - 2.0f * factor); + + return mix(baseColor, highlightColor, factor); + } + + private Color mix(Color from, Color to, float factor) { + factor = clamp01(factor); + + int red = Math.round(from.getRed() + (to.getRed() - from.getRed()) * factor); + int green = Math.round(from.getGreen() + (to.getGreen() - from.getGreen()) * factor); + int blue = Math.round(from.getBlue() + (to.getBlue() - from.getBlue()) * factor); + int alpha = Math.round(from.getAlpha() + (to.getAlpha() - from.getAlpha()) * factor); + + return new Color( + clampColor(red), + clampColor(green), + clampColor(blue), + clampColor(alpha) + ); + } + + private int clampColor(int value) { + return Math.max(0, Math.min(255, value)); + } + + private float getFadeAlpha(AABB box) { + if (mc.player == null) { + return 1.0f; + } + + float renderRange = range.getValue(); + float fade = fadeDistance.getValue(); + + if (fade <= 0.0f || renderRange <= 0.0f) { + return 1.0f; + } + + fade = Math.min(fade, renderRange); + + Vec3 playerPos = mc.player.position(); + + double centerX = (box.minX + box.maxX) * 0.5; + double centerZ = (box.minZ + box.maxZ) * 0.5; + double dx = centerX - playerPos.x; + double dz = centerZ - playerPos.z; + double distance = Math.sqrt(dx * dx + dz * dz); + + double fadeStart = renderRange - fade; + + if (distance <= fadeStart) { + return 1.0f; + } + + if (distance >= renderRange) { + return 0.0f; + } + + float alpha = (float) ((renderRange - distance) / fade); + alpha = alpha * alpha * (3.0f - 2.0f * alpha); + + return clamp01(alpha); + } + + private Color applyFade(Color color, float fade) { + fade = clamp01(fade); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + Math.round(color.getAlpha() * fade) + ); + } + + private Color scaleAlpha(Color color, float scale) { + scale = clamp01(scale); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + Math.round(color.getAlpha() * scale) + ); + } + + private float clamp01(float value) { + return Math.max(0.0f, Math.min(1.0f, value)); + } + + private void drawFlatSquare(PoseStack stack, AABB box, Color color) { + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float y = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + int rgb = color.getRGB(); + + buffer.addVertex(stack.last().pose(), minX, y, minZ).setColor(rgb); + buffer.addVertex(stack.last().pose(), maxX, y, minZ).setColor(rgb); + buffer.addVertex(stack.last().pose(), maxX, y, maxZ).setColor(rgb); + buffer.addVertex(stack.last().pose(), minX, y, maxZ).setColor(rgb); + + Layers.quads().draw(buffer.buildOrThrow()); + } + + private void drawFlatOutline(PoseStack stack, AABB box, Color color, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float y = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int rgb = color.getRGB(); + + addLine(buffer, pose, rgb, width, minX, y, minZ, maxX, y, minZ); + addLine(buffer, pose, rgb, width, maxX, y, minZ, maxX, y, maxZ); + addLine(buffer, pose, rgb, width, maxX, y, maxZ, minX, y, maxZ); + addLine(buffer, pose, rgb, width, minX, y, maxZ, minX, y, minZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawFlatOutlineGradient(PoseStack stack, AABB box, Color baseColor, Color highlightColor, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float y = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + + int cMinMin = getMovingGradientColor(box.minX, box.minZ, baseColor, highlightColor).getRGB(); + int cMaxMin = getMovingGradientColor(box.maxX, box.minZ, baseColor, highlightColor).getRGB(); + int cMaxMax = getMovingGradientColor(box.maxX, box.maxZ, baseColor, highlightColor).getRGB(); + int cMinMax = getMovingGradientColor(box.minX, box.maxZ, baseColor, highlightColor).getRGB(); + + addGradientLine(buffer, pose, cMinMin, cMaxMin, width, minX, y, minZ, maxX, y, minZ); + addGradientLine(buffer, pose, cMaxMin, cMaxMax, width, maxX, y, minZ, maxX, y, maxZ); + addGradientLine(buffer, pose, cMaxMax, cMinMax, width, maxX, y, maxZ, minX, y, maxZ); + addGradientLine(buffer, pose, cMinMax, cMinMin, width, minX, y, maxZ, minX, y, minZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawBoxOutline(PoseStack stack, AABB box, Color color, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float minY = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxY = (float) (box.maxY - camera.y); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int rgb = color.getRGB(); + + addLine(buffer, pose, rgb, width, minX, minY, minZ, maxX, minY, minZ); + addLine(buffer, pose, rgb, width, maxX, minY, minZ, maxX, minY, maxZ); + addLine(buffer, pose, rgb, width, maxX, minY, maxZ, minX, minY, maxZ); + addLine(buffer, pose, rgb, width, minX, minY, maxZ, minX, minY, minZ); + + addLine(buffer, pose, rgb, width, minX, maxY, minZ, maxX, maxY, minZ); + addLine(buffer, pose, rgb, width, maxX, maxY, minZ, maxX, maxY, maxZ); + addLine(buffer, pose, rgb, width, maxX, maxY, maxZ, minX, maxY, maxZ); + addLine(buffer, pose, rgb, width, minX, maxY, maxZ, minX, maxY, minZ); + + addLine(buffer, pose, rgb, width, minX, minY, minZ, minX, maxY, minZ); + addLine(buffer, pose, rgb, width, maxX, minY, minZ, maxX, maxY, minZ); + addLine(buffer, pose, rgb, width, maxX, minY, maxZ, maxX, maxY, maxZ); + addLine(buffer, pose, rgb, width, minX, minY, maxZ, minX, maxY, maxZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawBoxOutlineGradient(PoseStack stack, AABB box, Color baseColor, Color highlightColor, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float minY = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxY = (float) (box.maxY - camera.y); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + + int cMinMin = getMovingGradientColor(box.minX, box.minZ, baseColor, highlightColor).getRGB(); + int cMaxMin = getMovingGradientColor(box.maxX, box.minZ, baseColor, highlightColor).getRGB(); + int cMaxMax = getMovingGradientColor(box.maxX, box.maxZ, baseColor, highlightColor).getRGB(); + int cMinMax = getMovingGradientColor(box.minX, box.maxZ, baseColor, highlightColor).getRGB(); + + addGradientLine(buffer, pose, cMinMin, cMaxMin, width, minX, minY, minZ, maxX, minY, minZ); + addGradientLine(buffer, pose, cMaxMin, cMaxMax, width, maxX, minY, minZ, maxX, minY, maxZ); + addGradientLine(buffer, pose, cMaxMax, cMinMax, width, maxX, minY, maxZ, minX, minY, maxZ); + addGradientLine(buffer, pose, cMinMax, cMinMin, width, minX, minY, maxZ, minX, minY, minZ); + + addGradientLine(buffer, pose, cMinMin, cMaxMin, width, minX, maxY, minZ, maxX, maxY, minZ); + addGradientLine(buffer, pose, cMaxMin, cMaxMax, width, maxX, maxY, minZ, maxX, maxY, maxZ); + addGradientLine(buffer, pose, cMaxMax, cMinMax, width, maxX, maxY, maxZ, minX, maxY, maxZ); + addGradientLine(buffer, pose, cMinMax, cMinMin, width, minX, maxY, maxZ, minX, maxY, minZ); + + addGradientLine(buffer, pose, cMinMin, cMinMin, width, minX, minY, minZ, minX, maxY, minZ); + addGradientLine(buffer, pose, cMaxMin, cMaxMin, width, maxX, minY, minZ, maxX, maxY, minZ); + addGradientLine(buffer, pose, cMaxMax, cMaxMax, width, maxX, minY, maxZ, maxX, maxY, maxZ); + addGradientLine(buffer, pose, cMinMax, cMinMax, width, minX, minY, maxZ, minX, maxY, maxZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawFlatX(PoseStack stack, AABB box, Color color, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float y = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int rgb = color.getRGB(); + + addLine(buffer, pose, rgb, width, minX, y, minZ, maxX, y, maxZ); + addLine(buffer, pose, rgb, width, maxX, y, minZ, minX, y, maxZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawFlatXGradient(PoseStack stack, AABB box, Color baseColor, Color highlightColor, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float y = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + + int cMinMin = getMovingGradientColor(box.minX, box.minZ, baseColor, highlightColor).getRGB(); + int cMaxMax = getMovingGradientColor(box.maxX, box.maxZ, baseColor, highlightColor).getRGB(); + int cMaxMin = getMovingGradientColor(box.maxX, box.minZ, baseColor, highlightColor).getRGB(); + int cMinMax = getMovingGradientColor(box.minX, box.maxZ, baseColor, highlightColor).getRGB(); + + addGradientLine(buffer, pose, cMinMin, cMaxMax, width, minX, y, minZ, maxX, y, maxZ); + addGradientLine(buffer, pose, cMaxMin, cMinMax, width, maxX, y, minZ, minX, y, maxZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawBoxX(PoseStack stack, AABB box, Color color, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float minY = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxY = (float) (box.maxY - camera.y); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int rgb = color.getRGB(); + + addLine(buffer, pose, rgb, width, minX, minY, minZ, maxX, minY, maxZ); + addLine(buffer, pose, rgb, width, maxX, minY, minZ, minX, minY, maxZ); + addLine(buffer, pose, rgb, width, minX, maxY, minZ, maxX, maxY, maxZ); + addLine(buffer, pose, rgb, width, maxX, maxY, minZ, minX, maxY, maxZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void drawBoxXGradient(PoseStack stack, AABB box, Color baseColor, Color highlightColor, float width) { + if (width <= 0.0f) { + return; + } + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + float minX = (float) (box.minX - camera.x); + float minY = (float) (box.minY - camera.y); + float minZ = (float) (box.minZ - camera.z); + float maxX = (float) (box.maxX - camera.x); + float maxY = (float) (box.maxY - camera.y); + float maxZ = (float) (box.maxZ - camera.z); + + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + + int cMinMin = getMovingGradientColor(box.minX, box.minZ, baseColor, highlightColor).getRGB(); + int cMaxMax = getMovingGradientColor(box.maxX, box.maxZ, baseColor, highlightColor).getRGB(); + int cMaxMin = getMovingGradientColor(box.maxX, box.minZ, baseColor, highlightColor).getRGB(); + int cMinMax = getMovingGradientColor(box.minX, box.maxZ, baseColor, highlightColor).getRGB(); + + addGradientLine(buffer, pose, cMinMin, cMaxMax, width, minX, minY, minZ, maxX, minY, maxZ); + addGradientLine(buffer, pose, cMaxMin, cMinMax, width, maxX, minY, minZ, minX, minY, maxZ); + addGradientLine(buffer, pose, cMinMin, cMaxMax, width, minX, maxY, minZ, maxX, maxY, maxZ); + addGradientLine(buffer, pose, cMaxMin, cMinMax, width, maxX, maxY, minZ, minX, maxY, maxZ); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + private void addLine( + BufferBuilder buffer, + PoseStack.Pose pose, + int color, + float width, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2 + ) { + addGradientLine(buffer, pose, color, color, width, x1, y1, z1, x2, y2, z2); + } + + private void addGradientLine( + BufferBuilder buffer, + PoseStack.Pose pose, + int color1, + int color2, + float width, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2 + ) { + float nx = x2 - x1; + float ny = y2 - y1; + float nz = z2 - z1; + + buffer.addVertex(pose, x1, y1, z1) + .setColor(color1) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + + buffer.addVertex(pose, x2, y2, z2) + .setColor(color2) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + } + + private enum HoleKind { + BEDROCK, + UNSAFE, + MIXED, + PARTIAL + } + + private record HoleBox(AABB box, HoleKind kind) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/KillEffect.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/KillEffect.java new file mode 100644 index 0000000..ad3d70f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/KillEffect.java @@ -0,0 +1,165 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class KillEffect extends Module { + + public static KillEffect INSTANCE; + + public enum Mode { + Sparkle, + Orthodox, + FallingLava + } + + private final Setting mode = mode("Mode", Mode.Sparkle); + private final Setting speed = num("Speed", 0.0f, -10.0f, 10.0f); + private final Setting playSound = bool("PlaySound", true); + private final Setting volume = num("Volume", 100, 0, 100); + private final Setting color = color("Color", new Color(255, 255, 0, 150)); + private final Setting mobs = bool("Mobs", false); + private final Setting lineWidth = num("LineWidth", 2.0f, 0.1f, 6.0f); + + private final Map renderEntities = new ConcurrentHashMap<>(); + private final Map seenDead = new ConcurrentHashMap<>(); + + public KillEffect() { + super("KillEffect", "Renders effects on entity death", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onTick() { + if (nullCheck() || mc.level == null || mc.player == null) return; + + for (Entity entity : mc.level.entitiesForRendering()) { + if (entity == mc.player) continue; + if (!(entity instanceof LivingEntity living)) continue; + if (!(entity instanceof Player) && !mobs.getValue()) continue; + + if (living.isAlive() && living.getHealth() > 0.0f) continue; + if (renderEntities.containsKey(entity.getId())) continue; + if (seenDead.containsKey(entity.getId())) continue; + + Vec3 pos = entity.position(); + + renderEntities.put(entity.getId(), new DeathRender(pos, System.currentTimeMillis())); + seenDead.put(entity.getId(), System.currentTimeMillis()); + + if (playSound.getValue()) { + mc.level.playLocalSound( + pos.x, + pos.y, + pos.z, + SoundEvents.LIGHTNING_BOLT_THUNDER, + SoundSource.MASTER, + volume.getValue() / 100.0f, + 1.0f, + false + ); + } + } + + long now = System.currentTimeMillis(); + + renderEntities.entrySet().removeIf(entry -> now - entry.getValue().timeMs > 3000L); + seenDead.entrySet().removeIf(entry -> now - entry.getValue() > 5000L); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (nullCheck() || mc.level == null) return; + + switch (mode.getValue()) { + case Orthodox -> { + for (DeathRender death : renderEntities.values()) { + double offset = calculateSpeed(); + Vec3 base = death.pos.add(0.0, offset, 0.0); + + RenderUtil.drawBox( + event.getMatrix(), + new net.minecraft.world.phys.AABB( + base.x - 0.03, + base.y, + base.z - 0.03, + base.x + 0.03, + base.y + 3.0, + base.z + 0.03 + ), + color.getValue(), + lineWidth.getValue() + ); + + RenderUtil.drawBox( + event.getMatrix(), + new net.minecraft.world.phys.AABB( + base.x - 1.0, + base.y + 2.25, + base.z - 0.03, + base.x + 1.0, + base.y + 2.35, + base.z + 0.03 + ), + color.getValue(), + lineWidth.getValue() + ); + } + } + + case FallingLava -> { + for (DeathRender death : renderEntities.values()) { + for (int i = 0; i < 20; i++) { + mc.level.addParticle( + ParticleTypes.FALLING_LAVA, + death.pos.x + (Math.random() - 0.5), + death.pos.y + Math.random() * 2.0, + death.pos.z + (Math.random() - 0.5), + 0.0, + 0.0, + 0.0 + ); + } + } + + renderEntities.clear(); + } + + case Sparkle -> { + for (DeathRender death : renderEntities.values()) { + for (int i = 0; i < 8; i++) { + mc.level.addParticle( + ParticleTypes.ELECTRIC_SPARK, + death.pos.x + (Math.random() - 0.5), + death.pos.y + Math.random() * 2.0, + death.pos.z + (Math.random() - 0.5), + 0.0, + 0.08, + 0.0 + ); + } + } + } + } + } + + private double calculateSpeed() { + return speed.getValue() / 100.0; + } + + private record DeathRender(Vec3 pos, long timeMs) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Nametags.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Nametags.java new file mode 100644 index 0000000..74b27ce --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Nametags.java @@ -0,0 +1,622 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.ColorUtil; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityAttachment; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class Nametags extends Module { + public static Nametags INSTANCE; + + private static final EquipmentSlot[] ARMOR_ORDER = { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + + private static final int ARMOR_TEXT_Y_OFFSET = -20; + private static final int DURABILITY_Y_OFFSET = -10; + private static final int MAIN_Y_OFFSET = 0; + + private final Setting health = bool("Health", true); + + private final Setting armorIcons = bool("ArmorIcons", true); + private final Setting armorText = bool("ArmorText", false); + private final Setting armorDurability = bool("ArmorDurability", true); + private final Setting armorPercentIcon = bool("ArmorPercent", false); + private final Setting armorShadow = bool("ArmorShadow", true); + private final Setting armorNameGap = num("ArmorNameGap", 10, 0, 40); + private final Setting armorDurabilitySpacing = num("ArmorDurabilitySpacing", 20, 1, 80); + + private final Setting background = bool("Background", true); + private final Setting backgroundColor = color("BackgroundColor", new Color(0, 0, 0, 90)); + private final Setting backgroundBorderColor = color("BackgroundBorderColor", new Color(255, 255, 255, 180)); + + private final Setting self = bool("Self", false); + private final Setting invisibles = bool("Invisibles", true); + private final Setting range = num("Range", 300.0, 1.0, 300.0); + private final Setting yOffset = num("YOffset", 0.0, -2.0, 2.0); + + private final Setting distanceScaling = bool("DistanceScaling", true); + private final Setting minScale = num("MinScale", 1.0, 0.25, 10.0); + private final Setting maxScale = num("MaxScale", 4.0, 0.25, 20.0); + private final Setting scaleStartDistance = num("ScaleStartDistance", 8.0, 0.0, 300.0); + private final Setting scaleEndDistance = num("ScaleEndDistance", 80.0, 1.0, 300.0); + + private final Setting nameColor = color("NameColor", new Color(0, 255, 255, 255)); + private final Setting goodHealthColor = color("GoodHealth", new Color(0, 255, 0, 255)); + private final Setting midHealthColor = color("MidHealth", new Color(255, 255, 0, 255)); + private final Setting lowHealthColor = color("LowHealth", new Color(255, 0, 0, 255)); + + private final Setting goodDurabilityColor = color("GoodDurability", new Color(34, 255, 0, 255)); + private final Setting midDurabilityColor = color("MidDurability", new Color(255, 136, 0, 255)); + private final Setting lowDurabilityColor = color("LowDurability", new Color(255, 0, 0, 255)); + + private final DecimalFormat healthFormat = new DecimalFormat("#.#"); + + public Nametags() { + super("Nametags", "Renders custom player nametags", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + } + + public static boolean shouldRenderNametag(Entity entity) { + if (INSTANCE == null) { + return false; + } + + if (!INSTANCE.isEnabled()) { + return false; + } + + if (!(entity instanceof Player player)) { + return false; + } + + return INSTANCE.canRenderPlayer(player); + } + + public static Vec3 getNameTagAttachment(Entity entity, float partialTick) { + Vec3 attachment = entity.getAttachments().getNullable( + EntityAttachment.NAME_TAG, + 0, + entity.getYRot(partialTick) + ); + + if (attachment == null) { + attachment = new Vec3(0.0D, entity.getBbHeight() + 0.5D, 0.0D); + } + + if (INSTANCE == null) { + return attachment; + } + + return attachment.add(0.0D, INSTANCE.yOffset.getValue(), 0.0D); + } + + public static boolean shouldRenderBackground() { + return INSTANCE != null && INSTANCE.background.getValue(); + } + + public static int getBackgroundColor() { + if (INSTANCE == null) { + return new Color(0, 0, 0, 90).getRGB(); + } + + return INSTANCE.backgroundColor.getValue().getRGB(); + } + + public static int getBackgroundBorderColor() { + if (INSTANCE == null) { + return new Color(255, 255, 255, 180).getRGB(); + } + + return INSTANCE.backgroundBorderColor.getValue().getRGB(); + } + + public static boolean shouldRenderVanillaBackground() { + return false; + } + + public static int getArmorTextYOffset() { + return ARMOR_TEXT_Y_OFFSET; + } + + public static int getDurabilityYOffset() { + return DURABILITY_Y_OFFSET; + } + + public static int getMainYOffset() { + return MAIN_Y_OFFSET; + } + + public static int getArmorNameGap() { + if (INSTANCE == null) { + return 10; + } + + return INSTANCE.armorNameGap.getValue(); + } + + public static int getArmorDurabilitySpacing() { + if (INSTANCE == null) { + return 20; + } + + return INSTANCE.armorDurabilitySpacing.getValue(); + } + + public static float getNametagScale(Entity entity, double distanceToCameraSq) { + if (INSTANCE == null) { + return 1.0F; + } + + return INSTANCE.getScaleForEntity(entity, distanceToCameraSq); + } + + public static Component getMainText(Entity entity) { + if (!shouldRenderNametag(entity)) { + return null; + } + + return INSTANCE.buildMainText((Player) entity); + } + + public static Component getArmorText(Entity entity) { + if (!shouldRenderNametag(entity)) { + return null; + } + + return INSTANCE.buildArmorText((Player) entity); + } + + public static Component getDurabilityText(Entity entity) { + if (!shouldRenderNametag(entity)) { + return null; + } + + return INSTANCE.buildDurabilityText((Player) entity); + } + + public static boolean shouldRenderArmorIcons(Entity entity) { + if (!shouldRenderNametag(entity)) { + return false; + } + + if (!(entity instanceof Player player)) { + return false; + } + + return INSTANCE.armorIcons.getValue() && INSTANCE.hasArmor(player); + } + + public static boolean shouldRenderArmorText() { + return INSTANCE != null && INSTANCE.armorText.getValue(); + } + + public static boolean shouldRenderArmorDurability() { + return INSTANCE != null && INSTANCE.armorDurability.getValue(); + } + + public static boolean shouldRenderArmorShadow() { + return INSTANCE != null && INSTANCE.armorShadow.getValue(); + } + + public static String getArmorPieceText(ItemStack stack, EquipmentSlot slot) { + if (INSTANCE == null || stack == null || stack.isEmpty()) { + return ""; + } + + return "[" + INSTANCE.getArmorShortName(stack, slot) + "]"; + } + + public static int getArmorPieceTextColor(ItemStack stack) { + if (INSTANCE == null || stack == null || stack.isEmpty()) { + return Color.WHITE.getRGB(); + } + + return INSTANCE.getDurabilityColor(INSTANCE.getDurabilityPercent(stack)).getRGB(); + } + + public static String getArmorDurabilityText(ItemStack stack) { + if (INSTANCE == null || stack == null || stack.isEmpty()) { + return ""; + } + + if (!stack.isDamageableItem() || stack.getMaxDamage() <= 0) { + return ""; + } + + int percent = INSTANCE.getDurabilityPercent(stack); + return percent + (INSTANCE.armorPercentIcon.getValue() ? "%" : ""); + } + + public static int getArmorDurabilityTextColor(ItemStack stack) { + if (INSTANCE == null || stack == null || stack.isEmpty()) { + return Color.WHITE.getRGB(); + } + + return INSTANCE.getDurabilityColor(INSTANCE.getDurabilityPercent(stack)).getRGB(); + } + + private boolean canRenderPlayer(Player player) { + if (mc.player == null) { + return false; + } + + if (player == mc.player && !self.getValue()) { + return false; + } + + if (player == mc.player && mc.options.getCameraType().isFirstPerson()) { + return false; + } + + if (!player.isAlive()) { + return false; + } + + if (!invisibles.getValue() && player.isInvisible()) { + return false; + } + + double rangeSq = range.getValue() * range.getValue(); + return mc.player.distanceToSqr(player) <= rangeSq; + } + + private float getScaleForEntity(Entity entity, double distanceToCameraSq) { + float min = clampScale(minScale.getValue().floatValue()); + float max = clampScale(maxScale.getValue().floatValue()); + + if (max < min) { + float temp = min; + min = max; + max = temp; + } + + if (!distanceScaling.getValue()) { + return min; + } + + double start = scaleStartDistance.getValue(); + double end = scaleEndDistance.getValue(); + + if (end <= start) { + end = start + 1.0D; + } + + double distance; + + if (distanceToCameraSq > 0.0D) { + distance = Math.sqrt(distanceToCameraSq); + } else if (mc.player != null && entity != null) { + distance = Math.sqrt(mc.player.distanceToSqr(entity)); + } else { + distance = start; + } + + if (distance <= start) { + return min; + } + + if (distance >= end) { + return max; + } + + float factor = (float) ((distance - start) / (end - start)); + factor = Math.max(0.0F, Math.min(1.0F, factor)); + factor = factor * factor * (3.0F - 2.0F * factor); + + return min + (max - min) * factor; + } + + private float clampScale(float value) { + return Math.max(0.05F, Math.min(32.0F, value)); + } + + private Component buildMainText(Player player) { + MutableComponent component = Component.empty(); + String name = getRawPlayerName(player); + + if (name.isEmpty()) { + return Component.empty(); + } + + component.append( + Component.literal(name) + .withStyle(style(nameColor.getValue())) + ); + + if (health.getValue()) { + float hp = getHealthValue(player); + + component.append(Component.literal(" ")); + component.append( + Component.literal(healthFormat.format(hp)) + .withStyle(style(getHealthColor(hp))) + ); + } + + return component; + } + + private Component buildArmorText(Player player) { + if (!armorText.getValue()) { + return null; + } + + List parts = getArmorParts(player); + + if (parts.isEmpty()) { + return null; + } + + MutableComponent component = Component.empty(); + + for (int i = 0; i < parts.size(); i++) { + ArmorPart part = parts.get(i); + + if (i > 0) { + component.append(Component.literal(" ")); + } + + component.append( + Component.literal(part.label()) + .withStyle(style(getDurabilityColor(part.durabilityPercent()))) + ); + } + + return component; + } + + private Component buildDurabilityText(Player player) { + if (!armorDurability.getValue()) { + return null; + } + + List parts = getArmorParts(player); + + if (parts.isEmpty()) { + return null; + } + + MutableComponent component = Component.empty(); + boolean hasDurability = false; + + for (int i = 0; i < parts.size(); i++) { + ArmorPart part = parts.get(i); + + if (i > 0) { + component.append(Component.literal(" ")); + } + + if (part.durabilityText().isEmpty()) { + component.append(Component.literal(" ")); + continue; + } + + component.append( + Component.literal(part.durabilityText()) + .withStyle(style(getDurabilityColor(part.durabilityPercent()))) + ); + + hasDurability = true; + } + + return hasDurability ? component : null; + } + + private boolean hasArmor(Player player) { + for (EquipmentSlot slot : ARMOR_ORDER) { + if (!player.getItemBySlot(slot).isEmpty()) { + return true; + } + } + + return false; + } + + private List getArmorParts(Player player) { + List parts = new ArrayList<>(); + + for (EquipmentSlot slot : ARMOR_ORDER) { + ItemStack stack = player.getItemBySlot(slot); + + if (stack.isEmpty()) { + continue; + } + + int durabilityPercent = getDurabilityPercent(stack); + + String durabilityText = stack.isDamageableItem() + ? durabilityPercent + (armorPercentIcon.getValue() ? "%" : "") + : ""; + + parts.add(new ArmorPart( + "[" + getArmorShortName(stack, slot) + "]", + durabilityText, + durabilityPercent + )); + } + + return parts; + } + + private String getRawPlayerName(Player player) { + return player.getScoreboardName(); + } + + private float getHealthValue(Player player) { + return player.getHealth() + player.getAbsorptionAmount(); + } + + private String getArmorShortName(ItemStack stack, EquipmentSlot slot) { + return getArmorMaterialName(stack) + getArmorSlotName(stack, slot); + } + + private String getArmorSlotName(ItemStack stack, EquipmentSlot slot) { + if (stack.is(Items.ELYTRA)) { + return "E"; + } + + if (slot == EquipmentSlot.HEAD) { + return "H"; + } + + if (slot == EquipmentSlot.CHEST) { + return "C"; + } + + if (slot == EquipmentSlot.LEGS) { + return "L"; + } + + if (slot == EquipmentSlot.FEET) { + return "B"; + } + + return "?"; + } + + private String getArmorMaterialName(ItemStack stack) { + if (stack.is(Items.NETHERITE_HELMET) + || stack.is(Items.NETHERITE_CHESTPLATE) + || stack.is(Items.NETHERITE_LEGGINGS) + || stack.is(Items.NETHERITE_BOOTS)) { + return "N"; + } + + if (stack.is(Items.DIAMOND_HELMET) + || stack.is(Items.DIAMOND_CHESTPLATE) + || stack.is(Items.DIAMOND_LEGGINGS) + || stack.is(Items.DIAMOND_BOOTS)) { + return "D"; + } + + if (stack.is(Items.IRON_HELMET) + || stack.is(Items.IRON_CHESTPLATE) + || stack.is(Items.IRON_LEGGINGS) + || stack.is(Items.IRON_BOOTS)) { + return "I"; + } + + if (stack.is(Items.GOLDEN_HELMET) + || stack.is(Items.GOLDEN_CHESTPLATE) + || stack.is(Items.GOLDEN_LEGGINGS) + || stack.is(Items.GOLDEN_BOOTS)) { + return "G"; + } + + if (stack.is(Items.CHAINMAIL_HELMET) + || stack.is(Items.CHAINMAIL_CHESTPLATE) + || stack.is(Items.CHAINMAIL_LEGGINGS) + || stack.is(Items.CHAINMAIL_BOOTS)) { + return "C"; + } + + if (stack.is(Items.LEATHER_HELMET) + || stack.is(Items.LEATHER_CHESTPLATE) + || stack.is(Items.LEATHER_LEGGINGS) + || stack.is(Items.LEATHER_BOOTS)) { + return "L"; + } + + if (stack.is(Items.TURTLE_HELMET)) { + return "T"; + } + + if (stack.is(Items.ELYTRA)) { + return "E"; + } + + return "?"; + } + + private int getDurabilityPercent(ItemStack stack) { + if (!stack.isDamageableItem()) { + return 100; + } + + int maxDamage = stack.getMaxDamage(); + + if (maxDamage <= 0) { + return 100; + } + + int remaining = maxDamage - stack.getDamageValue(); + float percentage = remaining / (float) maxDamage * 100.0F; + + return Math.max(0, Math.min(100, Math.round(percentage))); + } + + private Color getHealthColor(float value) { + if (value >= 15.0F) { + return goodHealthColor.getValue(); + } + + if (value >= 8.0F) { + float factor = (value - 8.0F) / 7.0F; + return ColorUtil.interpolate(midHealthColor.getValue(), goodHealthColor.getValue(), factor); + } + + float factor = Math.max(0.0F, Math.min(1.0F, value / 8.0F)); + return ColorUtil.interpolate(lowHealthColor.getValue(), midHealthColor.getValue(), factor); + } + + private Color getDurabilityColor(int durability) { + if (durability >= 75) { + return goodDurabilityColor.getValue(); + } + + if (durability >= 35) { + float factor = (durability - 35.0F) / 40.0F; + return ColorUtil.interpolate(midDurabilityColor.getValue(), goodDurabilityColor.getValue(), factor); + } + + float factor = Math.max(0.0F, Math.min(1.0F, durability / 35.0F)); + return ColorUtil.interpolate(lowDurabilityColor.getValue(), midDurabilityColor.getValue(), factor); + } + + private Style style(Color color) { + return Style.EMPTY.withColor(color.getRGB() & 0xFFFFFF); + } + + @Override + public String getDisplayInfo() { + if (!distanceScaling.getValue()) { + return String.valueOf(range.getValue().intValue()); + } + + return String.format( + "%.1fx-%.1fx", + minScale.getValue(), + maxScale.getValue() + ); + } + + private record ArmorPart( + String label, + String durabilityText, + int durabilityPercent + ) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/NoEatingAnimation.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/NoEatingAnimation.java new file mode 100644 index 0000000..9b8ef14 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/NoEatingAnimation.java @@ -0,0 +1,47 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.features.modules.Module; +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.ItemStack; + +public class NoEatingAnimation extends Module { + + private static NoEatingAnimation INSTANCE; + + public NoEatingAnimation() { + super("NoEatingAnimation", "Cancels the first person eating animation", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + } + + public static boolean shouldCancelEatingAnimation(ItemStack stack) { + NoEatingAnimation module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (stack == null) { + return false; + } + + if (stack.isEmpty()) { + return false; + } + + return stack.has(DataComponents.FOOD); + } + + @Override + public String getDisplayInfo() { + return "Eating"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/NoRender.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/NoRender.java new file mode 100644 index 0000000..19c1e92 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/NoRender.java @@ -0,0 +1,868 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.impl.render.ParticleEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.particle.Particle; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.player.Player; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Map; + +public class NoRender extends Module { + + private static NoRender INSTANCE; + + public final Setting portal = bool("Portal", true); + public final Setting spyglassOverlay = bool("Spyglass", false); + public final Setting nausea = bool("Nausea", true); + public final Setting pumpkinOverlay = bool("Pumpkin", false); + public final Setting powderedSnowOverlay = bool("PowderSnow", false); + public final Setting fireOverlay = bool("FireOverlay", true); + public final Setting waterOverlay = bool("WaterOverlay", true); + public final Setting blockOverlay = bool("BlockOverlay", true); + public final Setting vignette = bool("Vignette", false); + public final Setting guiBackground = bool("GuiBackground", false); + public final Setting totem = bool("Totem", true); + public final Setting eatingParticles = bool("EatingParticles", false); + public final Setting enchantGlint = bool("EnchantGlint", false); + + public final Setting potionsIcon = bool("PotionsIcon", false); + public final Setting bossBars = bool("BossBars", false); + public final Setting scoreboard = bool("Scoreboard", false); + public final Setting crosshair = bool("Crosshair", false); + public final Setting antiTitle = bool("Title", false); + public final Setting heldItemName = bool("HeldItemName", false); + public final Setting obfuscation = bool("Obfuscation", false); + public final Setting messageSignatureIndicator = bool("MessageSignature", false); + + public final Setting weather = bool("Weather", true); + public final Setting worldBorder = bool("WorldBorder", false); + public final Setting blindness = bool("Blindness", true); + public final Setting darkness = bool("Darkness", true); + public final Setting fog = bool("Fog", false); + public final Setting enchantTableBook = bool("EnchantBook", false); + public final Setting signText = bool("SignText", false); + public final Setting blockBreakOverlay = bool("BlockBreak", false); + public final Setting beaconBeams = bool("BeaconBeams", false); + public final Setting fallingBlocks = bool("FallingBlocks", false); + public final Setting caveCulling = bool("CaveCulling", false); + public final Setting mapMarkers = bool("MapMarkers", false); + public final Setting mapContents = bool("MapContents", false); + public final Setting fireworkExplosions = bool("FireworkExplosions", false); + public final Setting barrierInvisibility = bool("BarrierInvis", false); + public final Setting textureRotations = bool("TextureRotations", false); + + public final Setting potions = bool("Potions", true); + public final Setting effect = bool("Effect", true); + public final Setting elderGuardian = bool("Guardian", false); + public final Setting explosions = bool("Explosions", true); + public final Setting campFire = bool("CampFire", false); + public final Setting fireworks = bool("Fireworks", false); + public final Setting rainParticles = bool("RainParticles", false); + public final Setting smokeParticles = bool("SmokeParticles", false); + public final Setting flameParticles = bool("FlameParticles", false); + public final Setting portalParticles = bool("PortalParticles", false); + public final Setting critParticles = bool("CritParticles", false); + + public final Setting invisible = bool("Invisible", false); + public final Setting armor = bool("Armor", false); + public final Setting hurtCam = bool("HurtCam", true); + public final Setting fireEntity = bool("EntityFire", true); + public final Setting antiPlayerCollision = bool("PlayerCollision", true); + public final Setting glowing = bool("Glowing", false); + public final Setting mobInSpawner = bool("SpawnerMobs", false); + public final Setting deadEntities = bool("DeadEntities", false); + public final Setting nametags = bool("Nametags", false); + public final Setting dropSpawnPackets = bool("DropSpawnPackets", false); + + private boolean forceRendererReload = false; + + public NoRender() { + super("NoRender", "Disables selected rendered effects", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + forceRendererReload = true; + + if (mc.gui != null && shouldCancelBossBars()) { + clearBossBars(); + } + + reloadWorldRendererIfNeeded(); + } + + @Override + public void onDisable() { + forceRendererReload = true; + reloadWorldRendererIfNeeded(); + } + + @Override + public void onTick() { + if (nullCheck() || mc.player == null || mc.level == null) { + return; + } + + useAllHooks(); + + if (shouldCancelNausea()) { + mc.player.removeEffect(MobEffects.NAUSEA); + } + + if (shouldCancelBlindness()) { + mc.player.removeEffect(MobEffects.BLINDNESS); + } + + if (shouldCancelDarkness()) { + mc.player.removeEffect(MobEffects.DARKNESS); + } + + if (shouldCancelPortalOverlay()) { + clearPortalEffect(mc.player); + } + + if (shouldCancelWeather()) { + clearWeather(mc.level); + } + + if (mc.gui != null && shouldCancelBossBars()) { + clearBossBars(); + } + + reloadWorldRendererIfNeeded(); + } + + private void useAllHooks() { + boolean overlay = + shouldCancelPortalOverlay() + || shouldCancelSpyglassOverlay() + || shouldCancelNausea() + || shouldCancelPumpkinOverlay() + || shouldCancelPowderedSnowOverlay() + || shouldCancelFireOverlay() + || shouldCancelWaterOverlay() + || shouldCancelLiquidOverlay() + || shouldCancelBlockOverlay() + || shouldCancelInWallOverlay() + || shouldCancelVignette() + || shouldCancelGuiBackground() + || shouldCancelTotemAnimation() + || shouldCancelEatingParticles() + || shouldCancelEnchantGlint(); + + boolean hud = + shouldCancelPotionIcons() + || shouldCancelBossBars() + || shouldCancelScoreboard() + || shouldCancelCrosshair() + || shouldCancelTitle() + || shouldCancelHeldItemName() + || shouldCancelObfuscation() + || shouldCancelMessageSignatureIndicator(); + + boolean world = + shouldCancelWeather() + || shouldCancelWorldBorder() + || shouldCancelBlindness() + || shouldCancelDarkness() + || shouldCancelFog() + || shouldCancelEnchantTableBook() + || shouldCancelSignText() + || shouldCancelBlockBreakOverlay() + || shouldCancelBeaconBeams() + || shouldCancelFallingBlocks() + || shouldCancelCaveCulling() + || shouldCancelMapMarkers() + || shouldCancelMapContents() + || shouldCancelFireworkExplosions() + || shouldCancelBarrierInvisibility() + || shouldCancelTextureRotations(); + + boolean entity = + shouldRenderInvisibleEntities() + || shouldCancelArmor() + || shouldCancelHurtCam() + || shouldCancelEntityFire() + || shouldCancelPlayerCollision() + || shouldCancelGlowing() + || shouldCancelMobInSpawner() + || shouldCancelDeadEntities() + || shouldCancelNametags() + || shouldDropSpawnPackets() + || shouldCancelEntityType(EntityType.FALLING_BLOCK); + + if ((overlay || hud || world || entity) && mc.gui != null && shouldCancelBossBars()) { + clearBossBars(); + } + } + + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + Packet packet = event.getPacket(); + + if (packet == null) { + return; + } + + if (explosions.getValue() && packet instanceof ClientboundExplodePacket) { + event.cancel(); + return; + } + + if (shouldCancelBossBars() && isBossBarPacket(packet)) { + event.cancel(); + + if (mc.gui != null) { + clearBossBars(); + } + + return; + } + + String packetName = packet.getClass().getSimpleName().toLowerCase(); + + if (shouldCancelTitle() && packetName.contains("title")) { + event.cancel(); + return; + } + + if (shouldCancelTotemAnimation() && isTotemPacket(packet)) { + event.cancel(); + return; + } + + if (shouldDropSpawnPackets() && isEntitySpawnPacket(packet)) { + event.cancel(); + } + } + + @Subscribe + public void onParticleAdd(ParticleEvent.Add event) { + Particle particle = event.particle; + + if (particle == null) { + return; + } + + if (shouldCancelParticleName(getParticleName(particle))) { + event.cancel(); + } + } + + @Override + public void onRender3D(Render3DEvent event) { + if (nullCheck()) { + return; + } + + ClientLevel level = mc.level; + + if (level == null) { + return; + } + + for (Entity entity : level.entitiesForRendering()) { + if (shouldCancelEntity(entity)) { + entity.remove(Entity.RemovalReason.KILLED); + continue; + } + + String type = entity.getType().toString().toLowerCase(); + + if (potions.getValue() && isPotion(type)) { + entity.remove(Entity.RemovalReason.KILLED); + } + } + } + + private String getParticleName(Particle particle) { + return particle.getClass().getSimpleName().toLowerCase() + + " " + + particle.getClass().getName().toLowerCase(); + } + + private boolean shouldCancelParticleName(String particleName) { + if (particleName == null || particleName.isBlank()) { + return false; + } + + if (elderGuardian.getValue() && particleName.contains("guardian")) { + return true; + } + + if (explosions.getValue() && isExplosionParticle(particleName)) { + return true; + } + + if (campFire.getValue() && particleName.contains("campfire")) { + return true; + } + + if ((fireworks.getValue() || shouldCancelFireworkExplosions()) && particleName.contains("firework")) { + return true; + } + + if (rainParticles.getValue() && particleName.contains("rain")) { + return true; + } + + if (smokeParticles.getValue() && particleName.contains("smoke")) { + return true; + } + + if (flameParticles.getValue() + && ( + particleName.contains("flame") + || particleName.contains("lava") + || particleName.contains("campfire") + )) { + return true; + } + + if (portalParticles.getValue() && particleName.contains("portal")) { + return true; + } + + if (critParticles.getValue() + && ( + particleName.contains("crit") + || particleName.contains("enchantedhit") + || particleName.contains("enchanted_hit") + )) { + return true; + } + + return effect.getValue() + && ( + particleName.contains("spell") + || particleName.contains("effect") + || particleName.contains("ambient") + || particleName.contains("mob") + ); + } + + private boolean isPotion(String type) { + return type.contains("potion") + || type.contains("splash_potion") + || type.contains("lingering_potion"); + } + + private boolean isExplosionParticle(String particleName) { + return particleName.contains("explosion") + || particleName.contains("hugeexplosion") + || particleName.contains("largeexplosion") + || particleName.contains("sonicboom") + || particleName.contains("sonic_boom") + || particleName.contains("sweepattack") + || particleName.contains("sweep_attack"); + } + + private boolean isBossBarPacket(Packet packet) { + String name = packet.getClass().getSimpleName().toLowerCase(); + + return name.contains("boss") + || name.contains("bossbar") + || name.contains("bossevent") + || name.contains("bosshealth"); + } + + private boolean isEntitySpawnPacket(Packet packet) { + String name = packet.getClass().getSimpleName().toLowerCase(); + + return name.contains("addentity") + || name.contains("spawnentity") + || name.contains("addmob") + || name.contains("spawnmob"); + } + + private boolean isTotemPacket(Packet packet) { + String name = packet.getClass().getSimpleName().toLowerCase(); + + if (!name.contains("entityevent")) { + return false; + } + + Byte eventId = readBytePacketValue(packet); + + return eventId != null && eventId == 35; + } + + private Byte readBytePacketValue(Packet packet) { + String[] methods = { + "getEventId", + "eventId", + "getEvent", + "event" + }; + + for (String methodName : methods) { + try { + Method method = packet.getClass().getMethod(methodName); + method.setAccessible(true); + + Object value = method.invoke(packet); + + if (value instanceof Byte b) { + return b; + } + + if (value instanceof Number number) { + return number.byteValue(); + } + } catch (Throwable ignored) { + } + } + + return null; + } + + private void clearWeather(ClientLevel level) { + level.setRainLevel(0.0f); + level.setThunderLevel(0.0f); + } + + private void clearPortalEffect(Player player) { + Class clazz = player.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + if (field.getType() != float.class) { + continue; + } + + String name = field.getName().toLowerCase(); + + if (!name.contains("portal")) { + continue; + } + + try { + field.setAccessible(true); + field.setFloat(player, 0.0f); + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } + + private static void clearBossBars() { + if (mc.gui == null) { + return; + } + + Object bossOverlay = getBossOverlay(); + + if (bossOverlay == null) { + return; + } + + callResetMethods(bossOverlay); + clearCollectionsInObject(bossOverlay); + } + + private static Object getBossOverlay() { + if (mc.gui == null) { + return null; + } + + String[] methodNames = { + "getBossOverlay", + "bossOverlay", + "getBossHealthOverlay", + "bossHealthOverlay" + }; + + for (String methodName : methodNames) { + try { + Method method = mc.gui.getClass().getMethod(methodName); + method.setAccessible(true); + + Object value = method.invoke(mc.gui); + + if (value != null) { + return value; + } + } catch (Throwable ignored) { + } + } + + Class clazz = mc.gui.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + String name = field.getName().toLowerCase(); + + if (!name.contains("boss")) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(mc.gui); + + if (value != null) { + return value; + } + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + + return null; + } + + private static void callResetMethods(Object object) { + String[] methodNames = { + "reset", + "clear", + "removeAll" + }; + + for (String methodName : methodNames) { + try { + Method method = object.getClass().getMethod(methodName); + + if (method.getParameterCount() != 0) { + continue; + } + + method.setAccessible(true); + method.invoke(object); + } catch (Throwable ignored) { + } + } + } + + private static void clearCollectionsInObject(Object object) { + Class clazz = object.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + + Object value = field.get(object); + + if (value instanceof Map map) { + map.clear(); + continue; + } + + if (value instanceof Collection collection) { + collection.clear(); + } + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } + + private void reloadWorldRendererIfNeeded() { + if (mc.levelRenderer == null) { + return; + } + + if (forceRendererReload || shouldCancelCaveCulling() || shouldCancelTextureRotations()) { + mc.levelRenderer.allChanged(); + forceRendererReload = false; + } + } + + public static boolean isEnabledModule() { + return INSTANCE != null && INSTANCE.isEnabled(); + } + + public static boolean shouldCancelPortalOverlay() { + return isEnabledModule() && INSTANCE.portal.getValue(); + } + + public static boolean shouldCancelSpyglassOverlay() { + return isEnabledModule() && INSTANCE.spyglassOverlay.getValue(); + } + + public static boolean shouldCancelNausea() { + return isEnabledModule() && INSTANCE.nausea.getValue(); + } + + public static boolean shouldCancelPumpkinOverlay() { + return isEnabledModule() && INSTANCE.pumpkinOverlay.getValue(); + } + + public static boolean shouldCancelPowderedSnowOverlay() { + return isEnabledModule() && INSTANCE.powderedSnowOverlay.getValue(); + } + + public static boolean shouldCancelFireOverlay() { + return isEnabledModule() && INSTANCE.fireOverlay.getValue(); + } + + public static boolean shouldCancelWaterOverlay() { + return isEnabledModule() && INSTANCE.waterOverlay.getValue(); + } + + public static boolean shouldCancelLiquidOverlay() { + return isEnabledModule() && INSTANCE.waterOverlay.getValue(); + } + + public static boolean shouldCancelBlockOverlay() { + return isEnabledModule() && INSTANCE.blockOverlay.getValue(); + } + + public static boolean shouldCancelInWallOverlay() { + return isEnabledModule() && INSTANCE.blockOverlay.getValue(); + } + + public static boolean shouldCancelVignette() { + return isEnabledModule() && INSTANCE.vignette.getValue(); + } + + public static boolean shouldCancelGuiBackground() { + return isEnabledModule() && INSTANCE.guiBackground.getValue(); + } + + public static boolean shouldCancelTotemAnimation() { + return isEnabledModule() && INSTANCE.totem.getValue(); + } + + public static boolean shouldCancelEatingParticles() { + return isEnabledModule() && INSTANCE.eatingParticles.getValue(); + } + + public static boolean shouldCancelEnchantGlint() { + return isEnabledModule() && INSTANCE.enchantGlint.getValue(); + } + + public static boolean shouldCancelPotionIcons() { + return isEnabledModule() && INSTANCE.potionsIcon.getValue(); + } + + public static boolean shouldCancelBossBars() { + boolean cancel = isEnabledModule() && INSTANCE.bossBars.getValue(); + + if (cancel && mc.gui != null) { + clearBossBars(); + } + + return cancel; + } + + public static boolean shouldCancelScoreboard() { + return isEnabledModule() && INSTANCE.scoreboard.getValue(); + } + + public static boolean shouldCancelCrosshair() { + return isEnabledModule() && INSTANCE.crosshair.getValue(); + } + + public static boolean shouldCancelTitle() { + return isEnabledModule() && INSTANCE.antiTitle.getValue(); + } + + public static boolean shouldCancelHeldItemName() { + return isEnabledModule() && INSTANCE.heldItemName.getValue(); + } + + public static boolean shouldCancelObfuscation() { + return isEnabledModule() && INSTANCE.obfuscation.getValue(); + } + + public static boolean shouldCancelMessageSignatureIndicator() { + return isEnabledModule() && INSTANCE.messageSignatureIndicator.getValue(); + } + + public static boolean shouldCancelWeather() { + return isEnabledModule() && INSTANCE.weather.getValue(); + } + + public static boolean shouldCancelWorldBorder() { + return isEnabledModule() && INSTANCE.worldBorder.getValue(); + } + + public static boolean shouldCancelBlindness() { + return isEnabledModule() && INSTANCE.blindness.getValue(); + } + + public static boolean shouldCancelDarkness() { + return isEnabledModule() && INSTANCE.darkness.getValue(); + } + + public static boolean shouldCancelFog() { + return isEnabledModule() && INSTANCE.fog.getValue(); + } + + public static boolean shouldCancelEnchantTableBook() { + return isEnabledModule() && INSTANCE.enchantTableBook.getValue(); + } + + public static boolean shouldCancelSignText() { + return isEnabledModule() && INSTANCE.signText.getValue(); + } + + public static boolean shouldCancelBlockBreakOverlay() { + return isEnabledModule() && INSTANCE.blockBreakOverlay.getValue(); + } + + public static boolean shouldCancelBeaconBeams() { + return isEnabledModule() && INSTANCE.beaconBeams.getValue(); + } + + public static boolean shouldCancelFallingBlocks() { + return isEnabledModule() && INSTANCE.fallingBlocks.getValue(); + } + + public static boolean shouldCancelCaveCulling() { + return isEnabledModule() && INSTANCE.caveCulling.getValue(); + } + + public static boolean shouldCancelMapMarkers() { + return isEnabledModule() && INSTANCE.mapMarkers.getValue(); + } + + public static boolean shouldCancelMapContents() { + return isEnabledModule() && INSTANCE.mapContents.getValue(); + } + + public static boolean shouldCancelFireworkExplosions() { + return isEnabledModule() && INSTANCE.fireworkExplosions.getValue(); + } + + public static boolean shouldCancelBarrierInvisibility() { + return isEnabledModule() && INSTANCE.barrierInvisibility.getValue(); + } + + public static boolean shouldCancelTextureRotations() { + return isEnabledModule() && INSTANCE.textureRotations.getValue(); + } + + public static boolean shouldRenderInvisibleEntities() { + return isEnabledModule() && INSTANCE.invisible.getValue(); + } + + public static boolean shouldCancelArmor() { + return isEnabledModule() && INSTANCE.armor.getValue(); + } + + public static boolean shouldCancelHurtCam() { + return isEnabledModule() && INSTANCE.hurtCam.getValue(); + } + + public static boolean shouldCancelEntityFire() { + return isEnabledModule() && INSTANCE.fireEntity.getValue(); + } + + public static boolean shouldCancelPlayerCollision() { + return isEnabledModule() && INSTANCE.antiPlayerCollision.getValue(); + } + + public static boolean shouldCancelGlowing() { + return isEnabledModule() && INSTANCE.glowing.getValue(); + } + + public static boolean shouldCancelMobInSpawner() { + return isEnabledModule() && INSTANCE.mobInSpawner.getValue(); + } + + public static boolean shouldCancelDeadEntities() { + return isEnabledModule() && INSTANCE.deadEntities.getValue(); + } + + public static boolean shouldCancelNametags() { + return isEnabledModule() && INSTANCE.nametags.getValue(); + } + + public static boolean shouldDropSpawnPackets() { + return isEnabledModule() && INSTANCE.dropSpawnPackets.getValue(); + } + + public static boolean shouldCancelEntity(Entity entity) { + if (!isEnabledModule() || entity == null) { + return false; + } + + if (INSTANCE.deadEntities.getValue() && !entity.isAlive()) { + return true; + } + + if (INSTANCE.fallingBlocks.getValue()) { + String type = entity.getType().toString().toLowerCase(); + + return type.contains("falling_block"); + } + + return false; + } + + public static boolean shouldCancelEntityType(EntityType type) { + if (!isEnabledModule() || type == null) { + return false; + } + + if (INSTANCE.fallingBlocks.getValue()) { + return type.toString().toLowerCase().contains("falling_block"); + } + + return false; + } + + public static void applyNoFogToFogData(Object fogData) { + if (!shouldCancelFog()) { + return; + } + + if (fogData == null) { + return; + } + + for (Field field : fogData.getClass().getDeclaredFields()) { + if (field.getType() != float.class) { + continue; + } + + String name = field.getName().toLowerCase(); + + try { + field.setAccessible(true); + + if (name.contains("start")) { + field.setFloat(fogData, 1_000_000.0f); + continue; + } + + if (name.contains("end") + || name.contains("distance") + || name.contains("sky") + || name.contains("cloud") + || name.contains("environment")) { + field.setFloat(fogData, 1_000_001.0f); + } + } catch (Throwable ignored) { + } + } + } + + @Override + public String getDisplayInfo() { + return "Active"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/PlaceAnimations.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/PlaceAnimations.java new file mode 100644 index 0000000..25d0234 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/PlaceAnimations.java @@ -0,0 +1,275 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; + +public class PlaceAnimations extends Module { + + public enum Mode { + Cancel, + Tap, + Slide, + Drop, + Spin, + Push, + Tilt, + Flip + } + + private static PlaceAnimations INSTANCE; + + public final Setting mode = mode("Mode", Mode.Tap); + public final Setting intensity = num("Intensity", 1.0, 0.1, 3.0); + public final Setting speed = num("Speed", 1.0, 0.1, 3.0); + public final Setting overrideViewModel = bool("OverrideViewModel", true); + + public PlaceAnimations() { + super("PlaceAnimations", "Changes first person placing animations", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + } + + public static boolean shouldCancelVanillaPlace(HumanoidArm arm) { + PlaceAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (module.mode.getValue() != Mode.Cancel) { + return false; + } + + if (!isMainHandArm(arm)) { + return false; + } + + return isPlaceAnimationActive(); + } + + public static boolean isViewModelOverrideActive(ItemDisplayContext displayContext) { + PlaceAnimations module = INSTANCE; + + if (module == null) { + return false; + } + + if (!module.isEnabled()) { + return false; + } + + if (!module.overrideViewModel.getValue()) { + return false; + } + + if (!isMainHandContext(displayContext)) { + return false; + } + + return isPlaceAnimationActive(); + } + + public static void applyAnimation(PoseStack poseStack, ItemDisplayContext displayContext) { + PlaceAnimations module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (poseStack == null) { + return; + } + + if (!isMainHandContext(displayContext)) { + return; + } + + if (!isPlaceAnimationActive()) { + return; + } + + Mode currentMode = module.mode.getValue(); + + if (currentMode == Mode.Cancel) { + return; + } + + module.apply(poseStack, displayContext, currentMode); + } + + public static boolean isPlaceAnimationActive() { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + if (!mc.options.keyUse.isDown()) { + return false; + } + + if (player.isUsingItem()) { + return false; + } + + ItemStack mainHand = player.getMainHandItem(); + + return isBlock(mainHand); + } + + private static boolean isBlock(ItemStack stack) { + return !stack.isEmpty() && stack.getItem() instanceof BlockItem; + } + + private void apply(PoseStack poseStack, ItemDisplayContext displayContext, Mode currentMode) { + float progress = animationProgress(280.0); + float eased = easeOut(progress); + float hand = handSign(displayContext); + float amount = intensity.getValue().floatValue(); + + switch (currentMode) { + case Tap -> { + poseStack.translate( + hand * 0.04f * amount * eased, + -0.05f * amount * eased, + -0.12f * amount * eased + ); + poseStack.mulPose(Axis.XP.rotationDegrees(-10.0f * amount * eased)); + } + + case Slide -> { + poseStack.translate( + hand * 0.22f * amount * eased, + 0.0f, + -0.10f * amount * eased + ); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * 18.0f * amount * eased)); + } + + case Drop -> { + poseStack.translate( + 0.0f, + -0.22f * amount * eased, + -0.06f * amount * eased + ); + poseStack.mulPose(Axis.XP.rotationDegrees(22.0f * amount * eased)); + } + + case Spin -> { + poseStack.translate( + hand * 0.04f * amount * eased, + -0.04f * amount * eased, + -0.08f * amount * eased + ); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * 180.0f * amount * eased)); + } + + case Push -> { + poseStack.translate( + 0.0f, + 0.0f, + -0.28f * amount * eased + ); + poseStack.scale( + 1.0f + 0.08f * amount * eased, + 1.0f + 0.08f * amount * eased, + 1.0f + 0.08f * amount * eased + ); + } + + case Tilt -> { + poseStack.translate( + hand * 0.08f * amount * eased, + -0.04f * amount * eased, + -0.10f * amount * eased + ); + poseStack.mulPose(Axis.XP.rotationDegrees(-18.0f * amount * eased)); + poseStack.mulPose(Axis.ZP.rotationDegrees(hand * 22.0f * amount * eased)); + } + + case Flip -> { + poseStack.translate( + hand * 0.06f * amount * eased, + -0.06f * amount * eased, + -0.12f * amount * eased + ); + poseStack.mulPose(Axis.XP.rotationDegrees(140.0f * amount * eased)); + poseStack.mulPose(Axis.YP.rotationDegrees(hand * 35.0f * amount * eased)); + } + + case Cancel -> { + } + } + } + + private float animationProgress(double baseDurationMs) { + double duration = Math.max(40.0, baseDurationMs / speed.getValue()); + long time = System.currentTimeMillis(); + + return (float) ((time % (long) duration) / duration); + } + + private static float easeOut(float value) { + float inverted = 1.0f - value; + + return 1.0f - inverted * inverted * inverted; + } + + private static float handSign(ItemDisplayContext displayContext) { + return displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND ? -1.0f : 1.0f; + } + + private static boolean isMainHandContext(ItemDisplayContext displayContext) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + if (player == null) { + return false; + } + + HumanoidArm mainArm = player.getMainArm(); + + if (displayContext == ItemDisplayContext.FIRST_PERSON_RIGHT_HAND) { + return mainArm == HumanoidArm.RIGHT; + } + + if (displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND) { + return mainArm == HumanoidArm.LEFT; + } + + return false; + } + + private static boolean isMainHandArm(HumanoidArm arm) { + Minecraft mc = Minecraft.getInstance(); + LocalPlayer player = mc.player; + + return player != null && arm == player.getMainArm(); + } + + @Override + public String getDisplayInfo() { + return mode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/PopChams.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/PopChams.java new file mode 100644 index 0000000..df4d9e7 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/PopChams.java @@ -0,0 +1,449 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.PopChamsRenderer; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.network.protocol.Packet; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; + +import java.awt.Color; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +public class PopChams extends Module { + public enum RenderMode { + Fill, + Wire, + Both + } + + private final Setting mode = mode("Mode", RenderMode.Both); + + private final Setting range = num("Range", 64.0, 4.0, 256.0); + private final Setting fadeTime = num("FadeTime", 1.25, 0.1, 5.0); + private final Setting self = bool("Self", true); + private final Setting throughWalls = bool("ThroughWalls", true); + + private final Setting fillColor = color("FillColor", new Color(105, 95, 255, 85)); + private final Setting wireColor = color("WireColor", new Color(255, 255, 255, 255)); + private final Setting lineWidth = num("LineWidth", 1.5F, 0.1F, 5.0F); + + private final Setting pulse = bool("Pulse", false); + private final Setting pulseMinAlpha = num("PulseMinAlpha", 45, 0, 255); + private final Setting pulseMaxAlpha = num("PulseMaxAlpha", 115, 0, 255); + private final Setting pulseSpeed = num("PulseSpeed", 1.0, 0.1, 5.0); + + private final Setting gradient = bool("Gradient", false); + private final Setting gradientColorA = color("GradientColorA", new Color(105, 95, 255, 255)); + private final Setting gradientColorB = color("GradientColorB", new Color(255, 80, 180, 255)); + private final Setting gradientSpeed = num("GradientSpeed", 0.75, 0.05, 5.0); + private final Setting gradientScale = num("GradientScale", 1.35, 0.1, 5.0); + private final Setting gradientStrength = num("GradientStrength", 1.0, 0.0, 1.0); + + private final Setting ripple = bool("Ripple", false); + private final Setting rippleColorA = color("RippleColorA", new Color(80, 180, 255, 255)); + private final Setting rippleColorB = color("RippleColorB", new Color(255, 80, 220, 255)); + private final Setting rippleSpeed = num("RippleSpeed", 1.0, 0.05, 5.0); + private final Setting rippleScale = num("RippleScale", 3.0, 0.1, 10.0); + private final Setting rippleStrength = num("RippleStrength", 1.0, 0.0, 1.0); + + private final Setting shine = bool("Shine", false); + private final Setting shineColor = color("ShineColor", new Color(255, 255, 255, 170)); + private final Setting shineSpeed = num("ShineSpeed", 1.2, 0.05, 5.0); + private final Setting shineWidth = num("ShineWidth", 0.28, 0.05, 1.0); + private final Setting shineStrength = num("ShineStrength", 0.65, 0.0, 1.0); + + private final List popChams = new ArrayList<>(); + + public PopChams() { + super("PopChams", "Renders fading player chams when someone pops a totem", Category.RENDER); + } + + @Override + public void onDisable() { + popChams.clear(); + } + + @Override + public void onTick() { + removeExpiredPopChams(); + } + + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + Packet packet = event.getPacket(); + + if (packet == null || mc.level == null || mc.player == null) { + return; + } + + if (!isTotemPopPacket(packet)) { + return; + } + + Entity entity = getPacketEntity(packet, mc.level); + + if (!(entity instanceof Player player)) { + return; + } + + if (player == mc.player && !self.getValue()) { + return; + } + + if (mc.player.distanceTo(player) > range.getValue()) { + return; + } + + addPopCham(player); + } + + @Override + public void onRender3D(Render3DEvent event) { + if (mc.player == null || mc.level == null) { + return; + } + + removeExpiredPopChams(); + + if (popChams.isEmpty()) { + return; + } + + PoseStack stack = event.getMatrix(); + + boolean drawFill = mode.getValue() == RenderMode.Fill || mode.getValue() == RenderMode.Both; + boolean drawWire = mode.getValue() == RenderMode.Wire || mode.getValue() == RenderMode.Both; + + for (PopCham popCham : popChams) { + float fade = popCham.getFade(fadeTime.getValue().floatValue()); + + if (fade <= 0.0F) { + continue; + } + + Color fill = getColor(fillColor.getValue(), fade, true); + Color wire = getColor(wireColor.getValue(), fade, false); + + PopChamsRenderer.renderPlayer( + stack, + popCham, + fill, + wire, + lineWidth.getValue(), + drawWire && wire.getAlpha() > 0, + drawFill && fill.getAlpha() > 0, + throughWalls.getValue(), + + gradient.getValue(), + gradientColorA.getValue(), + gradientColorB.getValue(), + gradientSpeed.getValue().floatValue(), + gradientScale.getValue().floatValue(), + gradientStrength.getValue().floatValue(), + + ripple.getValue(), + rippleColorA.getValue(), + rippleColorB.getValue(), + rippleSpeed.getValue().floatValue(), + rippleScale.getValue().floatValue(), + rippleStrength.getValue().floatValue(), + + shine.getValue(), + shineColor.getValue(), + shineSpeed.getValue().floatValue(), + shineWidth.getValue().floatValue(), + shineStrength.getValue().floatValue() + ); + } + } + + private void addPopCham(Player player) { + popChams.add(new PopCham( + player.getUUID(), + player.getX(), + player.getY(), + player.getZ(), + player.getYRot(), + player.getXRot(), + player.yBodyRot, + player.yHeadRot, + player.isShiftKeyDown(), + player.isSprinting(), + player.isSwimming(), + System.currentTimeMillis() + )); + } + + private void removeExpiredPopChams() { + long now = System.currentTimeMillis(); + long maxAge = Math.round(fadeTime.getValue() * 1000.0D); + + Iterator iterator = popChams.iterator(); + + while (iterator.hasNext()) { + PopCham popCham = iterator.next(); + + if (now - popCham.spawnTime() > maxAge) { + iterator.remove(); + } + } + } + + private boolean isTotemPopPacket(Packet packet) { + String packetName = packet.getClass().getSimpleName().toLowerCase(); + + if (!packetName.contains("entityevent")) { + return false; + } + + Byte eventId = getPacketEventId(packet); + + return eventId != null && eventId == 35; + } + + private Byte getPacketEventId(Packet packet) { + String[] methodNames = { + "getEventId", + "eventId", + "getEvent", + "event", + "getEventType", + "eventType" + }; + + for (String methodName : methodNames) { + try { + Method method = packet.getClass().getMethod(methodName); + method.setAccessible(true); + + Object value = method.invoke(packet); + + if (value instanceof Byte byteValue) { + return byteValue; + } + + if (value instanceof Number number) { + return number.byteValue(); + } + } catch (Throwable ignored) { + } + } + + for (Field field : packet.getClass().getDeclaredFields()) { + if (field.getType() != byte.class && field.getType() != Byte.class) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(packet); + + if (value instanceof Byte byteValue) { + return byteValue; + } + + if (value instanceof Number number) { + return number.byteValue(); + } + } catch (Throwable ignored) { + } + } + + return null; + } + + private Entity getPacketEntity(Packet packet, ClientLevel level) { + Entity entity = getPacketEntityByMethod(packet, level); + + if (entity != null) { + return entity; + } + + Integer entityId = getPacketEntityId(packet); + + if (entityId == null) { + return null; + } + + return level.getEntity(entityId); + } + + private Entity getPacketEntityByMethod(Packet packet, ClientLevel level) { + for (Method method : packet.getClass().getMethods()) { + if (!Entity.class.isAssignableFrom(method.getReturnType())) { + continue; + } + + try { + method.setAccessible(true); + + if (method.getParameterCount() == 0) { + Object value = method.invoke(packet); + + if (value instanceof Entity entity) { + return entity; + } + } + + if (method.getParameterCount() == 1 && method.getParameterTypes()[0].isAssignableFrom(level.getClass())) { + Object value = method.invoke(packet, level); + + if (value instanceof Entity entity) { + return entity; + } + } + } catch (Throwable ignored) { + } + } + + for (Method method : packet.getClass().getMethods()) { + if (!Entity.class.isAssignableFrom(method.getReturnType())) { + continue; + } + + try { + method.setAccessible(true); + + if (method.getParameterCount() == 1) { + Object value = method.invoke(packet, level); + + if (value instanceof Entity entity) { + return entity; + } + } + } catch (Throwable ignored) { + } + } + + return null; + } + + private Integer getPacketEntityId(Packet packet) { + String[] methodNames = { + "getEntityId", + "entityId", + "getId", + "id" + }; + + for (String methodName : methodNames) { + try { + Method method = packet.getClass().getMethod(methodName); + method.setAccessible(true); + + Object value = method.invoke(packet); + + if (value instanceof Number number) { + return number.intValue(); + } + } catch (Throwable ignored) { + } + } + + for (Field field : packet.getClass().getDeclaredFields()) { + if (field.getType() != int.class && field.getType() != Integer.class) { + continue; + } + + String fieldName = field.getName().toLowerCase(); + + if (fieldName.contains("event")) { + continue; + } + + try { + field.setAccessible(true); + + Object value = field.get(packet); + + if (value instanceof Number number) { + return number.intValue(); + } + } catch (Throwable ignored) { + } + } + + return null; + } + + private Color getColor(Color base, float fade, boolean applyPulse) { + int alpha = base.getAlpha(); + + if (applyPulse && pulse.getValue()) { + alpha = getPulseAlpha(alpha); + } + + alpha = Math.round(alpha * fade); + + return withAlpha(base, alpha); + } + + private int getPulseAlpha(int originalAlpha) { + int min = Math.min(pulseMinAlpha.getValue(), pulseMaxAlpha.getValue()); + int max = Math.max(pulseMinAlpha.getValue(), pulseMaxAlpha.getValue()); + + max = Math.min(max, originalAlpha); + + if (min > max) { + min = max; + } + + double time = System.currentTimeMillis() / 1000.0D; + double wave = (Math.sin(time * pulseSpeed.getValue() * Math.PI * 2.0D) + 1.0D) / 2.0D; + + return clampAlpha((int) Math.round(min + (max - min) * wave)); + } + + private Color withAlpha(Color color, int alpha) { + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + clampAlpha(alpha) + ); + } + + private int clampAlpha(int alpha) { + return Math.max(0, Math.min(255, alpha)); + } + + @Override + public String getDisplayInfo() { + return String.valueOf(popChams.size()); + } + + public record PopCham( + UUID uuid, + double x, + double y, + double z, + float yaw, + float pitch, + float bodyYaw, + float headYaw, + boolean sneaking, + boolean sprinting, + boolean swimming, + long spawnTime + ) { + public float getFade(float fadeTimeSeconds) { + float maxAge = Math.max(0.05F, fadeTimeSeconds) * 1000.0F; + float age = System.currentTimeMillis() - spawnTime; + float fade = 1.0F - (age / maxAge); + + return Math.max(0.0F, Math.min(1.0F, fade)); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/TargetESP.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/TargetESP.java new file mode 100644 index 0000000..52aec54 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/TargetESP.java @@ -0,0 +1,559 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.combat.Aura; +import me.humanbeing.nolongerhuman.features.modules.combat.Aura32k; +import me.humanbeing.nolongerhuman.features.modules.combat.AutoCrystal; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.FadeRenderUtil; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.phys.AABB; + +import java.awt.Color; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class TargetESP extends Module { + public enum RenderMode { + Fill, + Outline, + Both + } + + private static TargetESP INSTANCE; + + private static Field AUTO_CRYSTAL_TARGET_FIELD = null; + private static Field AURA_32K_TARGET_FIELD = null; + private static boolean lookedUpAutoCrystalTarget = false; + private static boolean lookedUpAura32kTarget = false; + + public final Setting autoCrystal = bool("AutoCrystal", true); + public final Setting aura = bool("Aura", true); + public final Setting aura32k = bool("Aura32k", true); + + public final Setting renderMode = mode("RenderMode", RenderMode.Both); + + public final Setting fillColor = color("FillColor", new Color(255, 255, 255, 55)); + public final Setting outlineColor = color("OutlineColor", new Color(255, 255, 255, 255)); + + public final Setting inwardGlow = bool("InwardGlow", true); + public final Setting inwardGlowColor = color("InwardGlowColor", new Color(255, 255, 255, 75)); + public final Setting inwardGlowSize = num("InwardGlowSize", 0.22f, 0.01f, 1.5f); + public final Setting inwardGlowPasses = num("InwardGlowPasses", 5, 1, 16); + + public final Setting outwardGlow = bool("OutwardGlow", true); + public final Setting outwardGlowColor = color("OutwardGlowColor", new Color(255, 255, 255, 75)); + public final Setting outwardGlowSize = num("OutwardGlowSize", 0.22f, 0.01f, 1.5f); + public final Setting outwardGlowPasses = num("OutwardGlowPasses", 5, 1, 16); + + public final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + public final Setting expand = num("Expand", 0.05, 0.0, 1.0); + + public final Setting fadeIn = bool("FadeIn", true); + public final Setting fadeInTime = num("FadeInTime", 150, 0, 2000); + public final Setting fadeOut = bool("FadeOut", true); + public final Setting fadeOutTime = num("FadeOutTime", 250, 0, 3000); + + + public final Setting hitGrow = bool("HitGrow", true); + public final Setting hitGrowAmount = num("HitGrowAmount", 0.25, 0.0, 2.0); + public final Setting hitGrowTime = num("HitGrowTime", 250, 0, 2000); + + private final FadeRenderUtil.FadeState fadeState = new FadeRenderUtil.FadeState(); + + private final Map hitGrowStartTimes = new ConcurrentHashMap<>(); + + private int targetCount = 0; + + public TargetESP() { + super("TargetESP", "Draws an ESP box around current combat targets", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + hitGrowStartTimes.clear(); + } + + @Override + public void onDisable() { + fadeState.reset(); + hitGrowStartTimes.clear(); + targetCount = 0; + } + + @Override + public void onRender3D(Render3DEvent event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + fadeState.reset(); + hitGrowStartTimes.clear(); + targetCount = 0; + return; + } + + List targets = collectTargets(); + List boxes = new ArrayList<>(); + Set activeIds = new HashSet<>(); + + PoseStack stack = event.getMatrix(); + + for (Entity target : targets) { + if (!isValidTarget(target)) { + continue; + } + + int id = target.getId(); + activeIds.add(id); + + AABB box = getTargetBox(target); + + drawGlow(stack, box); + + boxes.add(new FadeRenderUtil.FadeBox(id, box)); + } + + hitGrowStartTimes.keySet().removeIf(id -> !activeIds.contains(id)); + + targetCount = boxes.size(); + + Color fill = renderMode.getValue() == RenderMode.Outline ? null : fillColor.getValue(); + Color outline = renderMode.getValue() == RenderMode.Fill ? null : outlineColor.getValue(); + + FadeRenderUtil.renderBoxes( + stack, + fadeState, + boxes, + fill, + outline, + lineWidth.getValue(), + fadeIn.getValue(), + fadeInTime.getValue(), + fadeOut.getValue(), + fadeOutTime.getValue(), + 0.0D, + 0 + ); + } + + private List collectTargets() { + List targets = new ArrayList<>(); + Set added = new HashSet<>(); + + if (autoCrystal.getValue()) { + addTarget(targets, added, getAutoCrystalTarget()); + } + + if (aura.getValue()) { + addTarget(targets, added, getAuraTarget()); + } + + if (aura32k.getValue()) { + addTarget(targets, added, getAura32kTarget()); + } + + return targets; + } + + private void addTarget(List targets, Set added, Entity target) { + if (!isValidTarget(target)) { + return; + } + + if (added.add(target.getId())) { + targets.add(target); + } + } + + private Entity getAutoCrystalTarget() { + if (nolongerhuman.moduleManager == null) { + return null; + } + + AutoCrystal module = nolongerhuman.moduleManager.getModuleByClass(AutoCrystal.class); + + if (module == null || !module.isEnabled()) { + return null; + } + + try { + Field field = getAutoCrystalTargetField(); + + if (field == null) { + return null; + } + + Object value = field.get(module); + + return value instanceof Entity entity ? entity : null; + } catch (Exception ignored) { + return null; + } + } + + private Entity getAuraTarget() { + if (nolongerhuman.moduleManager == null) { + return null; + } + + Aura module = nolongerhuman.moduleManager.getModuleByClass(Aura.class); + + if (module == null || !module.isEnabled()) { + return null; + } + + return module.target; + } + + private Entity getAura32kTarget() { + if (nolongerhuman.moduleManager == null) { + return null; + } + + Aura32k module = nolongerhuman.moduleManager.getModuleByClass(Aura32k.class); + + if (module == null || !module.isEnabled()) { + return null; + } + + try { + Field field = getAura32kTargetField(); + + if (field == null) { + return null; + } + + Object value = field.get(module); + + return value instanceof Entity entity ? entity : null; + } catch (Exception ignored) { + return null; + } + } + + private Field getAutoCrystalTargetField() { + if (lookedUpAutoCrystalTarget) { + return AUTO_CRYSTAL_TARGET_FIELD; + } + + lookedUpAutoCrystalTarget = true; + + try { + AUTO_CRYSTAL_TARGET_FIELD = AutoCrystal.class.getDeclaredField("target"); + AUTO_CRYSTAL_TARGET_FIELD.setAccessible(true); + } catch (Exception ignored) { + AUTO_CRYSTAL_TARGET_FIELD = null; + } + + return AUTO_CRYSTAL_TARGET_FIELD; + } + + private Field getAura32kTargetField() { + if (lookedUpAura32kTarget) { + return AURA_32K_TARGET_FIELD; + } + + lookedUpAura32kTarget = true; + + try { + AURA_32K_TARGET_FIELD = Aura32k.class.getDeclaredField("target"); + AURA_32K_TARGET_FIELD.setAccessible(true); + } catch (Exception ignored) { + AURA_32K_TARGET_FIELD = null; + } + + return AURA_32K_TARGET_FIELD; + } + + private boolean isValidTarget(Entity target) { + if (target == null) { + return false; + } + + if (target == mc.player) { + return false; + } + + return target.isAlive(); + } + + private AABB getTargetBox(Entity target) { + double totalExpand = expand.getValue(); + + if (hitGrow.getValue()) { + totalExpand += getHitGrowExtra(target.getId()); + } + + return target.getBoundingBox().inflate(totalExpand); + } + + private void drawGlow(PoseStack stack, AABB box) { + if (outwardGlow.getValue()) { + drawOutwardGlow(stack, box); + } + + if (inwardGlow.getValue()) { + drawInwardGlow(stack, box); + } + } + + private void drawOutwardGlow(PoseStack stack, AABB box) { + Color color = outwardGlowColor.getValue(); + + if (color.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, outwardGlowPasses.getValue()); + double size = Math.max(0.0D, outwardGlowSize.getValue()); + + if (size <= 0.0D) { + return; + } + + for (int i = passes; i >= 1; i--) { + double progress = i / (double) passes; + double expand = size * progress; + double alphaFactor = (1.0D - progress) * 0.60D + 0.12D; + + AABB glowBox = box.inflate(expand); + + Color passFill = withAlphaMultiplier(color, alphaFactor * 0.35D); + Color passOutline = withAlphaMultiplier(color, alphaFactor); + + RenderUtil.drawBoxFilled(stack, glowBox, passFill); + RenderUtil.drawBox( + stack, + glowBox, + passOutline, + lineWidth.getValue() + (float) (i * 0.18D) + ); + } + } + + private void drawInwardGlow(PoseStack stack, AABB box) { + Color color = inwardGlowColor.getValue(); + + if (color.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, inwardGlowPasses.getValue()); + double size = Math.max(0.0D, inwardGlowSize.getValue()); + double maxInset = getMaxInset(box); + double wantedInset = Math.min(size, maxInset); + + if (wantedInset <= 0.0D) { + return; + } + + for (int i = 0; i < passes; i++) { + double progress = passes <= 1 ? 0.0D : i / (double) (passes - 1); + double inset = wantedInset * progress; + + AABB glowBox = insetBox(box, inset); + + if (glowBox == null) { + continue; + } + + double alphaFactor = (1.0D - progress) * 0.60D + 0.12D; + + Color passFill = withAlphaMultiplier(color, alphaFactor * 0.35D); + Color passOutline = withAlphaMultiplier(color, alphaFactor); + + RenderUtil.drawBoxFilled(stack, glowBox, passFill); + RenderUtil.drawBox( + stack, + glowBox, + passOutline, + lineWidth.getValue() + (float) ((passes - i) * 0.18D) + ); + } + } + + private double getMaxInset(AABB box) { + double width = box.maxX - box.minX; + double height = box.maxY - box.minY; + double depth = box.maxZ - box.minZ; + + return Math.max(0.0D, Math.min(width, Math.min(height, depth)) * 0.5D - 0.001D); + } + + private AABB insetBox(AABB box, double inset) { + double minX = box.minX + inset; + double minY = box.minY + inset; + double minZ = box.minZ + inset; + double maxX = box.maxX - inset; + double maxY = box.maxY - inset; + double maxZ = box.maxZ - inset; + + if (maxX <= minX || maxY <= minY || maxZ <= minZ) { + return null; + } + + return new AABB( + minX, + minY, + minZ, + maxX, + maxY, + maxZ + ); + } + + private void registerAuraHit(Entity entity) { + if (!hitGrow.getValue()) { + return; + } + + if (!isValidTarget(entity)) { + return; + } + + + if (entity instanceof LivingEntity) { + triggerHitGrow(entity.getId()); + } + } + + private void registerCrystalHit() { + if (!hitGrow.getValue()) { + return; + } + + + List targets = collectTargets(); + + for (Entity target : targets) { + if (!isValidTarget(target)) { + continue; + } + + if (!(target instanceof LivingEntity)) { + continue; + } + + triggerHitGrow(target.getId()); + } + } + + private void triggerHitGrow(int entityId) { + hitGrowStartTimes.put(entityId, System.currentTimeMillis()); + } + + private double getHitGrowExtra(int entityId) { + Long startTime = hitGrowStartTimes.get(entityId); + + if (startTime == null) { + return 0.0D; + } + + int growTime = Math.max(1, hitGrowTime.getValue()); + long elapsed = System.currentTimeMillis() - startTime; + + if (elapsed >= growTime) { + hitGrowStartTimes.remove(entityId); + return 0.0D; + } + + double progress = elapsed / (double) growTime; + + + double shrink = smoothStep(progress); + double growFactor = 1.0D - shrink; + + return hitGrowAmount.getValue() * growFactor; + } + + private double smoothStep(double value) { + value = clamp01(value); + + return value * value * (3.0D - 2.0D * value); + } + + private double clamp01(double value) { + return Math.max(0.0D, Math.min(1.0D, value)); + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = clamp01(multiplier); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + + public static void spawn(Entity entity) { + TargetESP module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (entity == null) { + return; + } + + module.registerAuraHit(entity); + } + + + public static void spawn(EndCrystal crystal) { + TargetESP module = INSTANCE; + + if (module == null) { + return; + } + + if (!module.isEnabled()) { + return; + } + + if (crystal == null) { + return; + } + + module.registerCrystalHit(); + } + + public static void auraHit(Entity entity) { + spawn(entity); + } + + public static void crystalHit(EndCrystal crystal) { + spawn(crystal); + } + + @Override + public String getDisplayInfo() { + return String.valueOf(targetCount); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Trajectories.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Trajectories.java new file mode 100644 index 0000000..878529a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/Trajectories.java @@ -0,0 +1,434 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.render.Layers; +import me.humanbeing.nolongerhuman.util.render.RenderUtil; +import net.minecraft.client.Camera; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.BowItem; +import net.minecraft.world.item.CrossbowItem; +import net.minecraft.world.item.ExperienceBottleItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; + +public class Trajectories extends Module { + private final Setting arrows = bool("Arrows", true); + private final Setting enderPearls = bool("EnderPearls", true); + private final Setting experienceBottles = bool("ExpBottles", true); + + private final Setting lineColor = color("LineColor", new Color(255, 255, 255, 220)); + private final Setting hitColor = color("HitColor", new Color(255, 255, 255, 80)); + private final Setting hitOutlineColor = color("HitOutline", new Color(255, 255, 255, 220)); + + private final Setting glow = bool("Glow", true); + private final Setting glowColor = color("GlowColor", new Color(255, 255, 255, 70)); + private final Setting glowSize = num("GlowSize", 0.20f, 0.01f, 1.0f); + private final Setting glowPasses = num("GlowPasses", 5, 1, 12); + + private final Setting lineWidth = num("LineWidth", 1.5f, 0.1f, 5.0f); + private final Setting maxTicks = num("MaxTicks", 200, 20, 500); + + public Trajectories() { + super("Trajectories", "Renders trajectories for arrows, pearls, and experience bottles", Category.RENDER); + } + + @Override + public void onRender3D(Render3DEvent event) { + LocalPlayer player = mc.player; + ClientLevel level = mc.level; + + if (player == null || level == null) { + return; + } + + ProjectileStack projectile = getProjectileStack(player); + + if (projectile.stack().isEmpty()) { + return; + } + + Item item = projectile.stack().getItem(); + + if (isArrowItem(item) && !player.isUsingItem()) { + return; + } + + renderTrajectory( + event.getMatrix(), + level, + player, + projectile, + item, + event.getDelta() + ); + } + + private ProjectileStack getProjectileStack(LocalPlayer player) { + ItemStack mainHand = player.getMainHandItem(); + + if (shouldRenderItem(mainHand.getItem())) { + return new ProjectileStack(mainHand, true); + } + + ItemStack offHand = player.getOffhandItem(); + + if (shouldRenderItem(offHand.getItem())) { + return new ProjectileStack(offHand, false); + } + + return new ProjectileStack(ItemStack.EMPTY, true); + } + + private boolean shouldRenderItem(Item item) { + if (arrows.getValue() && isArrowItem(item)) { + return true; + } + + if (enderPearls.getValue() && item == Items.ENDER_PEARL) { + return true; + } + + return experienceBottles.getValue() && item instanceof ExperienceBottleItem; + } + + private boolean isArrowItem(Item item) { + return item instanceof BowItem || item instanceof CrossbowItem; + } + + private void renderTrajectory( + PoseStack stack, + ClientLevel level, + LocalPlayer player, + ProjectileStack projectile, + Item item, + float tickDelta + ) { + Camera camera = mc.gameRenderer.getMainCamera(); + + float yaw = player.getYRot(); + float pitch = player.getXRot(); + + double x = Mth.lerp(tickDelta, player.xOld, player.getX()); + double y = Mth.lerp(tickDelta, player.yOld, player.getY()); + double z = Mth.lerp(tickDelta, player.zOld, player.getZ()); + + y += player.getEyeHeight() - 0.1D; + + if (projectile.mainHand()) { + x -= Mth.cos(yaw * Mth.DEG_TO_RAD) * 0.16F; + z -= Mth.sin(yaw * Mth.DEG_TO_RAD) * 0.16F; + } else { + x += Mth.cos(yaw * Mth.DEG_TO_RAD) * 0.16F; + z += Mth.sin(yaw * Mth.DEG_TO_RAD) * 0.16F; + } + + boolean arrow = isArrowItem(item); + boolean bottle = item instanceof ExperienceBottleItem; + + float baseVelocity = arrow ? 1.0F : 0.4F; + float pitchOffset = bottle ? -20.0F : 0.0F; + + double motionX = -Mth.sin(yaw * Mth.DEG_TO_RAD) + * Mth.cos(pitch * Mth.DEG_TO_RAD) + * baseVelocity; + double motionY = -Mth.sin((pitch + pitchOffset) * Mth.DEG_TO_RAD) + * baseVelocity; + double motionZ = Mth.cos(yaw * Mth.DEG_TO_RAD) + * Mth.cos(pitch * Mth.DEG_TO_RAD) + * baseVelocity; + + double length = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + + if (length <= 0.0D) { + return; + } + + motionX /= length; + motionY /= length; + motionZ /= length; + + float velocity = getProjectileVelocity(player, item); + + motionX *= velocity; + motionY *= velocity; + motionZ *= velocity; + + if (!player.onGround()) { + motionY += player.getDeltaMovement().y; + } + + float size = arrow ? 0.3F : 0.25F; + Vec3 cameraPos = camera.position(); + + boolean landed = false; + int ticks = 0; + + while (!landed && ticks < maxTicks.getValue()) { + ticks++; + + Vec3 lastPos = new Vec3(x, y, z); + + x += motionX; + y += motionY; + z += motionZ; + + Vec3 currentPos = new Vec3(x, y, z); + BlockPos blockPos = BlockPos.containing(x, y, z); + + if (level.getBlockState(blockPos).is(Blocks.WATER)) { + motionX *= 0.8D; + motionY *= 0.8D; + motionZ *= 0.8D; + } else { + motionX *= 0.99D; + motionY *= 0.99D; + motionZ *= 0.99D; + } + + motionY -= arrow ? 0.05D : 0.03D; + + HitResult hitResult = level.clip(new ClipContext( + lastPos, + currentPos, + ClipContext.Block.COLLIDER, + ClipContext.Fluid.NONE, + player + )); + + if (hitResult.getType() == HitResult.Type.BLOCK) { + landed = true; + currentPos = hitResult.getLocation(); + + if (hitResult instanceof BlockHitResult blockHitResult) { + renderHitBox(stack, blockHitResult.getBlockPos()); + } + } + + AABB projectileBox = new AABB( + x - size, + y - size, + z - size, + x + size, + y + size, + z + size + ); + + for (Entity entity : level.getEntities(player, projectileBox)) { + if (!isValidHitEntity(entity, player)) { + continue; + } + + landed = true; + renderEntityHitBox(stack, entity); + break; + } + + if (y < level.getMinY()) { + break; + } + + drawLine( + stack, + cameraPos, + lastPos, + currentPos, + lineColor.getValue(), + lineWidth.getValue() + ); + } + } + + private boolean isValidHitEntity(Entity entity, LocalPlayer player) { + return entity != player && entity.isAlive(); + } + + private float getProjectileVelocity(LocalPlayer player, Item item) { + if (item instanceof BowItem) { + return getBowPower(player) * 2.0F * 1.5F; + } + + if (item instanceof CrossbowItem) { + return 2.2F * 1.5F; + } + + if (item instanceof ExperienceBottleItem) { + return 0.5F; + } + + return 1.5F; + } + + private float getBowPower(LocalPlayer player) { + int useTicks = player.getTicksUsingItem(); + + float power = useTicks / 20.0F; + power = (power * power + power * 2.0F) / 3.0F; + + return Math.min(power, 1.0F); + } + + private void renderHitBox(PoseStack stack, BlockPos pos) { + AABB box = new AABB(pos).inflate(0.002D); + + drawInwardGlow(stack, box); + + RenderUtil.drawBoxFilled(stack, box, hitColor.getValue()); + RenderUtil.drawBox(stack, box, hitOutlineColor.getValue(), lineWidth.getValue()); + } + + private void renderEntityHitBox(PoseStack stack, Entity entity) { + AABB box = entity.getBoundingBox(); + + drawInwardGlow(stack, box); + + RenderUtil.drawBoxFilled(stack, box, hitColor.getValue()); + RenderUtil.drawBox(stack, box, hitOutlineColor.getValue(), lineWidth.getValue()); + } + + private void drawInwardGlow(PoseStack stack, AABB box) { + if (!glow.getValue()) { + return; + } + + Color color = glowColor.getValue(); + + if (color.getAlpha() <= 0) { + return; + } + + int passes = Math.max(1, glowPasses.getValue()); + double maxInset = getMaxInset(box); + double wantedInset = Math.min(glowSize.getValue(), maxInset); + + if (wantedInset <= 0.0D) { + return; + } + + for (int i = 0; i < passes; i++) { + double progress = passes <= 1 ? 0.0D : i / (double) (passes - 1); + double inset = wantedInset * progress; + + AABB glowBox = insetBox(box, inset); + + if (glowBox == null) { + continue; + } + + double alphaFactor = (1.0D - progress) * 0.55D + 0.10D; + Color passFill = withAlphaMultiplier(color, alphaFactor * 0.45D); + Color passOutline = withAlphaMultiplier(color, alphaFactor); + + RenderUtil.drawBoxFilled(stack, glowBox, passFill); + RenderUtil.drawBox(stack, glowBox, passOutline, lineWidth.getValue() + (float) ((passes - i) * 0.12D)); + } + } + + private double getMaxInset(AABB box) { + double width = box.maxX - box.minX; + double height = box.maxY - box.minY; + double depth = box.maxZ - box.minZ; + + return Math.max(0.0D, Math.min(width, Math.min(height, depth)) * 0.5D - 0.001D); + } + + private AABB insetBox(AABB box, double inset) { + double minX = box.minX + inset; + double minY = box.minY + inset; + double minZ = box.minZ + inset; + double maxX = box.maxX - inset; + double maxY = box.maxY - inset; + double maxZ = box.maxZ - inset; + + if (maxX <= minX || maxY <= minY || maxZ <= minZ) { + return null; + } + + return new AABB( + minX, + minY, + minZ, + maxX, + maxY, + maxZ + ); + } + + private Color withAlphaMultiplier(Color color, double multiplier) { + multiplier = Math.max(0.0D, Math.min(1.0D, multiplier)); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + private void drawLine( + PoseStack stack, + Vec3 camera, + Vec3 start, + Vec3 end, + Color color, + float width + ) { + BufferBuilder buffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + + float x1 = (float) (start.x - camera.x); + float y1 = (float) (start.y - camera.y); + float z1 = (float) (start.z - camera.z); + float x2 = (float) (end.x - camera.x); + float y2 = (float) (end.y - camera.y); + float z2 = (float) (end.z - camera.z); + + float nx = x2 - x1; + float ny = y2 - y1; + float nz = z2 - z1; + + buffer.addVertex(pose, x1, y1, z1) + .setColor(color.getRGB()) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + + buffer.addVertex(pose, x2, y2, z2) + .setColor(color.getRGB()) + .setNormal(pose, nx, ny, nz) + .setLineWidth(width); + + Layers.lines().draw(buffer.buildOrThrow()); + } + + @Override + public String getDisplayInfo() { + return "3"; + } + + private record ProjectileStack(ItemStack stack, boolean mainHand) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/ViewModel.java b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/ViewModel.java new file mode 100644 index 0000000..a28f7c7 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/modules/render/ViewModel.java @@ -0,0 +1,198 @@ +package me.humanbeing.nolongerhuman.features.modules.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import net.minecraft.world.item.ItemDisplayContext; + +public class ViewModel extends Module { + + public enum FovMode { + None, + Custom + } + + private static ViewModel INSTANCE; + + public final Setting fovMode = mode("FOVMode", FovMode.None); + public final Setting fov = num("FOV", 130.0, 60.0, 170.0); + + public final Setting items = bool("Items", true); + public final Setting itemFov = num("ItemFOV", 70.0, 60.0, 170.0); + + public final Setting translate = bool("Translate", false); + + public final Setting rightX = num("RightX", 0.0, -3.0, 3.0); + public final Setting rightY = num("RightY", 0.0, -3.0, 3.0); + public final Setting rightZ = num("RightZ", 0.0, -3.0, 3.0); + + public final Setting leftX = num("LeftX", 0.0, -3.0, 3.0); + public final Setting leftY = num("LeftY", 0.0, -3.0, 3.0); + public final Setting leftZ = num("LeftZ", 0.0, -3.0, 3.0); + + public final Setting scaleX = num("ScaleX", 1.0, 0.1, 3.0); + public final Setting scaleY = num("ScaleY", 1.0, 0.1, 3.0); + public final Setting scaleZ = num("ScaleZ", 1.0, 0.1, 3.0); + + public final Setting rotateX = num("RotateX", 0.0, -180.0, 180.0); + public final Setting rotateY = num("RotateY", 0.0, -180.0, 180.0); + public final Setting rotateZ = num("RotateZ", 0.0, -180.0, 180.0); + + public ViewModel() { + super("ViewModel", "Changes where items render in your hand", Category.RENDER); + INSTANCE = this; + } + + @Override + public void onEnable() { + INSTANCE = this; + } + + public static float modifyWorldFov(float originalFov) { + ViewModel viewModel = INSTANCE; + + if (viewModel == null) { + return originalFov; + } + + if (!viewModel.isEnabled()) { + return originalFov; + } + + if (viewModel.fovMode.getValue() != FovMode.Custom) { + return originalFov; + } + + return viewModel.fov.getValue().floatValue(); + } + + public static float modifyItemFov(float originalFov) { + ViewModel viewModel = INSTANCE; + + if (viewModel == null) { + return originalFov; + } + + if (!viewModel.isEnabled()) { + return originalFov; + } + + if (viewModel.fovMode.getValue() != FovMode.Custom) { + return originalFov; + } + + if (!viewModel.items.getValue()) { + return originalFov; + } + + return viewModel.itemFov.getValue().floatValue(); + } + + public static void applyItemTransform(PoseStack poseStack, ItemDisplayContext displayContext) { + ViewModel viewModel = INSTANCE; + + if (viewModel == null) { + return; + } + + if (!viewModel.isEnabled()) { + return; + } + + if (poseStack == null) { + return; + } + + if (!isFirstPersonHand(displayContext)) { + return; + } + + if (shouldLetAnimationOverride(displayContext)) { + return; + } + + viewModel.applyItemFovScale(poseStack); + viewModel.applyPerHandTranslation(poseStack, displayContext); + viewModel.applyRotation(poseStack); + viewModel.applyScale(poseStack); + } + + private static boolean shouldLetAnimationOverride(ItemDisplayContext displayContext) { + if (BreakAnimations.isViewModelOverrideActive(displayContext)) { + return true; + } + + if (AttackAnimations.isViewModelOverrideActive(displayContext)) { + return true; + } + + return PlaceAnimations.isViewModelOverrideActive(displayContext); + } + + private static boolean isFirstPersonHand(ItemDisplayContext displayContext) { + return displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND + || displayContext == ItemDisplayContext.FIRST_PERSON_RIGHT_HAND; + } + + private void applyItemFovScale(PoseStack poseStack) { + float modifiedItemFov = modifyItemFov(70.0f); + + if (items.getValue() + && fovMode.getValue() == FovMode.Custom + && modifiedItemFov > 0.0f) { + float itemFovScale = 70.0f / modifiedItemFov; + poseStack.scale(itemFovScale, itemFovScale, itemFovScale); + } + } + + private void applyPerHandTranslation(PoseStack poseStack, ItemDisplayContext displayContext) { + if (!translate.getValue()) { + return; + } + + if (displayContext == ItemDisplayContext.FIRST_PERSON_LEFT_HAND) { + poseStack.translate( + leftX.getValue(), + leftY.getValue(), + leftZ.getValue() + ); + return; + } + + if (displayContext == ItemDisplayContext.FIRST_PERSON_RIGHT_HAND) { + poseStack.translate( + rightX.getValue(), + rightY.getValue(), + rightZ.getValue() + ); + } + } + + private void applyRotation(PoseStack poseStack) { + poseStack.mulPose(Axis.XP.rotationDegrees(rotateX.getValue().floatValue())); + poseStack.mulPose(Axis.YP.rotationDegrees(rotateY.getValue().floatValue())); + poseStack.mulPose(Axis.ZP.rotationDegrees(rotateZ.getValue().floatValue())); + } + + private void applyScale(PoseStack poseStack) { + poseStack.scale( + scaleX.getValue().floatValue(), + scaleY.getValue().floatValue(), + scaleZ.getValue().floatValue() + ); + } + + @Override + public String getDisplayInfo() { + if (translate.getValue()) { + return "Hands"; + } + + if (fovMode.getValue() == FovMode.Custom && items.getValue()) { + return "World+Items"; + } + + return fovMode.getValue().name(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/readme.md b/src/main/java/me/humanbeing/nolongerhuman/features/readme.md new file mode 100644 index 0000000..d652749 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/readme.md @@ -0,0 +1 @@ +this is where modules goes diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/settings/Bind.java b/src/main/java/me/humanbeing/nolongerhuman/features/settings/Bind.java new file mode 100644 index 0000000..2f65fcf --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/settings/Bind.java @@ -0,0 +1,497 @@ +package me.humanbeing.nolongerhuman.features.settings; + +import com.google.common.base.Converter; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.mojang.blaze3d.platform.InputConstants; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.client.input.KeyEvent; +import org.lwjgl.glfw.GLFW; + +import java.lang.reflect.Field; +import java.util.Locale; + +public class Bind implements Util { + private static final int NONE = -1; + + private int key; + private Mode mode; + + public enum Mode { + Toggle, + Hold; + + public Mode next() { + return this == Toggle ? Hold : Toggle; + } + } + + public Bind(int key) { + this(key, Mode.Toggle); + } + + public Bind(int key, Mode mode) { + this.key = key; + this.mode = mode == null ? Mode.Toggle : mode; + } + + public static Bind none() { + return new Bind(NONE, Mode.Toggle); + } + + public static Bind keyboard(int key) { + return new Bind(key, Mode.Toggle); + } + + public static Bind keyboard(int key, Mode mode) { + return new Bind(key, mode); + } + + public static Bind mouse(int mouseButton) { + return new Bind(encodeMouse(mouseButton), Mode.Toggle); + } + + public static Bind mouse(int mouseButton, Mode mode) { + return new Bind(encodeMouse(mouseButton), mode); + } + + public int getKey() { + return this.key; + } + + public void setKey(int key) { + this.key = key; + } + + public Mode getMode() { + return this.mode; + } + + public void setMode(Mode mode) { + this.mode = mode == null ? Mode.Toggle : mode; + } + + public boolean isToggle() { + return this.mode == Mode.Toggle; + } + + public boolean isHold() { + return this.mode == Mode.Hold; + } + + public Bind withKey(int key) { + return new Bind(key, this.mode); + } + + public Bind withMode(Mode mode) { + return new Bind(this.key, mode); + } + + public Bind cycleMode() { + return new Bind(this.key, this.mode.next()); + } + + public boolean isEmpty() { + return this.key == NONE; + } + + public boolean isMouse() { + return this.key < NONE; + } + + public int getMouseButton() { + if (!isMouse()) { + return -1; + } + + return decodeMouse(this.key); + } + + public String getKeyName() { + if (this.isEmpty()) { + return "None"; + } + + if (this.isMouse()) { + return "Mouse " + (this.getMouseButton() + 1); + } + + return getKeyName(this.key); + } + + @Override + public String toString() { + if (this.isEmpty()) { + return "None"; + } + + return getKeyName(); + } + + public String toDisplayString() { + return getKeyName() + " [" + this.mode.name() + "]"; + } + + public JsonObject toJsonObject() { + JsonObject object = new JsonObject(); + object.addProperty("key", this.key); + object.addProperty("mode", this.mode.name()); + return object; + } + + private static int encodeMouse(int mouseButton) { + return -(mouseButton + 2); + } + + private static int decodeMouse(int encoded) { + return -encoded - 2; + } + + private static String getKeyName(int key) { + if (key < 0) { + return "None"; + } + + try { + String name = InputConstants.getKey(new KeyEvent(key, 0, 0)).getName(); + + if (!name.isBlank()) { + return cleanKeyName(name); + } + } catch (Exception ignored) { + } + + try { + String glfwName = GLFW.glfwGetKeyName(key, 0); + + if (glfwName != null && !glfwName.isBlank()) { + return glfwName.toUpperCase(Locale.ROOT); + } + } catch (Exception ignored) { + } + + String constantName = getGlfwKeyConstantName(key); + + if (constantName != null) { + return constantName; + } + + return "Key " + key; + } + + private static String cleanKeyName(String name) { + if (name.isBlank()) { + return "Unknown"; + } + + String cleaned = name; + + if (cleaned.startsWith("key.keyboard.")) { + cleaned = cleaned.substring("key.keyboard.".length()); + } else if (cleaned.startsWith("key.mouse.")) { + cleaned = cleaned.substring("key.mouse.".length()); + } else if (cleaned.startsWith("scancode.")) { + cleaned = cleaned.substring("scancode.".length()); + } + + cleaned = cleaned + .replace("left.", "Left ") + .replace("right.", "Right ") + .replace(".", " ") + .replace("_", " ") + .trim(); + + if (cleaned.length() == 1) { + return cleaned.toUpperCase(Locale.ROOT); + } + + return capitaliseWords(cleaned); + } + + private static String capitaliseWords(String input) { + if (input == null || input.isBlank()) { + return ""; + } + + String[] split = input.split(" "); + StringBuilder builder = new StringBuilder(); + + for (String part : split) { + if (part.isBlank()) { + continue; + } + + if (builder.length() > 0) { + builder.append(" "); + } + + if (part.length() == 1) { + builder.append(part.toUpperCase(Locale.ROOT)); + } else { + builder.append(Character.toUpperCase(part.charAt(0))); + builder.append(part.substring(1).toLowerCase(Locale.ROOT)); + } + } + + return builder.toString(); + } + + private static String getGlfwKeyConstantName(int key) { + try { + for (Field field : GLFW.class.getFields()) { + if (!field.getName().startsWith("GLFW_KEY_")) { + continue; + } + + if (field.getType() != int.class) { + continue; + } + + if (field.getInt(null) == key) { + return cleanGlfwKeyConstant(field.getName()); + } + } + } catch (Exception ignored) { + } + + return null; + } + + private static String cleanGlfwKeyConstant(String name) { + String cleaned = name; + + if (cleaned.startsWith("GLFW_KEY_")) { + cleaned = cleaned.substring("GLFW_KEY_".length()); + } + + cleaned = cleaned.replace("_", " "); + + return capitaliseWords(cleaned); + } + + private static int parseMouse(String value) { + String lower = value.toLowerCase(Locale.ROOT).trim(); + + if (lower.equals("leftclick") + || lower.equals("left click") + || lower.equals("mouseleft") + || lower.equals("mouse left") + || lower.equals("button1") + || lower.equals("button 1")) { + return GLFW.GLFW_MOUSE_BUTTON_LEFT; + } + + if (lower.equals("rightclick") + || lower.equals("right click") + || lower.equals("mouseright") + || lower.equals("mouse right") + || lower.equals("button2") + || lower.equals("button 2")) { + return GLFW.GLFW_MOUSE_BUTTON_RIGHT; + } + + if (lower.equals("middleclick") + || lower.equals("middle click") + || lower.equals("mousemiddle") + || lower.equals("mouse middle") + || lower.equals("button3") + || lower.equals("button 3")) { + return GLFW.GLFW_MOUSE_BUTTON_MIDDLE; + } + + if (lower.startsWith("mouse ")) { + try { + int displayedButton = Integer.parseInt(lower.substring("mouse ".length()).trim()); + + if (displayedButton <= 0) { + return -1; + } + + return displayedButton - 1; + } catch (Exception ignored) { + } + } + + if (lower.startsWith("mouse")) { + try { + int displayedButton = Integer.parseInt(lower.substring("mouse".length()).trim()); + + if (displayedButton <= 0) { + return -1; + } + + return displayedButton - 1; + } catch (Exception ignored) { + } + } + + return -1; + } + + private static int parseKeyboard(String value) { + String raw = value.trim(); + + if (raw.isEmpty()) { + return NONE; + } + + try { + int numeric = Integer.parseInt(raw); + + if (numeric >= 0 && numeric <= GLFW.GLFW_KEY_LAST) { + return numeric; + } + } catch (Exception ignored) { + } + + String normalized = raw + .toUpperCase(Locale.ROOT) + .replace("KEY.KEYBOARD.", "") + .replace("KEYBOARD.", "") + .replace("KEY.", "") + .replace("GLFW_KEY_", "") + .replace(" ", "_") + .replace("-", "_"); + + int glfwConstant = parseGlfwKeyConstant("GLFW_KEY_" + normalized); + + if (glfwConstant != NONE) { + return glfwConstant; + } + + glfwConstant = parseGlfwKeyConstant(normalized); + + if (glfwConstant != NONE) { + return glfwConstant; + } + + try { + return InputConstants.getKey(raw.toUpperCase(Locale.ROOT)).getValue(); + } catch (Exception ignored) { + } + + try { + return InputConstants.getKey("key.keyboard." + raw.toLowerCase(Locale.ROOT)).getValue(); + } catch (Exception ignored) { + } + + return NONE; + } + + private static int parseGlfwKeyConstant(String constantName) { + try { + Field field = GLFW.class.getField(constantName); + + if (field.getType() == int.class) { + int value = field.getInt(null); + + if (value >= 0 && value <= GLFW.GLFW_KEY_LAST) { + return value; + } + } + } catch (Exception ignored) { + } + + return NONE; + } + + private static Mode parseMode(String value) { + if (value == null || value.isBlank()) { + return Mode.Toggle; + } + + for (Mode mode : Mode.values()) { + if (mode.name().equalsIgnoreCase(value.trim())) { + return mode; + } + } + + return Mode.Toggle; + } + + @SuppressWarnings("unused") + public static class BindConverter extends Converter { + @Override + public JsonElement doForward(Bind bind) { + if (bind == null) { + return Bind.none().toJsonObject(); + } + + return bind.toJsonObject(); + } + + @Override + public Bind doBackward(JsonElement jsonElement) { + if (jsonElement == null || jsonElement.isJsonNull()) { + return Bind.none(); + } + + try { + if (jsonElement.isJsonObject()) { + JsonObject object = jsonElement.getAsJsonObject(); + + int key = object.has("key") && !object.get("key").isJsonNull() + ? object.get("key").getAsInt() + : NONE; + + Mode mode = object.has("mode") && !object.get("mode").isJsonNull() + ? parseMode(object.get("mode").getAsString()) + : Mode.Toggle; + + return new Bind(key, mode); + } + } catch (Throwable ignored) { + } + + String value; + + try { + value = jsonElement.getAsString(); + } catch (Throwable ignored) { + return Bind.none(); + } + + if (value == null) { + return Bind.none(); + } + + value = value.trim(); + + if (value.isEmpty() || value.equalsIgnoreCase("None")) { + return Bind.none(); + } + + Mode mode = Mode.Toggle; + + String lower = value.toLowerCase(Locale.ROOT); + + if (lower.startsWith("hold:")) { + mode = Mode.Hold; + value = value.substring("hold:".length()).trim(); + } else if (lower.startsWith("toggle:")) { + mode = Mode.Toggle; + value = value.substring("toggle:".length()).trim(); + } else if (lower.endsWith(":hold")) { + mode = Mode.Hold; + value = value.substring(0, value.length() - ":hold".length()).trim(); + } else if (lower.endsWith(":toggle")) { + mode = Mode.Toggle; + value = value.substring(0, value.length() - ":toggle".length()).trim(); + } + + int mouseButton = parseMouse(value); + + if (mouseButton >= 0 && mouseButton <= GLFW.GLFW_MOUSE_BUTTON_LAST) { + return Bind.mouse(mouseButton, mode); + } + + int keyboardKey = parseKeyboard(value); + + if (keyboardKey <= 0) { + return Bind.none().withMode(mode); + } + + return Bind.keyboard(keyboardKey, mode); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/settings/EnumConverter.java b/src/main/java/me/humanbeing/nolongerhuman/features/settings/EnumConverter.java new file mode 100644 index 0000000..e2477b9 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/settings/EnumConverter.java @@ -0,0 +1,49 @@ +package me.humanbeing.nolongerhuman.features.settings; + +import com.google.common.base.Converter; +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; + +@SuppressWarnings("unchecked") +public class EnumConverter> extends Converter { + private final Class clazz; + + public EnumConverter(Class clazz) { + this.clazz = clazz; + } + + public static > int currentEnum(T clazz) { + for (int i = 0; i < clazz.getDeclaringClass().getEnumConstants().length; ++i) { + T e = (T) clazz.getDeclaringClass().getEnumConstants()[i]; + if (!e.name().equalsIgnoreCase(clazz.name())) continue; + return i; + } + return -1; + } + + public static > T increaseEnum(T clazz) { + int index = EnumConverter.currentEnum(clazz); + for (int i = 0; i < clazz.getDeclaringClass().getEnumConstants().length; ++i) { + T e = (T) clazz.getDeclaringClass().getEnumConstants()[i]; + if (i != index + 1) continue; + return e; + } + return (T) clazz.getDeclaringClass().getEnumConstants()[0]; + } + + public static > String getProperName(T clazz) { + return Character.toUpperCase(clazz.name().charAt(0)) + clazz.name().toLowerCase().substring(1); + } + + public JsonElement doForward(Enum anEnum) { + return new JsonPrimitive(anEnum.toString()); + } + + public T doBackward(JsonElement jsonElement) { + try { + return Enum.valueOf(this.clazz, jsonElement.getAsString()); + } catch (IllegalArgumentException e) { + return null; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/settings/Setting.java b/src/main/java/me/humanbeing/nolongerhuman/features/settings/Setting.java new file mode 100644 index 0000000..b71392e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/settings/Setting.java @@ -0,0 +1,272 @@ +package me.humanbeing.nolongerhuman.features.settings; + +import me.humanbeing.nolongerhuman.event.impl.ClientEvent; +import me.humanbeing.nolongerhuman.features.Feature; +import org.joml.Vector2f; + +import java.util.Objects; +import java.util.function.Predicate; + +import static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +public class Setting { + private final String name; + private final T defaultValue; + private T value; + private T plannedValue; + private T min; + private T max; + private boolean hasRestriction; + private Predicate visibility; + private String description; + private Feature feature; + + public Setting(String name, T defaultValue) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.plannedValue = defaultValue; + this.description = ""; + } + + public Setting(String name, T defaultValue, String description) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.plannedValue = defaultValue; + this.description = description; + } + + public Setting(String name, T defaultValue, T min, T max, String description) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.min = min; + this.max = max; + this.plannedValue = defaultValue; + this.description = description; + this.hasRestriction = true; + } + + public Setting(String name, T defaultValue, T min, T max) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.min = min; + this.max = max; + this.plannedValue = defaultValue; + this.description = ""; + this.hasRestriction = true; + } + + public Setting(String name, T defaultValue, T min, T max, Predicate visibility, String description) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.min = min; + this.max = max; + this.plannedValue = defaultValue; + this.visibility = visibility; + this.description = description; + this.hasRestriction = true; + } + + public Setting(String name, T defaultValue, T min, T max, Predicate visibility) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.min = min; + this.max = max; + this.plannedValue = defaultValue; + this.visibility = visibility; + this.description = ""; + this.hasRestriction = true; + } + + public Setting(String name, T defaultValue, Predicate visibility) { + this.name = name; + this.defaultValue = defaultValue; + this.value = defaultValue; + this.visibility = visibility; + this.plannedValue = defaultValue; + } + + public String getName() { + return this.name; + } + + public T getValue() { + return this.value; + } + + public void setValue(T value) { + this.setPlannedValue(value); + if (this.hasRestriction) { + if (((Number) this.min).floatValue() > ((Number) value).floatValue()) { + this.setPlannedValue(this.min); + } + if (((Number) this.max).floatValue() < ((Number) value).floatValue()) { + this.setPlannedValue(this.max); + } + } + ClientEvent event = new ClientEvent(this); + EVENT_BUS.post(event); + if (!event.isCancelled()) { + this.value = this.plannedValue; + } else { + this.plannedValue = this.value; + } + } + + public void reset() { + setValue(getDefaultValue()); + } + + public T getPlannedValue() { + return this.plannedValue; + } + + public void setPlannedValue(T value) { + this.plannedValue = value; + } + + public T getMin() { + return this.min; + } + + public void setMin(T min) { + this.min = min; + } + + public T getMax() { + return this.max; + } + + public void setMax(T max) { + this.max = max; + } + + public void setValueNoEvent(T value) { + this.setPlannedValue(value); + if (this.hasRestriction) { + if (((Number) this.min).floatValue() > ((Number) value).floatValue()) { + this.setPlannedValue(this.min); + } + if (((Number) this.max).floatValue() < ((Number) value).floatValue()) { + this.setPlannedValue(this.max); + } + } + this.value = this.plannedValue; + } + + public Feature getFeature() { + return this.feature; + } + + public void setFeature(Feature feature) { + this.feature = feature; + } + + public int getEnum(String input) { + for (int i = 0; i < this.value.getClass().getEnumConstants().length; ++i) { + Enum e = (Enum) this.value.getClass().getEnumConstants()[i]; + if (!e.name().equalsIgnoreCase(input)) continue; + return i; + } + return -1; + } + + @SuppressWarnings("unchecked") + public void setEnumValue(String value) { + for (Enum e : ((Enum) this.value).getClass().getEnumConstants()) { + if (!e.name().equalsIgnoreCase(value)) continue; + this.value = (T) e; + } + } + + public String currentEnumName() { + return EnumConverter.getProperName((Enum) this.value); + } + + public int currentEnum() { + return EnumConverter.currentEnum((Enum) this.value); + } + + @SuppressWarnings("unchecked") + public void increaseEnum() { + this.plannedValue = (T) EnumConverter.increaseEnum((Enum) this.value); + ClientEvent event = new ClientEvent(this); + EVENT_BUS.post(event); + if (!event.isCancelled()) { + this.value = this.plannedValue; + } else { + this.plannedValue = this.value; + } + } + + @SuppressWarnings("unchecked") + public void increaseEnumNoEvent() { + this.value = (T) EnumConverter.increaseEnum((Enum) this.value); + } + + public String getType() { + if (this.isEnumSetting()) { + return "Enum"; + } + if (this.isColorSetting()) { + return "Color"; + } + if (this.isVec2fSetting()) { + return "Pos"; + } + return this.getClassName(this.defaultValue); + } + + public String getClassName(K value) { + return value.getClass().getSimpleName(); + } + + public String getDescription() { + return Objects.requireNonNullElse(this.description, ""); + } + + public boolean isNumberSetting() { + return this.value instanceof Number; + } + + public boolean isEnumSetting() { + return this.value instanceof Enum; + } + + public boolean isStringSetting() { + return this.value instanceof String; + } + + public boolean isColorSetting() { + return this.value instanceof java.awt.Color; + } + + public boolean isVec2fSetting() { + return this.value instanceof Vector2f; + } + + public T getDefaultValue() { + return this.defaultValue; + } + + public String getValueAsString() { + return this.value.toString(); + } + + public boolean hasRestriction() { + return this.hasRestriction; + } + + public void setVisibility(Predicate visibility) { + this.visibility = visibility; + } + + public boolean isVisible() { + return this.visibility == null || this.visibility.test(this.getValue()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/features/settings/SettingFactory.java b/src/main/java/me/humanbeing/nolongerhuman/features/settings/SettingFactory.java new file mode 100644 index 0000000..cc2724c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/features/settings/SettingFactory.java @@ -0,0 +1,46 @@ +package me.humanbeing.nolongerhuman.features.settings; + +import org.joml.Vector2f; + +import java.awt.*; + +public interface SettingFactory { + > T register(T setting); + + default Setting bool(String name, boolean value) { + return register(new Setting<>(name, value)); + } + + default Setting num(String name, T value, T min, T max) { + return register(new Setting<>(name, value, min, max)); + } + + default Setting str(String name, String value) { + return register(new Setting<>(name, value)); + } + + default > Setting mode(String name, T value) { + return register(new Setting<>(name, value)); + } + + default Setting key(String name, Bind bind) { + return register(new Setting<>(name, bind)); + } + + default Setting color(String name, Color value) { + return register(new Setting<>(name, value)); + } + + default Setting color(String name, int r, int g, int b, int a) { + return register(new Setting<>(name, new Color(r, g, b, a))); + } + + default Setting vec2f(String name, Vector2f value) { + return register(new Setting<>(name, value)); + } + + default Setting vec2f(String name, float x, float y) { + return register(new Setting<>(name, new Vector2f(x, y))); + } + +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/BoostManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/BoostManager.java new file mode 100644 index 0000000..70d51ec --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/BoostManager.java @@ -0,0 +1,134 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.util.models.Timer; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +import net.minecraft.world.phys.Vec3; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +public final class BoostManager implements Util { + + private static BoostManager INSTANCE; + + private final Timer boostTimer = new Timer(); + + private double horizontalBoost; + private double verticalBoost; + private Vec3 boostVelocity = Vec3.ZERO; + + private BoostManager() { + EVENT_BUS.register(this); + reset(); + } + + public static BoostManager get() { + if (INSTANCE == null) { + INSTANCE = new BoostManager(); + } + + return INSTANCE; + } + + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + LocalPlayer player = mc.player; + if (player == null) return; + + Packet packet = event.getPacket(); + if (!(packet instanceof ClientboundSetEntityMotionPacket velocityPacket)) return; + if (velocityPacket.getId() != player.getId()) return; + + Vec3 velocity = readVelocity(velocityPacket); + registerBoost(velocity); + } + + public void registerBoost(Vec3 velocity) { + this.boostVelocity = velocity; + this.horizontalBoost = Math.hypot(velocity.x, velocity.z); + this.verticalBoost = velocity.y; + this.boostTimer.reset(); + } + + public boolean hasBoost(double minHorizontalBoost) { + return !boostTimer.passedMs(1000L) && horizontalBoost >= minHorizontalBoost; + } + + public boolean canDoLongjump() { + return hasBoost(0.5); + } + + public void consume() { + reset(); + } + + public void reset() { + this.horizontalBoost = 0.0; + this.verticalBoost = 0.0; + this.boostVelocity = Vec3.ZERO; + this.boostTimer.setMs(Long.MIN_VALUE / 2L); + } + + public double getHorizontalBoost() { + return horizontalBoost; + } + + public double getVerticalBoost() { + return verticalBoost; + } + + public Vec3 getBoostVelocity() { + return boostVelocity; + } + + private Vec3 readVelocity(ClientboundSetEntityMotionPacket packet) { + + int x = readPacketInt(packet, + "getXa", "getVelocityX", "getX", "x", "xa", "velocityX", "field_12377"); + + int y = readPacketInt(packet, + "getYa", "getVelocityY", "getY", "y", "ya", "velocityY", "field_12375"); + + int z = readPacketInt(packet, + "getZa", "getVelocityZ", "getZ", "z", "za", "velocityZ", "field_12376"); + + return new Vec3(x / 8000.0, y / 8000.0, z / 8000.0); + } + + private int readPacketInt(Object object, String... names) { + Class clazz = object.getClass(); + + for (String name : names) { + try { + Method method = clazz.getDeclaredMethod(name); + method.setAccessible(true); + + Object value = method.invoke(object); + if (value instanceof Number number) { + return number.intValue(); + } + } catch (Throwable ignored) { + } + } + + for (String name : names) { + try { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + + Object value = field.get(object); + if (value instanceof Number number) { + return number.intValue(); + } + } catch (Throwable ignored) { + } + } + + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/ColorManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/ColorManager.java new file mode 100644 index 0000000..bb5a9ea --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/ColorManager.java @@ -0,0 +1,61 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.features.modules.client.ClickGuiModule; + +import java.awt.Color; + +public class ColorManager { + private Color color = new Color(105, 95, 255, 230); + + public void init() { + ClickGuiModule clickGui = ClickGuiModule.getInstance(); + + if (clickGui != null && clickGui.color != null && clickGui.color.getValue() != null) { + setColor(clickGui.color.getValue()); + } + } + + public Color getColor() { + return this.color; + } + + public void setColor(Color color) { + if (color == null) { + return; + } + + this.color = color; + } + + public int getColorAsInt() { + return this.color.getRGB(); + } + + public int getColorAsIntFullAlpha() { + return new Color( + this.color.getRed(), + this.color.getGreen(), + this.color.getBlue(), + 255 + ).getRGB(); + } + + public int getColorWithAlpha(float offset, int alpha) { + return getColorWithAlpha(alpha); + } + + public int getColorWithAlpha(int alpha) { + int clampedAlpha = clampAlpha(alpha); + + return new Color( + this.color.getRed(), + this.color.getGreen(), + this.color.getBlue(), + clampedAlpha + ).getRGB(); + } + + private int clampAlpha(int alpha) { + return Math.max(0, Math.min(255, alpha)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/CommandManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/CommandManager.java new file mode 100644 index 0000000..f7b013a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/CommandManager.java @@ -0,0 +1,139 @@ +package me.humanbeing.nolongerhuman.manager; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.commands.Command; +import me.humanbeing.nolongerhuman.features.commands.impl.BindCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.ConfigCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.DrawnCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.FriendCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.HelpCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.LoadVisualsCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.PrefixCommand; +import me.humanbeing.nolongerhuman.features.commands.impl.ToggleCommand; +import me.humanbeing.nolongerhuman.util.traits.Jsonable; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static com.mojang.brigadier.Command.SINGLE_SUCCESS; +import static me.humanbeing.nolongerhuman.features.commands.Command.SINGLE_FAILURE; +import static me.humanbeing.nolongerhuman.features.commands.MessageIdentifiers.GENERAL; + +public class CommandManager extends Feature implements Jsonable { + private static final Logger LOGGER = LogManager.getLogger("Commands"); + + private final CommandDispatcher dispatcher = new CommandDispatcher<>(); + private final Map commandAliasMap = new LinkedHashMap<>(); + private final List commandList = new LinkedList<>(); + + private String commandPrefix = "."; + + public CommandManager() { + super("Commands"); + } + + public void init() { + register(new BindCommand()); + register(new ConfigCommand()); + register(new DrawnCommand()); + register(new FriendCommand()); + register(new HelpCommand()); + register(new LoadVisualsCommand()); + register(new PrefixCommand()); + register(new ToggleCommand()); + + LOGGER.info("Registered {} commands", commandList.size()); + + nolongerhuman.configManager.addConfig(this); + } + + public void onChatSent(String message) { + try { + int result = dispatcher.execute(message.substring(commandPrefix.length()).trim(), this); + + if (result == SINGLE_SUCCESS) { + Command.sendMessage("{green} Command executed successfully", GENERAL); + } else if (result == SINGLE_FAILURE) { + Command.sendMessage("{red} Failed to execute command", GENERAL); + } + } catch (CommandSyntaxException e) { + LOGGER.error("Failed to execute command", e); + Command.sendMessage("{red} %s", GENERAL, e.getMessage()); + } + } + + public void register(Command command) { + commandList.add(command); + + for (String alias : command.getAliases()) { + commandAliasMap.put(alias, command); + + LiteralArgumentBuilder builder = Command.literal(alias); + command.createArgumentBuilder(builder); + + dispatcher.register(builder); + } + } + + public void setCommandPrefix(String commandPrefix) { + this.commandPrefix = commandPrefix; + } + + public String getCommandPrefix() { + return commandPrefix; + } + + public Command getCommand(String alias) { + return commandAliasMap.get(alias); + } + + public Set getCommandAliases() { + return commandAliasMap.keySet(); + } + + public List getCommands() { + return commandList; + } + + public CommandDispatcher getDispatcher() { + return dispatcher; + } + + @Override + public JsonElement toJson() { + JsonObject object = new JsonObject(); + + object.addProperty("prefix", commandPrefix); + + return object; + } + + @Override + public void fromJson(JsonElement element) { + if (element == null || !element.isJsonObject()) { + return; + } + + JsonObject object = element.getAsJsonObject(); + + if (object.has("prefix")) { + setCommandPrefix(object.get("prefix").getAsString()); + } + } + + @Override + public String getFileName() { + return "commands.json"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/ConfigManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/ConfigManager.java new file mode 100644 index 0000000..107ae92 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/ConfigManager.java @@ -0,0 +1,915 @@ +package me.humanbeing.nolongerhuman.manager; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.settings.Bind; +import me.humanbeing.nolongerhuman.features.settings.EnumConverter; +import me.humanbeing.nolongerhuman.features.settings.Setting; +import me.humanbeing.nolongerhuman.util.traits.Jsonable; +import net.fabricmc.loader.api.FabricLoader; +import org.joml.Vector2f; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.awt.Color; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; + +public class ConfigManager { + + private static final Logger LOGGER = LoggerFactory.getLogger("ConfigManager"); + + private static final Path NOLONGERHUMAN_PATH = + FabricLoader.getInstance().getGameDir().resolve("nolongerhuman"); + + private static final Path CONFIGS_PATH = + NOLONGERHUMAN_PATH.resolve("configs"); + + private static final Path NAMED_CONFIGS_PATH = + CONFIGS_PATH.resolve("named"); + + private static final Gson GSON = + new GsonBuilder().setPrettyPrinting().create(); + + private final List jsonables = new LinkedList<>(); + + public void addConfig(Jsonable jsonable) { + jsonables.add(jsonable); + } + + public void load() { + mkdirs(); + + for (Jsonable jsonable : jsonables) { + try { + Path filePath = CONFIGS_PATH.resolve(jsonable.getFileName()); + + if (!Files.exists(filePath)) { + LOGGER.warn("Config file does not exist: {}", filePath); + continue; + } + + String read = Files.readString(filePath); + jsonable.fromJson(JsonParser.parseString(read)); + } catch (Throwable e) { + LOGGER.error("Failed to load config: {}", jsonable.getFileName(), e); + } + } + } + + public void save() { + mkdirs(); + + for (Jsonable jsonable : jsonables) { + try { + JsonElement json = jsonable.toJson(); + + Files.writeString( + CONFIGS_PATH.resolve(jsonable.getFileName()), + GSON.toJson(json) + ); + } catch (Throwable e) { + LOGGER.error("Failed to write config file: {}", jsonable.getFileName(), e); + } + } + } + + public boolean save(String name) { + mkdirs(); + + String safeName = sanitizeName(name); + + if (safeName.isEmpty()) { + return false; + } + + JsonObject root = new JsonObject(); + + for (Jsonable jsonable : jsonables) { + try { + root.add(jsonable.getFileName(), jsonable.toJson()); + } catch (Throwable e) { + LOGGER.error("Failed to serialize config part: {}", jsonable.getFileName(), e); + return false; + } + } + + try { + Files.writeString(getNamedConfigPath(safeName), GSON.toJson(root)); + return true; + } catch (Throwable e) { + LOGGER.error("Failed to save named config: {}", safeName, e); + return false; + } + } + + public boolean load(String name) { + mkdirs(); + + String safeName = sanitizeName(name); + + if (safeName.isEmpty()) { + return false; + } + + Path filePath = getNamedConfigPath(safeName); + + if (!Files.exists(filePath)) { + LOGGER.warn("Named config does not exist: {}", filePath); + return false; + } + + try { + JsonElement element = JsonParser.parseString(Files.readString(filePath)); + + if (element == null || !element.isJsonObject()) { + LOGGER.error("Named config is not a valid json object: {}", filePath); + return false; + } + + JsonObject root = element.getAsJsonObject(); + + for (Jsonable jsonable : jsonables) { + try { + String fileName = jsonable.getFileName(); + + if (!root.has(fileName)) { + LOGGER.warn("Named config {} does not contain {}", safeName, fileName); + continue; + } + + jsonable.fromJson(root.get(fileName)); + } catch (Throwable e) { + LOGGER.error("Failed to load config part: {}", jsonable.getFileName(), e); + } + } + + return true; + } catch (Throwable e) { + LOGGER.error("Failed to load named config: {}", safeName, e); + return false; + } + } + + + public boolean loadVisuals(String name) { + mkdirs(); + + String safeName = sanitizeName(name); + + if (safeName.isEmpty()) { + return false; + } + + Path filePath = getNamedConfigPath(safeName); + + if (!Files.exists(filePath)) { + LOGGER.warn("Named config does not exist: {}", filePath); + return false; + } + + try { + JsonElement element = JsonParser.parseString(Files.readString(filePath)); + + if (element == null || !element.isJsonObject()) { + LOGGER.error("Named config is not a valid json object: {}", filePath); + return false; + } + + JsonObject root = element.getAsJsonObject(); + + for (Module module : nolongerhuman.moduleManager.getModules()) { + JsonObject moduleObject = findModuleObject(root, module); + + if (moduleObject == null) { + continue; + } + + boolean visualModule = isVisualModule(module); + + if (visualModule) { + loadVisualModuleState(module, moduleObject); + } + + for (Setting setting : module.getSettings()) { + if (!shouldLoadSettingAsVisual(setting, visualModule)) { + continue; + } + + JsonElement settingElement = findSettingElement(moduleObject, setting.getName()); + + if (settingElement == null) { + continue; + } + + setValueFromJson(module, setting, settingElement); + } + } + + return true; + } catch (Throwable e) { + LOGGER.error("Failed to load visuals from named config: {}", safeName, e); + return false; + } + } + + public boolean delete(String name) { + mkdirs(); + + String safeName = sanitizeName(name); + + if (safeName.isEmpty()) { + return false; + } + + Path filePath = getNamedConfigPath(safeName); + + if (!Files.exists(filePath)) { + return false; + } + + try { + Files.delete(filePath); + return true; + } catch (Throwable e) { + LOGGER.error("Failed to delete named config: {}", safeName, e); + return false; + } + } + + public boolean exists(String name) { + String safeName = sanitizeName(name); + + if (safeName.isEmpty()) { + return false; + } + + return Files.exists(getNamedConfigPath(safeName)); + } + + public List getNamedConfigs() { + mkdirs(); + + try { + if (!Files.exists(NAMED_CONFIGS_PATH)) { + return List.of(); + } + + try (var stream = Files.list(NAMED_CONFIGS_PATH)) { + return stream + .filter(Files::isRegularFile) + .map(path -> path.getFileName().toString()) + .filter(fileName -> fileName.endsWith(".json")) + .map(fileName -> fileName.substring(0, fileName.length() - ".json".length())) + .sorted(String::compareToIgnoreCase) + .toList(); + } + } catch (Throwable e) { + LOGGER.error("Failed to list named configs", e); + return List.of(); + } + } + + public Path getNamedConfigPath(String name) { + String safeName = sanitizeName(name); + return NAMED_CONFIGS_PATH.resolve(safeName + ".json"); + } + + public String sanitizeName(String name) { + if (name == null) { + return ""; + } + + String trimmed = name.trim().toLowerCase(Locale.ROOT); + + if (trimmed.endsWith(".json")) { + trimmed = trimmed.substring(0, trimmed.length() - ".json".length()); + } + + String sanitized = trimmed.replaceAll("[^a-z0-9_\\-]", "_"); + + while (sanitized.contains("__")) { + sanitized = sanitized.replace("__", "_"); + } + + if (sanitized.startsWith("_")) { + sanitized = sanitized.substring(1); + } + + if (sanitized.endsWith("_")) { + sanitized = sanitized.substring(0, sanitized.length() - 1); + } + + return sanitized; + } + + private void mkdirs() { + try { + Files.createDirectories(CONFIGS_PATH); + Files.createDirectories(NAMED_CONFIGS_PATH); + } catch (Throwable e) { + throw new RuntimeException("Failed to create config directory!", e); + } + } + + + private boolean isVisualModule(Module module) { + if (module == null || module.getCategory() == null) { + return false; + } + + String categoryName = ""; + + try { + categoryName = module.getCategory().getName(); + } catch (Throwable ignored) { + categoryName = String.valueOf(module.getCategory()); + } + + categoryName = categoryName + .toLowerCase(Locale.ROOT) + .replace("_", "") + .replace("-", "") + .replace(" ", ""); + + return categoryName.contains("client") + || categoryName.contains("render") + || categoryName.contains("visual") + || categoryName.contains("hud"); + } + + + private boolean shouldLoadSettingAsVisual(Setting setting, boolean visualModule) { + if (setting == null) { + return false; + } + + if (visualModule) { + return true; + } + + return isColorSetting(setting); + } + + private boolean isColorSetting(Setting setting) { + if (setting == null) { + return false; + } + + try { + if (setting.isColorSetting()) { + return true; + } + } catch (Throwable ignored) { + } + + try { + if ("Color".equalsIgnoreCase(setting.getType())) { + return true; + } + } catch (Throwable ignored) { + } + + try { + return setting.getValue() instanceof Color; + } catch (Throwable ignored) { + return false; + } + } + + private void loadVisualModuleState(Module module, JsonObject moduleObject) { + JsonElement enabledElement = findSettingElement(moduleObject, "Enabled"); + + if (enabledElement != null) { + Boolean enabled = getBoolean(enabledElement); + + if (enabled != null) { + setModuleEnabled(module, enabled); + } + } + + JsonElement drawnElement = findSettingElement(moduleObject, "Drawn"); + + if (drawnElement != null) { + Boolean drawn = getBoolean(drawnElement); + + if (drawn != null) { + setModuleDrawn(module, drawn); + } + } + + JsonElement displayNameElement = findSettingElement(moduleObject, "DisplayName"); + + if (displayNameElement != null && displayNameElement.isJsonPrimitive()) { + setModuleDisplayName(module, displayNameElement.getAsString()); + } + + JsonElement keybindElement = findSettingElement(moduleObject, "Keybind"); + + if (keybindElement != null) { + setModuleKeybind(module, keybindElement); + } + } + + private Boolean getBoolean(JsonElement element) { + if (element == null || element.isJsonNull()) { + return null; + } + + try { + if (element.isJsonPrimitive()) { + return element.getAsBoolean(); + } + } catch (Throwable ignored) { + } + + try { + return Boolean.parseBoolean(element.getAsString()); + } catch (Throwable ignored) { + return null; + } + } + + private void setModuleEnabled(Module module, boolean enabled) { + if (tryInvoke(module, "setEnabled", enabled)) { + return; + } + + if (tryInvoke(module, "setToggled", enabled)) { + return; + } + + try { + if (module.isEnabled() != enabled) { + if (enabled) { + if (tryInvokeNoArgs(module, "enable")) { + return; + } + } else { + if (tryInvokeNoArgs(module, "disable")) { + return; + } + } + + tryInvokeNoArgs(module, "toggle"); + } + } catch (Throwable ignored) { + } + } + + private void setModuleDrawn(Module module, boolean drawn) { + if (tryInvoke(module, "setDrawn", drawn)) { + return; + } + + if (tryInvoke(module, "setHidden", !drawn)) { + return; + } + + if (tryInvoke(module, "setVisible", drawn)) { + return; + } + } + + private void setModuleDisplayName(Module module, String displayName) { + if (displayName == null) { + return; + } + + tryInvoke(module, "setDisplayName", displayName); + tryInvoke(module, "setName", displayName); + } + + private void setModuleKeybind(Module module, JsonElement keybindElement) { + Object bindObject = tryGet(module, "getBind", "getKeybind", "getKeyBind", "getKey"); + + if (bindObject == null) { + return; + } + + int key = Integer.MIN_VALUE; + String mode = null; + + try { + if (keybindElement.isJsonObject()) { + JsonObject object = keybindElement.getAsJsonObject(); + + if (object.has("key")) { + key = object.get("key").getAsInt(); + } + + if (object.has("mode")) { + mode = object.get("mode").getAsString(); + } + } else if (keybindElement.isJsonPrimitive()) { + key = keybindElement.getAsInt(); + } + } catch (Throwable ignored) { + } + + if (key != Integer.MIN_VALUE) { + tryInvoke(bindObject, "setKey", key); + tryInvoke(bindObject, "setKeyCode", key); + tryInvoke(bindObject, "setCode", key); + } + + if (mode != null) { + setBindMode(bindObject, mode); + } + } + + private void setBindMode(Object bindObject, String mode) { + Object currentMode = tryGet(bindObject, "getMode", "getBindMode"); + + if (currentMode instanceof Enum currentEnum) { + Class enumClass = currentEnum.getDeclaringClass(); + + for (Object constant : enumClass.getEnumConstants()) { + if (constant.toString().equalsIgnoreCase(mode)) { + if (tryInvoke(bindObject, "setMode", constant)) { + return; + } + + if (tryInvoke(bindObject, "setBindMode", constant)) { + return; + } + } + } + } + + tryInvoke(bindObject, "setMode", mode); + tryInvoke(bindObject, "setBindMode", mode); + } + + private Object tryGet(Object object, String... methodNames) { + if (object == null) { + return null; + } + + for (String methodName : methodNames) { + try { + Method method = object.getClass().getMethod(methodName); + method.setAccessible(true); + return method.invoke(object); + } catch (Throwable ignored) { + } + } + + return null; + } + + private boolean tryInvoke(Object object, String methodName, Object argument) { + if (object == null) { + return false; + } + + for (Method method : object.getClass().getMethods()) { + if (!method.getName().equals(methodName)) { + continue; + } + + if (method.getParameterCount() != 1) { + continue; + } + + try { + method.setAccessible(true); + method.invoke(object, argument); + return true; + } catch (Throwable ignored) { + } + } + + return false; + } + + private boolean tryInvokeNoArgs(Object object, String methodName) { + if (object == null) { + return false; + } + + try { + Method method = object.getClass().getMethod(methodName); + method.setAccessible(true); + method.invoke(object); + return true; + } catch (Throwable ignored) { + return false; + } + } + + private JsonObject findModuleObject(JsonObject root, Module module) { + String moduleName = module.getName(); + String displayName = module.getDisplayName(); + + JsonObject direct = findObjectByKey(root, moduleName); + + if (direct != null) { + return direct; + } + + if (displayName != null && !displayName.equalsIgnoreCase(moduleName)) { + direct = findObjectByKey(root, displayName); + + if (direct != null) { + return direct; + } + } + + return findObjectContainingModuleName(root, moduleName, displayName); + } + + private JsonObject findObjectByKey(JsonObject object, String wantedKey) { + if (object == null || wantedKey == null) { + return null; + } + + for (String key : object.keySet()) { + JsonElement value = object.get(key); + + if (key.equalsIgnoreCase(wantedKey) && value != null && value.isJsonObject()) { + return value.getAsJsonObject(); + } + + if (value != null && value.isJsonObject()) { + JsonObject found = findObjectByKey(value.getAsJsonObject(), wantedKey); + + if (found != null) { + return found; + } + } + } + + return null; + } + + private JsonObject findObjectContainingModuleName(JsonObject object, String moduleName, String displayName) { + if (object == null) { + return null; + } + + for (String key : object.keySet()) { + JsonElement value = object.get(key); + + if (value == null || !value.isJsonObject()) { + continue; + } + + JsonObject child = value.getAsJsonObject(); + + if (containsMatchingName(child, moduleName) || containsMatchingName(child, displayName)) { + return child; + } + + JsonObject nested = findObjectContainingModuleName(child, moduleName, displayName); + + if (nested != null) { + return nested; + } + } + + return null; + } + + private boolean containsMatchingName(JsonObject object, String name) { + if (object == null || name == null) { + return false; + } + + for (String key : object.keySet()) { + if (!key.equalsIgnoreCase("name") && !key.equalsIgnoreCase("module")) { + continue; + } + + JsonElement element = object.get(key); + + if (element != null && element.isJsonPrimitive() && element.getAsString().equalsIgnoreCase(name)) { + return true; + } + } + + return false; + } + + private JsonElement findSettingElement(JsonObject moduleObject, String settingName) { + if (moduleObject == null || settingName == null) { + return null; + } + + for (String key : moduleObject.keySet()) { + if (key.equalsIgnoreCase(settingName)) { + return moduleObject.get(key); + } + } + + for (String wrapper : new String[]{"settings", "Settings", "values", "Values"}) { + if (!moduleObject.has(wrapper)) { + continue; + } + + JsonElement wrapped = moduleObject.get(wrapper); + + if (!wrapped.isJsonObject()) { + continue; + } + + JsonObject settingsObject = wrapped.getAsJsonObject(); + + for (String key : settingsObject.keySet()) { + if (key.equalsIgnoreCase(settingName)) { + return settingsObject.get(key); + } + } + } + + return null; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static void setValueFromJson(Feature feature, Setting setting, JsonElement element) { + if (element == null || element.isJsonNull()) { + return; + } + + switch (setting.getType()) { + case "Boolean" -> { + try { + setting.setValue(element.getAsBoolean()); + } catch (Exception exception) { + LOGGER.error("Error parsing boolean for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + case "Double" -> { + try { + setting.setValue(element.getAsDouble()); + } catch (Exception exception) { + LOGGER.error("Error parsing double for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + case "Float" -> { + try { + setting.setValue(element.getAsFloat()); + } catch (Exception exception) { + LOGGER.error("Error parsing float for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + case "Integer" -> { + try { + setting.setValue(element.getAsInt()); + } catch (Exception exception) { + LOGGER.error("Error parsing integer for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + case "String" -> { + try { + setting.setValue(element.getAsString().replace("_", " ")); + } catch (Exception exception) { + LOGGER.error("Error parsing string for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + case "Bind" -> { + try { + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + + if (object.has("key")) { + setting.setValue(new Bind(object.get("key").getAsInt())); + } + } else { + setting.setValue(new Bind(element.getAsInt())); + } + } catch (Exception exception) { + LOGGER.error("Error parsing bind for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + case "Color" -> { + try { + Color color = parseColor(element); + + if (color != null) { + setting.setValue(color); + } + } catch (Exception exception) { + LOGGER.error("Error parsing color for: {} : {}", feature.getName(), setting.getName()); + } + } + + case "Pos" -> { + try { + String posStr = element.getAsString(); + String[] parts = posStr.split(","); + + if (parts.length == 2) { + float x = Float.parseFloat(parts[0].trim()); + float y = Float.parseFloat(parts[1].trim()); + + setting.setValue(new Vector2f(x, y)); + } + } catch (Exception exception) { + LOGGER.error("Error parsing position for: {} : {}", feature.getName(), setting.getName()); + } + } + + case "Enum" -> { + try { + EnumConverter converter = new EnumConverter(setting.getValue().getClass()); + Enum value = converter.doBackward(element); + + setting.setValue(value); + } catch (Exception exception) { + LOGGER.error("Error parsing enum for {}.{}: {}", feature.getName(), setting.getName(), exception); + } + } + + default -> LOGGER.error("Unknown Setting type for: {} : {}", feature.getName(), setting.getName()); + } + } + + private static Color parseColor(JsonElement element) { + if (element == null || element.isJsonNull()) { + return null; + } + + try { + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + + int r = getColorPart(object, "r", "red"); + int g = getColorPart(object, "g", "green"); + int b = getColorPart(object, "b", "blue"); + int a = object.has("a") || object.has("alpha") ? getColorPart(object, "a", "alpha") : 255; + + return new Color(clampColor(r), clampColor(g), clampColor(b), clampColor(a)); + } + + String colorStr = element.getAsString().trim(); + + if (colorStr.startsWith("#")) { + String hex = colorStr.substring(1); + + if (hex.length() == 6) { + int rgb = Integer.parseInt(hex, 16); + return new Color(rgb | 0xFF000000, true); + } + + if (hex.length() == 8) { + long rgba = Long.parseLong(hex, 16); + + int r = (int) ((rgba >> 24) & 0xFF); + int g = (int) ((rgba >> 16) & 0xFF); + int b = (int) ((rgba >> 8) & 0xFF); + int a = (int) (rgba & 0xFF); + + return new Color(r, g, b, a); + } + } + + String[] parts = colorStr.split(","); + + if (parts.length < 3) { + return null; + } + + int r = Integer.parseInt(parts[0].trim()); + int g = Integer.parseInt(parts[1].trim()); + int b = Integer.parseInt(parts[2].trim()); + int a = parts.length >= 4 ? Integer.parseInt(parts[3].trim()) : 255; + + return new Color(clampColor(r), clampColor(g), clampColor(b), clampColor(a)); + } catch (Throwable ignored) { + return null; + } + } + + private static int getColorPart(JsonObject object, String shortName, String longName) { + if (object.has(shortName)) { + return object.get(shortName).getAsInt(); + } + + if (object.has(longName)) { + return object.get(longName).getAsInt(); + } + + return 0; + } + + private static int clampColor(int value) { + return Math.max(0, Math.min(255, value)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/EventManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/EventManager.java new file mode 100644 index 0000000..4fd7409 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/EventManager.java @@ -0,0 +1,99 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.Stage; +import me.humanbeing.nolongerhuman.event.impl.entity.DeathEvent; +import me.humanbeing.nolongerhuman.event.impl.entity.player.TickEvent; +import me.humanbeing.nolongerhuman.event.impl.entity.player.UpdateWalkingPlayerEvent; +import me.humanbeing.nolongerhuman.event.impl.input.KeyInputEvent; +import me.humanbeing.nolongerhuman.event.impl.input.MouseInputEvent; +import me.humanbeing.nolongerhuman.event.impl.network.ChatEvent; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.Feature; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.BrandPayload; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.game.ClientboundSetTimePacket; +import net.minecraft.world.entity.player.Player; + +public class EventManager extends Feature { + public void init() { + EVENT_BUS.register(this); + } + + public void onUnload() { + EVENT_BUS.unregister(this); + } + + @Subscribe + public void onTick(TickEvent event) { + if (nullCheck()) + return; + nolongerhuman.moduleManager.onTick(); + for (Player player : mc.level.players()) { + if (player == null || player.getHealth() > 0.0F) + continue; + EVENT_BUS.post(new DeathEvent(player)); + } + } + + @Subscribe + public void onUpdateWalkingPlayer(UpdateWalkingPlayerEvent event) { + if (nullCheck()) + return; + if (event.getStage() == Stage.PRE) { + nolongerhuman.speedManager.update(); + nolongerhuman.rotationManager.onPreTick(); + nolongerhuman.positionManager.updatePosition(); + } + if (event.getStage() == Stage.POST) { + nolongerhuman.positionManager.restorePosition(); + } + } + + @Subscribe + public void onPacketReceive(PacketEvent.Receive event) { + nolongerhuman.serverManager.onPacketReceived(); + if (event.getPacket() instanceof ClientboundSetTimePacket) + nolongerhuman.serverManager.update(); + if (event.getPacket() instanceof ClientboundCustomPayloadPacket(CustomPacketPayload payload) + && payload instanceof BrandPayload(String brand)) { + nolongerhuman.serverManager.setServerBrand(brand); + } + } + + @Subscribe + public void onWorldRender(Render3DEvent event) { + nolongerhuman.moduleManager.onRender3D(event); + } + + @Subscribe + public void onRenderGameOverlayEvent(Render2DEvent event) { + nolongerhuman.moduleManager.onRender2D(event); + } + + @Subscribe + public void onKeyInput(KeyInputEvent event) { + nolongerhuman.moduleManager.onKeyPressed(event.getKey()); + } + + @Subscribe + public void onMouseInput(MouseInputEvent event) { + if (event.getAction() == 1) { + nolongerhuman.moduleManager.onMouseClicked(event.getButton()); + } + } + + @Subscribe + public void onChatSent(ChatEvent event) { + String message = event.getMessage(); + if (!message.startsWith(nolongerhuman.commandManager.getCommandPrefix())) { + return; + } + event.cancel(); + nolongerhuman.commandManager.onChatSent(message); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/FriendManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/FriendManager.java new file mode 100644 index 0000000..628dae0 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/FriendManager.java @@ -0,0 +1,62 @@ +package me.humanbeing.nolongerhuman.manager; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.util.traits.Jsonable; +import net.minecraft.world.entity.player.Player; + +import java.util.ArrayList; +import java.util.List; + +public class FriendManager implements Jsonable { + private final List friends = new ArrayList<>(); + + public void init() { + nolongerhuman.configManager.addConfig(this); + } + + public boolean isFriend(String name) { + return this.friends.stream().anyMatch(friend -> friend.equalsIgnoreCase(name)); + } + + public boolean isFriend(Player player) { + return this.isFriend(player.getGameProfile().name()); + } + + public void addFriend(String name) { + this.friends.add(name); + } + + public void removeFriend(String name) { + friends.removeIf(s -> s.equalsIgnoreCase(name)); + } + + public List getFriends() { + return this.friends; + } + + @Override + public JsonElement toJson() { + JsonObject object = new JsonObject(); + JsonArray array = new JsonArray(); + for (String friend : friends) { + array.add(friend); + } + object.add("friends", array); + return object; + } + + @Override + public void fromJson(JsonElement element) { + for (JsonElement e : element.getAsJsonObject().get("friends").getAsJsonArray()) { + friends.add(e.getAsString()); + } + } + + @Override + public String getFileName() { + return "friends.json"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/HoleManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/HoleManager.java new file mode 100644 index 0000000..dde6415 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/HoleManager.java @@ -0,0 +1,312 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.event.impl.entity.player.TickEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.Feature; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class HoleManager extends Feature { + private static final int RANGE = 8; + + private final List holes = new ArrayList<>(); + private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); + + public HoleManager() { + EVENT_BUS.register(this); + } + + @Subscribe + private void onTick(TickEvent event) { + if (mc.player == null || mc.level == null) { + holes.clear(); + return; + } + + holes.clear(); + + int originX = floor(mc.player.getX()); + int originY = floor(mc.player.getY()); + int originZ = floor(mc.player.getZ()); + + for (int x = -RANGE; x <= RANGE; x++) { + for (int y = -RANGE; y <= RANGE; y++) { + for (int z = -RANGE; z <= RANGE; z++) { + pos.set(originX + x, originY + y, originZ + z); + + Hole hole = getHole(pos); + + if (hole == null) { + hole = getPartialHole(pos); + } + + if (hole == null) continue; + + holes.add(hole); + } + } + } + } + + @Nullable + public Hole getHole(BlockPos pos) { + if (mc.level == null) return null; + + Level level = mc.level; + + if (!isClearHoleSpace(level, pos)) return null; + if (!isHoleBlock(level, pos.below())) return null; + + List walls = new ArrayList<>(); + + for (Direction direction : Direction.Plane.HORIZONTAL) { + BlockPos side = pos.relative(direction); + + if (!isHoleBlock(level, side)) { + return null; + } + + walls.add(level.getBlockState(side)); + } + + walls.add(level.getBlockState(pos.below())); + + return new Hole(pos.immutable(), classify(walls)); + } + + @Nullable + public Hole getPartialHole(BlockPos pos) { + if (mc.level == null) return null; + + Level level = mc.level; + + if (!isPartialHole(level, pos)) return null; + + return new Hole(pos.immutable(), HoleType.PARTIAL); + } + + public boolean isPartialHole(Level level, BlockPos pos) { + if (!isClearHoleSpace(level, pos)) return false; + + + if (getHole(pos) != null) return false; + if (isPartOfDoubleHole(level, pos)) return false; + if (isPartOfQuadHole(level, pos)) return false; + + if (!isSolid(level, pos.below())) return false; + + int solidSides = 0; + BlockPos openSide = null; + + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos neighbor = pos.relative(dir); + + if (isSolid(level, neighbor)) { + solidSides++; + } else { + openSide = neighbor; + } + } + + if (solidSides != 3) return false; + + return openSide != null && isSolid(level, openSide.below()); + } + + public boolean isPartOfDoubleHole(Level level, BlockPos pos) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos other = pos.relative(dir); + + if (getDoubleHoleType(level, pos, other) != null) { + return true; + } + } + + return false; + } + + public boolean isPartOfQuadHole(Level level, BlockPos pos) { + BlockPos[] possibleBases = { + pos, + pos.west(), + pos.north(), + pos.west().north() + }; + + for (BlockPos base : possibleBases) { + if (getQuadHoleType(level, base) != null) { + return true; + } + } + + return false; + } + + @Nullable + public HoleType getDoubleHoleType(Level level, BlockPos a, BlockPos b) { + if (!isClearHoleSpace(level, a)) return null; + if (!isClearHoleSpace(level, b)) return null; + + if (!areHorizontalNeighbors(a, b)) return null; + + Set cells = Set.of(a, b); + List walls = new ArrayList<>(); + + for (BlockPos cell : cells) { + BlockPos below = cell.below(); + + if (!isHoleBlock(level, below)) return null; + + walls.add(level.getBlockState(below)); + } + + for (BlockPos cell : cells) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos side = cell.relative(dir); + + if (cells.contains(side)) continue; + + if (!isHoleBlock(level, side)) return null; + + walls.add(level.getBlockState(side)); + } + } + + return classify(walls); + } + + @Nullable + public HoleType getQuadHoleType(Level level, BlockPos base) { + BlockPos east = base.east(); + BlockPos south = base.south(); + BlockPos diagonal = base.east().south(); + + Set cells = Set.of(base, east, south, diagonal); + List walls = new ArrayList<>(); + + for (BlockPos cell : cells) { + if (!isClearHoleSpace(level, cell)) return null; + + BlockPos below = cell.below(); + + if (!isHoleBlock(level, below)) return null; + + walls.add(level.getBlockState(below)); + } + + for (BlockPos cell : cells) { + for (Direction dir : Direction.Plane.HORIZONTAL) { + BlockPos side = cell.relative(dir); + + if (cells.contains(side)) continue; + + if (!isHoleBlock(level, side)) return null; + + walls.add(level.getBlockState(side)); + } + } + + return classify(walls); + } + + private boolean areHorizontalNeighbors(BlockPos a, BlockPos b) { + if (a.getY() != b.getY()) return false; + + int dx = Math.abs(a.getX() - b.getX()); + int dz = Math.abs(a.getZ() - b.getZ()); + + return dx + dz == 1; + } + + public boolean isClearHoleSpace(Level level, BlockPos pos) { + return level.getBlockState(pos).isAir() + && level.getBlockState(pos.above()).isAir() + && level.getBlockState(pos.above(2)).isAir(); + } + + public boolean isSolid(Level level, BlockPos pos) { + BlockState state = level.getBlockState(pos); + return state.isCollisionShapeFullBlock(level, pos); + } + + public boolean isHoleBlock(Level level, BlockPos pos) { + BlockState state = level.getBlockState(pos); + return state.is(Blocks.BEDROCK) || state.is(Blocks.OBSIDIAN); + } + + private HoleType classify(List blocks) { + boolean anyBedrock = false; + boolean anyObsidian = false; + + for (BlockState state : blocks) { + if (state.is(Blocks.BEDROCK)) { + anyBedrock = true; + } else if (state.is(Blocks.OBSIDIAN)) { + anyObsidian = true; + } + } + + if (anyBedrock && anyObsidian) { + return HoleType.MIXED; + } + + if (anyObsidian) { + return HoleType.UNSAFE; + } + + return HoleType.BEDROCK; + } + + public boolean isNormalHole(BlockPos pos) { + return holes.stream() + .anyMatch(hole -> hole.pos().equals(pos) && hole.holeType() != HoleType.PARTIAL); + } + + public boolean isHole(BlockPos pos) { + return holes.stream().anyMatch(hole -> hole.pos().equals(pos)); + } + + public boolean isPartial(BlockPos pos) { + return holes.stream() + .anyMatch(hole -> hole.pos().equals(pos) && hole.holeType() == HoleType.PARTIAL); + } + + public List getHoles() { + return holes; + } + + public List getNormalHoles() { + return holes.stream() + .filter(hole -> hole.holeType() != HoleType.PARTIAL) + .toList(); + } + + public List getPartialHoles() { + return holes.stream() + .filter(hole -> hole.holeType() == HoleType.PARTIAL) + .toList(); + } + + private int floor(double value) { + int i = (int) value; + return value < i ? i - 1 : i; + } + + public record Hole(BlockPos pos, HoleType holeType) { + } + + public enum HoleType { + BEDROCK, + UNSAFE, + MIXED, + PARTIAL + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/ModuleManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/ModuleManager.java new file mode 100644 index 0000000..58d01fa --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/ModuleManager.java @@ -0,0 +1,402 @@ +package me.humanbeing.nolongerhuman.manager; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.features.commands.ModuleCommand; +import me.humanbeing.nolongerhuman.features.modules.Module; +import me.humanbeing.nolongerhuman.features.modules.client.*; +import me.humanbeing.nolongerhuman.features.modules.combat.*; +import me.humanbeing.nolongerhuman.features.modules.hud.*; +import me.humanbeing.nolongerhuman.features.modules.movement.*; +import me.humanbeing.nolongerhuman.features.modules.player.*; +import me.humanbeing.nolongerhuman.features.modules.render.*; +import me.humanbeing.nolongerhuman.features.settings.Bind; +import me.humanbeing.nolongerhuman.util.traits.Jsonable; +import me.humanbeing.nolongerhuman.util.traits.Util; +import org.lwjgl.glfw.GLFW; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.util.stream.Stream; + +public class ModuleManager implements Jsonable, Util { + private static final Logger LOGGER = LoggerFactory.getLogger("ModuleManager"); + + private final Map, Module> fastRegistry = new HashMap<>(); + private final List modules = new ArrayList<>(); + private final Set heldModules = new HashSet<>(); + + public void init() { + register(new WatermarkHudModule()); + register(new CoordinatesHudModule()); + register(new ArmorHudModule()); + register(new ArmorWarnerHudModule()); + register(new HealthBarHudModule()); + register(new CompassHudModule()); + register(new WelcomerHudModule()); + register(new InfoHudModule()); + register(new SafetyHudModule()); + register(new ArrayListHudModule()); + register(new HeldItemHudModule()); + + register(new HudEditorModule()); + register(new ClickGuiModule()); + register(new NotificationsModule()); + register(new FakePlayerModule()); + register(new Robotics()); + register(new Rotations()); + register(new RPC()); + register(new IRC()); + register(new CustomFontModule()); + + register(new AutoCrystal()); + register(new PacketMine()); + register(new CombatPlace()); + register(new HoleBuilder()); + register(new SelfTrap()); + register(new Surround()); + register(new HoleESP()); + register(new Anchor()); + register(new AutoTrap()); + register(new Aura()); + //register(new AntiPearl()); + register(new Aura32k()); + register(new Blocker()); + register(new Anti32k()); + register(new PearlCatcher()); + register(new HoleFill()); + register(new PearlChaser()); + register(new Offhand()); + register(new AutoCity()); + register(new CrystalBlocker()); + register(new CEV()); + register(new AutoMace()); + register(new AntiChainPop()); + register(new AntiPop()); + register(new AntiMace()); + register(new MaceBlocker()); + register(new HoleRefill()); + register(new AnchorBlocker()); + register(new ObsidianFarmer()); + register(new AntiShulker()); + register(new SelfBow()); + register(new BowBoost()); + + register(new AuraFarmer()); + register(new Velocity()); + register(new KeyPearl()); + register(new KeyFirework()); + register(new KeyExperience()); + register(new Criticals()); + register(new NoEntityTrace()); + register(new NoInteract()); + register(new NoRotate()); + register(new Replenish()); + register(new HitboxDesync()); + register(new FakeLag()); + register(new AutoLog()); + register(new Scaffold()); + register(new ClipboardScreenshot()); + + register(new Accelerate()); + register(new AntiVoid()); + //register(new AutoLongJump()); + register(new ElytraFly()); + register(new FastClimb()); + register(new FastWeb()); + register(new LongJump()); + register(new NoSlow()); + register(new ReverseStep()); + register(new Sprint()); + register(new Step()); + register(new Speed()); + register(new TickShift()); + register(new AntiClimb()); + register(new InventoryMove()); + register(new FastSwim()); + register(new HoleSnap()); + register(new NoJumpDelay()); + + register(new CityESP()); + register(new BreakESP()); + register(new FullBright()); + register(new KillEffect()); + register(new NoRender()); + register(new BlockHighlight()); + register(new CrystalCircles()); + register(new AuraCircles()); + register(new ViewModel()); + register(new NoEatingAnimation()); + register(new PlaceAnimations()); + register(new BreakAnimations()); + register(new AttackAnimations()); + register(new CrystalChams()); + register(new PopChams()); + register(new Ambience()); + register(new Nametags()); + register(new Trajectories()); + register(new Freecam()); + register(new TargetESP()); + + LOGGER.info("Registered {} modules", modules.size()); + + for (Module module : modules) { + nolongerhuman.commandManager.register(new ModuleCommand(module)); + } + + nolongerhuman.configManager.addConfig(this); + } + + public void register(Module module) { + if (module == null) { + return; + } + + getModules().add(module); + fastRegistry.put(module.getClass(), module); + } + + public List getModules() { + return modules; + } + + public Stream stream() { + return getModules().stream(); + } + + @SuppressWarnings("unchecked") + public T getModuleByClass(Class clazz) { + return (T) fastRegistry.get(clazz); + } + + public Module getModuleByName(String name) { + if (name == null) { + return null; + } + + return stream() + .filter(module -> module.getName().equalsIgnoreCase(name)) + .findFirst() + .orElse(null); + } + + public Module getModuleByDisplayName(String display) { + if (display == null) { + return null; + } + + return stream() + .filter(module -> module.getDisplayName().equalsIgnoreCase(display)) + .findFirst() + .orElse(null); + } + + public List getModulesByCategory(Module.Category category) { + return stream() + .filter(module -> module.getCategory() == category) + .toList(); + } + + public List getCategories() { + return Arrays.asList(Module.Category.values()); + } + + public void onLoad() { + getModules().forEach(Module::onLoad); + } + + public void onTick() { + updateHoldBinds(); + + stream() + .filter(Feature::isEnabled) + .forEach(Module::onTick); + } + + public void onRender2D(Render2DEvent event) { + stream() + .filter(Feature::isEnabled) + .forEach(module -> module.onRender2D(event)); + } + + public void onRender3D(Render3DEvent event) { + stream() + .filter(Feature::isEnabled) + .forEach(module -> module.onRender3D(event)); + } + + public void onUnload() { + disableAllHeldModules(); + + getModules().forEach(EVENT_BUS::unregister); + getModules().forEach(Module::onUnload); + } + + public void onKeyPressed(int key) { + if (key <= 0 || mc.screen != null) { + return; + } + + for (Module module : getModules()) { + Bind bind = module.getBind(); + + if (bind == null || bind.isEmpty() || bind.isMouse()) { + continue; + } + + if (bind.getKey() != key) { + continue; + } + + if (bind.isToggle()) { + module.toggle(); + } else if (bind.isHold()) { + enableHeldModule(module); + } + } + } + + public void onMouseClicked(int button) { + if (mc.screen != null) { + return; + } + + int key = -button - 2; + + for (Module module : getModules()) { + Bind bind = module.getBind(); + + if (bind == null || bind.isEmpty() || !bind.isMouse()) { + continue; + } + + if (bind.getKey() != key) { + continue; + } + + if (bind.isToggle()) { + module.toggle(); + } else if (bind.isHold()) { + enableHeldModule(module); + } + } + } + + private void updateHoldBinds() { + long windowHandle = GLFW.glfwGetCurrentContext(); + + if (windowHandle == 0L) { + disableAllHeldModules(); + return; + } + + for (Module module : getModules()) { + Bind bind = module.getBind(); + + if (bind == null || bind.isEmpty()) { + if (heldModules.remove(module) && module.isEnabled()) { + module.disable(); + } + + continue; + } + + if (!bind.isHold()) { + if (heldModules.remove(module) && module.isEnabled()) { + module.disable(); + } + + continue; + } + + boolean bindDown = mc.screen == null && isBindDown(bind, windowHandle); + + if (bindDown) { + enableHeldModule(module); + continue; + } + + if (module.isEnabled()) { + module.disable(); + } + + heldModules.remove(module); + } + } + + private boolean isBindDown(Bind bind, long windowHandle) { + if (bind == null || bind.isEmpty()) { + return false; + } + + if (bind.isMouse()) { + int mouseButton = bind.getMouseButton(); + + if (mouseButton < 0 || mouseButton > GLFW.GLFW_MOUSE_BUTTON_LAST) { + return false; + } + + return GLFW.glfwGetMouseButton(windowHandle, mouseButton) == GLFW.GLFW_PRESS; + } + + int key = bind.getKey(); + + if (key <= 0 || key > GLFW.GLFW_KEY_LAST) { + return false; + } + + return GLFW.glfwGetKey(windowHandle, key) == GLFW.GLFW_PRESS; + } + + private void enableHeldModule(Module module) { + heldModules.add(module); + + if (!module.isEnabled()) { + module.enable(); + } + } + + private void disableAllHeldModules() { + for (Module module : new HashSet<>(heldModules)) { + if (module.isEnabled()) { + module.disable(); + } + } + + heldModules.clear(); + } + + @Override + public JsonElement toJson() { + JsonObject object = new JsonObject(); + + for (Module module : getModules()) { + object.add(module.getName(), module.toJson()); + } + + return object; + } + + @Override + public void fromJson(JsonElement element) { + if (element == null || !element.isJsonObject()) { + return; + } + + JsonObject object = element.getAsJsonObject(); + + for (Module module : getModules()) { + module.fromJson(object.get(module.getName())); + } + } + + @Override + public String getFileName() { + return "modules.json"; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/PositionManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/PositionManager.java new file mode 100644 index 0000000..514308a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/PositionManager.java @@ -0,0 +1,92 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.event.Stage; +import me.humanbeing.nolongerhuman.event.impl.entity.player.UpdateWalkingPlayerEvent; +import me.humanbeing.nolongerhuman.event.system.Subscribe; +import me.humanbeing.nolongerhuman.features.Feature; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; + +public class PositionManager + extends Feature { + private double x; + private double y; + private double z; + private boolean onground; + private double fallDistance; + + public PositionManager() { + EVENT_BUS.register(this); + } + + @Subscribe + public void onUpdateWalkingPlayer(UpdateWalkingPlayerEvent event) { + if (event.getStage() == Stage.POST) return; + + double diff = mc.player.yo - mc.player.getY(); + if (mc.player.onGround() || diff <= 0) { + fallDistance = 0; + } else { + fallDistance += diff; + } + } + + public void updatePosition() { + this.x = mc.player.getX(); + this.y = mc.player.getY(); + this.z = mc.player.getZ(); + this.onground = mc.player.onGround(); + } + + public void restorePosition() { + mc.player.setPos(x, y, z); + mc.player.setOnGround(onground); + } + + public void setPlayerPosition(double x, double y, double z) { + mc.player.setPos(x, y, z); + } + + public void setPlayerPosition(double x, double y, double z, boolean onground) { + mc.player.setPos(x, y, z); + mc.player.setOnGround(onground); + } + + public void setPositionPacket(double x, double y, double z, boolean onGround, boolean setPos, boolean noLagBack) { + boolean bl = mc.player.horizontalCollision; + mc.player.connection.send(new ServerboundMovePlayerPacket.Pos(x, y, z, onGround, bl)); + if (setPos) { + mc.player.setPos(x, y, z); + if (noLagBack) { + this.updatePosition(); + } + } + } + + public double getX() { + return this.x; + } + + public void setX(double x) { + this.x = x; + } + + public double getY() { + return this.y; + } + + public void setY(double y) { + this.y = y; + } + + public double getZ() { + return this.z; + } + + public void setZ(double z) { + this.z = z; + } + + public double getFallDistance() { + return fallDistance; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/RotationManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/RotationManager.java new file mode 100644 index 0000000..3eaf224 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/RotationManager.java @@ -0,0 +1,1354 @@ +package me.humanbeing.nolongerhuman.manager; + +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.phys.Vec3; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Random; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.function.Supplier; + +@SuppressWarnings("unused") +public class RotationManager { + private static RotationManager INSTANCE; + private static final Random RANDOM = new Random(); + private final RotationConfig config = new RotationConfig(); + private final RotationStateHandler stateHandler = new RotationStateHandler(); + private final RotationRequestHandler requestHandler = + new RotationRequestHandler(stateHandler, config); + private final RotationTickHandler tickHandler = + new RotationTickHandler(stateHandler, requestHandler, config); + private float clientYaw; + private float clientPitch; + private float spoofedYaw; + private float spoofedPitch; + private float targetYaw; + private float targetPitch; + private boolean spoofing; + private float smoothServerYaw; + private float smoothServerPitch; + private boolean smoothInitialized; + private float lastSentYaw; + private float lastSentPitch; + private float gcdYaw; + private float gcdPitch; + private boolean gcdInitialized; + private float noiseYaw; + private float noisePitch; + private final PriorityBlockingQueue legacyQueue = + new PriorityBlockingQueue<>(11, this::compareLegacyRotations); + private float queuedYaw; + private float queuedPitch; + private boolean hasQueued; + private float prevRenderYaw; + private float prevRenderPitch; + private long lastRenderTime = 0L; + + public RotationManager() { + INSTANCE = this; + } + + public static RotationManager getInstance() { + return INSTANCE; + } + + static Minecraft mc() { + return Minecraft.getInstance(); + } + + public void onPreTick() { + updateRotations(); + tickHandler.onPreTick(); + } + + public void submit(RotationRequest request) { + requestHandler.submit(request); + } + + public void cancel(String id) { + requestHandler.cancel(id); + } + + public boolean hasRequest(String id) { + return requestHandler.hasRequest(id); + } + + public boolean isCompleted(String id) { + return requestHandler.isCompleted(id); + } + + public boolean isRotating() { + return tickHandler.isRotating(); + } + + public RotationConfig getConfig() { + return config; + } + + public RotationStateHandler getStateHandler() { + return stateHandler; + } + + public RotationRequestHandler getRequestHandler() { + return requestHandler; + } + + public RotationTickHandler getTickHandler() { + return tickHandler; + } + + private static final String DEFAULT_ID = "manual"; + private static final int DEFAULT_PRIORITY = 1; + + public void rotateTo(float yaw, float pitch) { + rotateTo(DEFAULT_ID, DEFAULT_PRIORITY, yaw, pitch); + } + + public void rotateTo(String id, int priority, float yaw, float pitch) { + submit(new RotationRequest(id, priority, yaw, pitch)); + } + + public void rotateDynamic(String id, int priority, Supplier yaw, Supplier pitch) { + submit(new RotationRequest(id, priority, yaw, pitch)); + } + + public void lookAtPos(BlockPos pos) { + lookAtVec3d(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5); + } + + public void lookAtVec3d(Vec3 vec) { + if (mc().player == null) return; + submit(new RotationRequest(DEFAULT_ID, DEFAULT_PRIORITY, mc().player, vec)); + } + + public void lookAtVec3d(double x, double y, double z) { + lookAtVec3d(new Vec3(x, y, z)); + } + + public void lookAtEntity(Entity entity) { + if (entity == null) return; + lookAtVec3d(entity.getEyePosition()); + } + + public void lookAtVec3(Vec3 vec3) { + lookAtVec3d(vec3); + } + + public boolean applyRotation(String id, int priority, float yaw, float pitch) { + RotationConfig cfg = getConfig(); + RotationMethod method = cfg.getRotationMethod(); + if (method == RotationMethod.NONE) { + return true; + } + pitch = Mth.clamp(pitch, -90f, 90f); + float step = (float) cfg.getRotationStep(); + switch (method) { + case NORMAL -> submit(new RotationRequest(id, priority, yaw, pitch, RotationMode.NORMAL)); + case MOTION, SMOOTH -> submit(new RotationRequest(id, priority, yaw, pitch, RotationMode.MOTION)); + case SILENT -> submit(new RotationRequest(id, priority, yaw, pitch, RotationMode.SILENT)); + case SPOOF -> setSpoofedRotations(yaw, pitch); + case SMOOTH_SPOOF -> setSpoofedRotations(yaw, pitch, step); + case GCD -> setSpoofedRotationsGCD(yaw, pitch, step); + case NOISE -> setSpoofedRotationsWithNoise(yaw, pitch, step, (float) cfg.getRotationNoise()); + case PACKET -> packetRotate(yaw, pitch); + case QUEUE -> rotate(yaw, pitch, priority); + case NONE -> { + return true; + } + } + return isRotationReady(id, yaw, pitch); + } + + public boolean applyRotation(String id, int priority, float[] rotations) { + if (rotations == null || rotations.length < 2) { + return true; + } + return applyRotation(id, priority, rotations[0], rotations[1]); + } + + public boolean applyRotationTo(String id, int priority, Vec3 target) { + float[] rot = calcRotationsTo(target); + return applyRotation(id, priority, rot[0], rot[1]); + } + + public boolean applyRotationTo(String id, int priority, BlockPos pos) { + return applyRotationTo(id, priority, new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5)); + } + + public boolean applyRotationToEntity(String id, int priority, Entity entity) { + if (entity == null) { + return true; + } + float[] rot = calcRotationsToEntity(entity); + return applyRotation(id, priority, rot[0], rot[1]); + } + + public boolean isRotationReady(String id, float yaw, float pitch) { + RotationConfig cfg = getConfig(); + if (!cfg.isRotationWait()) { + return true; + } + float tol = (float) cfg.getRotationThreshold(); + return switch (cfg.getRotationMethod()) { + case NONE, NORMAL, SILENT, SPOOF, PACKET -> true; + case MOTION, SMOOTH -> isCompleted(id); + case SMOOTH_SPOOF, GCD, NOISE -> isAligned(tol); + case QUEUE -> getAngleDifference(yaw, getServerYaw()) <= tol + && getPitchDifference(pitch, getServerPitch()) <= tol; + }; + } + + public void endRotation(String id, int priority) { + cancel(id); + clearRotations(priority); + RotationMethod method = getConfig().getRotationMethod(); + if (method == RotationMethod.SPOOF + || method == RotationMethod.SMOOTH_SPOOF + || method == RotationMethod.GCD + || method == RotationMethod.NOISE) { + resetSpoofedRotations(); + } + } + + + @Deprecated + public void restoreRotations() { + cancel(DEFAULT_ID); + if (mc().player == null) { + return; + } + mc().player.setYRot(clientYaw); + mc().player.yHeadRot = clientYaw; + mc().player.setXRot(clientPitch); + } + + @Deprecated + public void updateRotations() { + if (mc().player == null) { + return; + } + this.clientYaw = mc().player.getYRot(); + this.clientPitch = mc().player.getXRot(); + stateHandler.updateRealRotation(clientYaw, clientPitch); + long now = System.currentTimeMillis(); + legacyQueue.removeIf(req -> now - req.time > 100L); + LegacyRotationRequest best = legacyQueue.peek(); + if (best != null) { + this.queuedYaw = best.yaw; + this.queuedPitch = Mth.clamp(best.pitch, -90f, 90f); + this.hasQueued = true; + this.lastRenderTime = now; + } else { + this.hasQueued = false; + } + } + + public void setPlayerRotations(float yaw, float pitch) { + rotateTo(yaw, pitch); + } + + public void setPlayerYaw(float yaw) { + rotateTo(yaw, stateHandler.getRotationXRot()); + } + + public void setPlayerPitch(float pitch) { + rotateTo(stateHandler.getRotationYRot(), pitch); + } + + public void forcePlayerRotations(float yaw, float pitch) { + if (mc().player == null) { + return; + } + pitch = Mth.clamp(pitch, -90f, 90f); + mc().player.setYRot(yaw); + mc().player.yHeadRot = yaw; + mc().player.setXRot(pitch); + stateHandler.updateRealRotation(yaw, pitch); + stateHandler.setRotationYRot(yaw); + stateHandler.setRotationXRot(pitch); + } + + public float getYaw() { + return stateHandler.getRotationYRot(); + } + + public void setYaw(float yaw) { + this.clientYaw = yaw; + stateHandler.setRotationYRot(yaw); + } + + public float getPitch() { + return stateHandler.getRotationXRot(); + } + + public float getClientYaw() { + return clientYaw; + } + + public float getClientPitch() { + return clientPitch; + } + + public float getSpoofedYaw() { + return spoofedYaw; + } + + public float getSpoofedPitch() { + return spoofedPitch; + } + + public float getTargetYaw() { + return targetYaw; + } + + public float getTargetPitch() { + return targetPitch; + } + + public boolean isSpoofing() { + return spoofing; + } + + public float getLastSentYaw() { + return lastSentYaw; + } + + public float getLastSentPitch() { + return lastSentPitch; + } + + public void setSpoofedRotations(float yaw, float pitch) { + this.targetYaw = yaw; + this.targetPitch = Mth.clamp(pitch, -90f, 90f); + this.spoofedYaw = this.targetYaw; + this.spoofedPitch = this.targetPitch; + this.spoofing = true; + this.smoothInitialized = false; + this.gcdInitialized = false; + updateNoise(0f, 0f); + stateHandler.setServerYRot(this.spoofedYaw); + stateHandler.setServerXRot(this.spoofedPitch); + this.lastRenderTime = System.currentTimeMillis(); + } + + public void setSpoofedRotations(float targetYaw, float targetPitch, float step) { + if (mc().player == null) { + return; + } + this.targetYaw = targetYaw; + this.targetPitch = Mth.clamp(targetPitch, -90f, 90f); + if (!smoothInitialized || !spoofing) { + this.smoothServerYaw = mc().player.getYRot(); + this.smoothServerPitch = mc().player.getXRot(); + this.smoothInitialized = true; + } + float deltaYaw = Mth.wrapDegrees(this.targetYaw - smoothServerYaw); + if (Math.abs(deltaYaw) > step) { + smoothServerYaw = Mth.wrapDegrees(smoothServerYaw + (deltaYaw > 0 ? step : -step)); + } else { + smoothServerYaw = this.targetYaw; + } + float deltaPitch = this.targetPitch - smoothServerPitch; + if (Math.abs(deltaPitch) > step) { + smoothServerPitch += deltaPitch > 0 ? step : -step; + } else { + smoothServerPitch = this.targetPitch; + } + smoothServerPitch = Mth.clamp(smoothServerPitch, -90f, 90f); + this.spoofedYaw = smoothServerYaw; + this.spoofedPitch = smoothServerPitch; + this.spoofing = true; + stateHandler.setServerYRot(this.spoofedYaw); + stateHandler.setServerXRot(this.spoofedPitch); + this.lastRenderTime = System.currentTimeMillis(); + } + + public void setSpoofedRotationsGCD(float targetYaw, float targetPitch, float step) { + if (mc().player == null) { + return; + } + this.targetYaw = targetYaw; + this.targetPitch = Mth.clamp(targetPitch, -90f, 90f); + if (!smoothInitialized || !spoofing) { + this.smoothServerYaw = mc().player.getYRot(); + this.smoothServerPitch = mc().player.getXRot(); + this.smoothInitialized = true; + } + if (!gcdInitialized) { + gcdYaw = computeGCDFactor(); + gcdPitch = computeGCDFactor(); + gcdInitialized = true; + } + float deltaYaw = Mth.wrapDegrees(this.targetYaw - smoothServerYaw); + if (Math.abs(deltaYaw) > step) { + smoothServerYaw = Mth.wrapDegrees(smoothServerYaw + (deltaYaw > 0 ? step : -step)); + } else { + smoothServerYaw = this.targetYaw; + } + float deltaPitch = this.targetPitch - smoothServerPitch; + if (Math.abs(deltaPitch) > step) { + smoothServerPitch += deltaPitch > 0 ? step : -step; + } else { + smoothServerPitch = this.targetPitch; + } + smoothServerPitch = Mth.clamp(smoothServerPitch, -90f, 90f); + this.spoofedYaw = applyGCD(smoothServerYaw, lastSentYaw, gcdYaw); + this.spoofedPitch = applyGCD(smoothServerPitch, lastSentPitch, gcdPitch); + this.spoofedPitch = Mth.clamp(this.spoofedPitch, -90f, 90f); + this.spoofing = true; + stateHandler.setServerYRot(this.spoofedYaw); + stateHandler.setServerXRot(this.spoofedPitch); + this.lastRenderTime = System.currentTimeMillis(); + } + + public void setSpoofedRotationsWithNoise(float targetYaw, float targetPitch, float step, float noiseStrength) { + updateNoise(noiseStrength, noiseStrength * 0.5f); + setSpoofedRotations(targetYaw + noiseYaw, targetPitch + noisePitch, step); + } + + public void resetSpoofedRotations() { + this.spoofing = false; + this.smoothInitialized = false; + this.gcdInitialized = false; + this.noiseYaw = 0f; + this.noisePitch = 0f; + } + + public boolean isAligned(float tolerance) { + if (!spoofing) { + return true; + } + float deltaYaw = Math.abs(Mth.wrapDegrees(targetYaw - spoofedYaw)); + float deltaPitch = Math.abs(targetPitch - spoofedPitch); + return deltaYaw <= tolerance && deltaPitch <= tolerance; + } + + public boolean isAlignedPitch(float tolerance) { + if (!spoofing) { + return true; + } + return Math.abs(targetPitch - spoofedPitch) <= tolerance; + } + + public float getServerYaw() { + if (hasQueued) { + return queuedYaw; + } + if (spoofing) { + return spoofedYaw; + } + return stateHandler.getServerYRot(); + } + + public float getServerPitch() { + if (hasQueued) { + return queuedPitch; + } + if (spoofing) { + return spoofedPitch; + } + return stateHandler.getServerXRot(); + } + + public float getEffectiveYaw() { + if (hasQueued) { + return queuedYaw; + } + if (spoofing) { + return spoofedYaw; + } + return clientYaw; + } + + public float getEffectivePitch() { + if (hasQueued) { + return queuedPitch; + } + if (spoofing) { + return spoofedPitch; + } + return clientPitch; + } + + public boolean shouldSpoof() { + return spoofing || hasQueued || requestHandler.getActiveRequest() != null; + } + + public void rotate(float[] rotations, int priority) { + if (rotations == null || rotations.length < 2) { + return; + } + rotate(rotations[0], rotations[1], priority); + } + + public void rotate(float yaw, float pitch, int priority) { + legacyQueue.removeIf(req -> req.priority == priority); + legacyQueue.add(new LegacyRotationRequest(yaw, pitch, priority)); + lastRenderTime = System.currentTimeMillis(); + } + + public void clearRotations(int priority) { + legacyQueue.removeIf(req -> req.priority == priority); + } + + public void clearAllRotations() { + legacyQueue.clear(); + hasQueued = false; + resetSpoofedRotations(); + requestHandler.clear(); + } + + public void onMovePacketSent(float yaw, float pitch) { + this.lastSentYaw = yaw; + this.lastSentPitch = pitch; + } + + public void packetRotate(float[] rotations) { + if (rotations == null || rotations.length < 2) { + return; + } + packetRotate(rotations[0], rotations[1]); + } + + public void packetRotate(float yaw, float pitch) { + if (mc().player == null || mc().player.connection == null) { + return; + } + pitch = Mth.clamp(pitch, -90f, 90f); + if (lastSentYaw == yaw && lastSentPitch == pitch) { + return; + } + mc().player.connection.send(new ServerboundMovePlayerPacket.Rot( + yaw, + pitch, + mc().player.onGround(), + mc().player.horizontalCollision + )); + this.lastSentYaw = yaw; + this.lastSentPitch = pitch; + stateHandler.setServerYRot(yaw); + stateHandler.setServerXRot(pitch); + } + + public void packetRotateTo(Vec3 target) { + float[] rotations = calcRotationsTo(target); + packetRotate(rotations[0], rotations[1]); + } + + public void packetRotateTo(BlockPos pos) { + packetRotateTo(new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5)); + } + + public boolean inRenderTime() { + return System.currentTimeMillis() - lastRenderTime < 1000L; + } + + public float[] getRenderRotations() { + if (mc().player == null) { + return new float[]{prevRenderYaw, prevRenderPitch}; + } + float targetYawValue = shouldSpoof() ? getEffectiveYaw() : mc().player.getYRot(); + float targetPitchValue = shouldSpoof() ? getEffectivePitch() : mc().player.getXRot(); + float factor = Mth.clamp((System.currentTimeMillis() - lastRenderTime) / 1000f, 0f, 1f); + float yaw = Mth.rotLerp(factor, prevRenderYaw, targetYawValue); + float pitch = Mth.lerp(factor, prevRenderPitch, targetPitchValue); + prevRenderYaw = yaw; + prevRenderPitch = pitch; + return new float[]{yaw, pitch}; + } + + public Vec3 getEffectiveLookVec() { + return calculateViewVector(getEffectivePitch(), getEffectiveYaw()); + } + + public float[] calcRotationsTo(Vec3 target) { + if (mc().player == null) { + return new float[]{clientYaw, clientPitch}; + } + return calcAngle(mc().player.getEyePosition(), target); + } + + public float[] calcRotationsTo(BlockPos pos) { + return calcRotationsTo(new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5)); + } + + public float[] calcRotationsToEntity(Entity entity) { + if (mc().player == null || entity == null) { + return new float[]{clientYaw, clientPitch}; + } + return calcAngle(mc().player.getEyePosition(), entity.getEyePosition()); + } + + public float getAngleDifference(float yaw1, float yaw2) { + return Math.abs(Mth.wrapDegrees(yaw1 - yaw2)); + } + + public float getPitchDifference(float pitch1, float pitch2) { + return Math.abs(pitch1 - pitch2); + } + + public boolean isFacingEntity(Entity entity, float fovDegrees) { + if (mc().player == null || entity == null) { + return false; + } + float[] needed = calcRotationsToEntity(entity); + float deltaYaw = getAngleDifference(mc().player.getYRot(), needed[0]); + float deltaPitch = getPitchDifference(mc().player.getXRot(), needed[1]); + float half = fovDegrees / 2f; + return deltaYaw <= half && deltaPitch <= half; + } + + public float interpolatePitch(float from, float to, float factor) { + return from + factor * (to - from); + } + + private Vec3 calculateViewVector(float pitch, float yaw) { + float pitchRad = pitch * ((float) Math.PI / 180f); + float yawRad = -yaw * ((float) Math.PI / 180f); + float cosPitch = Mth.cos(pitchRad); + float sinPitch = Mth.sin(pitchRad); + float cosYaw = Mth.cos(yawRad); + float sinYaw = Mth.sin(yawRad); + return new Vec3(sinYaw * cosPitch, -sinPitch, cosYaw * cosPitch); + } + + private float applyGCD(float current, float last, float gcdFactor) { + if (gcdFactor <= 0f) { + return current; + } + float delta = Mth.wrapDegrees(current - last); + float steps = Math.round(delta / gcdFactor); + return last + steps * gcdFactor; + } + + private float computeGCDFactor() { + float sensitivity = (float) (double) mc().options.sensitivity().get(); + if (sensitivity <= 0f) { + return 0.35f; + } + float f = sensitivity * 0.6f + 0.2f; + float f3 = f * f * f * 1.2f; + return f3 * 8f; + } + + private void updateNoise(float yawStrength, float pitchStrength) { + if (yawStrength <= 0f && pitchStrength <= 0f) { + noiseYaw = 0f; + noisePitch = 0f; + return; + } + noiseYaw = (float) (RANDOM.nextGaussian() * yawStrength); + noisePitch = (float) (RANDOM.nextGaussian() * pitchStrength); + } + + private int compareLegacyRotations(LegacyRotationRequest a, LegacyRotationRequest b) { + if (a.priority == b.priority) { + return -Long.compare(a.time, b.time); + } + return -Integer.compare(a.priority, b.priority); + } + + static float wrapDegrees(float degrees) { + return Mth.wrapDegrees(degrees); + } + + static float yRotDifference(float a, float b) { + return Mth.wrapDegrees(a - b); + } + + static float alignYRot(float realYRot, float rotationYRot) { + return rotationYRot + yRotDifference(realYRot, rotationYRot); + } + + static Vec3 predictMotion(LivingEntity player) { + return player.getEyePosition().add(player.getDeltaMovement()); + } + + static float[] calcAngle(Vec3 from, Vec3 to) { + double dx = to.x - from.x; + double dy = to.y - from.y; + double dz = to.z - from.z; + double horizontal = Math.sqrt(dx * dx + dz * dz); + float yRot = Mth.wrapDegrees((float) Math.toDegrees(Math.atan2(dz, dx)) - 90.0F); + float xRot = Mth.clamp((float) -Math.toDegrees(Math.atan2(dy, horizontal)), -90F, 90F); + return new float[]{yRot, xRot}; + } + + static float getYRotToVec(Vec3 from, Vec3 to) { + return calcAngle(from, to)[0]; + } + + static float getXRotToVec(Vec3 from, Vec3 to) { + return calcAngle(from, to)[1]; + } + + static float lerp(float from, float to, float factor) { + return from + (to - from) * factor; + } + + public enum RotationMode { + NORMAL, + MOTION, + SILENT + } + + public enum JitterMode { + NONE, + NORMAL, + GRIM + } + + public enum RotationMethod { + NONE, + NORMAL, + MOTION, + SILENT, + SMOOTH, + SPOOF, + SMOOTH_SPOOF, + GCD, + NOISE, + PACKET, + QUEUE + } + + public static class RotationConfig { + private RotationMode rotationMode = RotationMode.MOTION; + private JitterMode jitterMode = JitterMode.NONE; + private double rotationSpeed = 30.0; + private double rotationEase = 0.45; + private double rotationThreshold = 1.0; + private int holdTicks = 2; + private boolean moveFix = true; + + private RotationMethod rotationMethod = RotationMethod.SILENT; + private double rotationStep = 30.0; + private double rotationNoise = 1.0; + private boolean rotationWait = false; + + public RotationMode getRotationMode() { + return rotationMode; + } + + public void setRotationMode(RotationMode v) { + this.rotationMode = v; + } + + public JitterMode getJitterMode() { + return jitterMode; + } + + public void setJitterMode(JitterMode v) { + this.jitterMode = v; + } + + public double getRotationSpeed() { + return rotationSpeed; + } + + public void setRotationSpeed(double v) { + this.rotationSpeed = v; + } + + public double getRotationEase() { + return rotationEase; + } + + public void setRotationEase(double v) { + this.rotationEase = v; + } + + public double getRotationThreshold() { + return rotationThreshold; + } + + public void setRotationThreshold(double v) { + this.rotationThreshold = v; + } + + public int getHoldTicks() { + return holdTicks; + } + + public void setHoldTicks(int v) { + this.holdTicks = v; + } + + public boolean isMoveFixEnabled() { + return moveFix; + } + + public void setMoveFixEnabled(boolean v) { + this.moveFix = v; + } + + public RotationMethod getRotationMethod() { + return rotationMethod; + } + + public void setRotationMethod(RotationMethod v) { + this.rotationMethod = v; + } + + public double getRotationStep() { + return rotationStep; + } + + public void setRotationStep(double v) { + this.rotationStep = v; + } + + public double getRotationNoise() { + return rotationNoise; + } + + public void setRotationNoise(double v) { + this.rotationNoise = v; + } + + public boolean isRotationWait() { + return rotationWait; + } + + public void setRotationWait(boolean v) { + this.rotationWait = v; + } + } + + public static class RotationRequest { + public final String id; + public final int priority; + private final boolean dynamic; + private final Supplier yRotSupplier; + private final Supplier xRotSupplier; + public float targetYRot; + public float targetXRot; + public final RotationMode rotationMode; + + public RotationRequest(String id, int priority, float yRot, float xRot) { + this(id, priority, yRot, xRot, getDefaultRotationMode()); + } + + public RotationRequest(String id, int priority, float yRot, float xRot, RotationMode rotationMode) { + this.id = id; + this.priority = priority; + this.dynamic = false; + this.targetYRot = yRot; + this.targetXRot = Mth.clamp(xRot, -90f, 90f); + this.yRotSupplier = null; + this.xRotSupplier = null; + this.rotationMode = rotationMode; + } + + public RotationRequest(String id, int priority, Supplier yRotSupplier, Supplier xRotSupplier) { + this(id, priority, yRotSupplier, xRotSupplier, getDefaultRotationMode()); + } + + public RotationRequest(String id, int priority, Supplier yRotSupplier, Supplier xRotSupplier, RotationMode rotationMode) { + this.id = id; + this.priority = priority; + this.dynamic = true; + this.yRotSupplier = yRotSupplier; + this.xRotSupplier = xRotSupplier; + this.rotationMode = rotationMode; + updateTarget(); + } + + public RotationRequest(String id, int priority, LivingEntity player, Vec3 pos) { + this.id = id; + this.priority = priority; + this.rotationMode = RotationMode.MOTION; + Vec3 predictedEye = predictMotion(player); + this.targetYRot = getYRotToVec(predictedEye, pos); + this.targetXRot = getXRotToVec(predictedEye, pos); + this.yRotSupplier = null; + this.xRotSupplier = null; + this.dynamic = false; + } + + public boolean shouldUpdate() { + return dynamic; + } + + public void updateTarget() { + if (dynamic && yRotSupplier != null && xRotSupplier != null) { + targetYRot = yRotSupplier.get(); + targetXRot = Mth.clamp(xRotSupplier.get(), -90f, 90f); + } + } + + private static RotationMode getDefaultRotationMode() { + RotationManager rm = getInstance(); + return rm != null ? rm.getConfig().getRotationMode() : RotationMode.MOTION; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof RotationRequest)) return false; + return this.id.equals(((RotationRequest) o).id); + } + + @Override + public int hashCode() { + return id.hashCode(); + } + } + + public static class RotationStateHandler { + private float realYRot; + private float realXRot; + private float rotationYRot; + private float rotationXRot; + private float serverYRot; + private float serverXRot; + private float serverYRot0; + private float serverXRot0; + private float serverDeltaYRot; + private boolean silentSyncRequired; + private boolean moveFixActive; + private boolean mfForward; + private boolean mfBack; + private boolean mfLeft; + private boolean mfRight; + + public void updateRealRotation(float yRot, float xRot) { + realYRot = yRot; + realXRot = Mth.clamp(xRot, -90f, 90f); + } + + public float getRealYRot() { + return realYRot; + } + + public float getRealXRot() { + return realXRot; + } + + public float getRotationYRot() { + return rotationYRot; + } + + public float getRotationXRot() { + return rotationXRot; + } + + public void setRotationYRot(float yRot) { + this.rotationYRot = yRot; + } + + public void setRotationXRot(float xRot) { + this.rotationXRot = Mth.clamp(xRot, -90f, 90f); + } + + public float getServerYRot() { + return serverYRot; + } + + public void setServerYRot(float yRot) { + this.serverYRot0 = serverYRot; + this.serverYRot = yRot; + } + + public float getServerXRot() { + return serverXRot; + } + + public void setServerXRot(float xRot) { + this.serverXRot0 = serverXRot; + this.serverXRot = Mth.clamp(xRot, -90f, 90f); + } + + public float getServerYRot0() { + return serverYRot0; + } + + public float getServerXRot0() { + return serverXRot0; + } + + public float getServerDeltaYRot() { + return serverDeltaYRot; + } + + public void setServerDeltaYRot(float v) { + this.serverDeltaYRot = v; + } + + public boolean getSilentSyncRequired() { + return silentSyncRequired; + } + + public void setSilentSyncRequired(boolean v) { + this.silentSyncRequired = v; + } + + public void setMoveFix(boolean active, boolean f, boolean b, boolean l, boolean r) { + this.moveFixActive = active; + this.mfForward = f; + this.mfBack = b; + this.mfLeft = l; + this.mfRight = r; + } + + public boolean isMoveFixActive() { + return moveFixActive; + } + + public boolean mfForward() { + return mfForward; + } + + public boolean mfBack() { + return mfBack; + } + + public boolean mfLeft() { + return mfLeft; + } + + public boolean mfRight() { + return mfRight; + } + } + + public static class RotationRequestHandler { + private final List requests = new ArrayList<>(); + private final RotationStateHandler stateHandler; + private final RotationConfig config; + private String lastActiveRequestId = null; + + public RotationRequestHandler(RotationStateHandler stateHandler, RotationConfig config) { + this.stateHandler = stateHandler; + this.config = config; + } + + public void submit(RotationRequest request) { + if (request.rotationMode == RotationMode.SILENT) { + performSilent(request); + stateHandler.setSilentSyncRequired(true); + return; + } + requests.removeIf(r -> Objects.equals(r.id, request.id)); + requests.add(request); + requests.sort(Comparator.comparingInt(r -> -r.priority)); + } + + public boolean hasRequest(String id) { + return requests.stream().anyMatch(r -> r.id.equals(id)); + } + + public void cancel(String id) { + requests.removeIf(r -> r.id.equals(id)); + } + + public boolean isCompleted(String id) { + return isCompleted(id, config.getRotationThreshold()); + } + + public boolean isCompleted(String id, double threshold) { + if (config.getRotationMode() == RotationMode.SILENT && stateHandler.getSilentSyncRequired()) { + return true; + } + return requests.stream() + .filter(r -> r.id.equals(id)) + .findFirst() + .map(r -> { + float yawDiff = yRotDifference(r.targetYRot, stateHandler.getRotationYRot()); + float pitchDiff = r.targetXRot - stateHandler.getRotationXRot(); + return Math.abs(yawDiff) <= threshold && Math.abs(pitchDiff) <= threshold; + }) + .orElse(false); + } + + public RotationRequest getActiveRequest() { + return requests.isEmpty() ? null : requests.get(0); + } + + public void removeActiveRequest() { + if (!requests.isEmpty()) { + requests.remove(0); + } + } + + public void clear() { + requests.clear(); + lastActiveRequestId = null; + } + + public void clearLastActiveId() { + lastActiveRequestId = null; + } + + public String getLastActiveId() { + return lastActiveRequestId; + } + + public void setLastActiveId(String id) { + lastActiveRequestId = id; + } + + private void performSilent(RotationRequest req) { + if (mc().player == null || mc().getConnection() == null) { + return; + } + float targetYRot = req.targetYRot; + float targetXRot = Mth.clamp(req.targetXRot, -90f, 90f); + if (config.getJitterMode() == JitterMode.NORMAL) { + float minJitter = (float) (config.getRotationThreshold() / 4f); + float maxJitter = (float) (config.getRotationThreshold() / 2f); + float jY = minJitter + (float) (Math.random() * (maxJitter - minJitter)); + float jX = minJitter + (float) (Math.random() * (maxJitter - minJitter)); + jY *= Math.random() < 0.5 ? -1 : 1; + jX *= Math.random() < 0.5 ? -1 : 1; + targetYRot += jY; + targetXRot = Mth.clamp(targetXRot + jX, -90f, 90f); + } else if (config.getJitterMode() == JitterMode.GRIM) { + float f = (float) ((Math.random() * 2.0 - 1.0) * 0.001f); + targetXRot = Mth.clamp(targetXRot + f, -90f, 90f); + } + stateHandler.setServerYRot(targetYRot); + stateHandler.setServerXRot(targetXRot); + mc().getConnection().send(new ServerboundMovePlayerPacket.PosRot( + mc().player.getX(), + mc().player.getY(), + mc().player.getZ(), + targetYRot, + targetXRot, + mc().player.onGround(), + false + )); + } + } + + public static class RotationTickHandler { + private final RotationStateHandler stateHandler; + private final RotationRequestHandler requestHandler; + private final RotationConfig config; + private float currentYRotSpeed = 0f; + private float currentXRotSpeed = 0f; + private int ticksHolding = 0; + private boolean returning = false; + + public RotationTickHandler( + RotationStateHandler stateHandler, + RotationRequestHandler requestHandler, + RotationConfig config + ) { + this.stateHandler = stateHandler; + this.requestHandler = requestHandler; + this.config = config; + } + + public void onPreTick() { + if (mc().player == null) { + return; + } + stateHandler.updateRealRotation(mc().player.getYRot(), mc().player.getXRot()); + RotationRequest active = requestHandler.getActiveRequest(); + if (config.getRotationMode() == RotationMode.SILENT && stateHandler.getSilentSyncRequired()) { + requestHandler.clear(); + returning = false; + stateHandler.setSilentSyncRequired(false); + return; + } + if (active != null) { + processRequest(active); + } else if (returning) { + returnToRealRotation(); + } else { + idleReset(); + } + if (config.isMoveFixEnabled() && isRotating()) { + fixMovementForSpoof(); + } else { + stateHandler.setMoveFix(false, false, false, false, false); + } + } + + private void processRequest(RotationRequest request) { + if (!request.id.equals(requestHandler.getLastActiveId())) { + resetRotationToReal(); + requestHandler.setLastActiveId(request.id); + } + boolean updated = false; + if (request.shouldUpdate()) { + float oldY = request.targetYRot; + float oldX = request.targetXRot; + request.updateTarget(); + updated = Math.abs(oldY - request.targetYRot) > 0.001f + || Math.abs(oldX - request.targetXRot) > 0.001f; + if (updated) { + ticksHolding = 0; + } + } + float yRotDiff = yRotDifference(request.targetYRot, stateHandler.getRotationYRot()); + float xRotDiff = request.targetXRot - stateHandler.getRotationXRot(); + boolean reached = Math.abs(yRotDiff) <= config.getRotationThreshold() + && Math.abs(xRotDiff) <= config.getRotationThreshold(); + if (reached && !updated) { + if (++ticksHolding >= config.getHoldTicks()) { + requestHandler.removeActiveRequest(); + ticksHolding = 0; + returning = true; + } + } else { + ticksHolding = 0; + interpolateRotation(yRotDiff, xRotDiff); + } + } + + private void resetRotationToReal() { + if (mc().player == null) { + return; + } + float targetYRot = alignYRot(stateHandler.getRealYRot(), stateHandler.getRotationYRot()); + stateHandler.updateRealRotation(targetYRot, stateHandler.getRealXRot()); + mc().player.setYRot(targetYRot); + stateHandler.setRotationYRot(stateHandler.getRealYRot()); + stateHandler.setRotationXRot(stateHandler.getRealXRot()); + currentYRotSpeed = 0f; + currentXRotSpeed = 0f; + ticksHolding = 0; + returning = false; + } + + private void returnToRealRotation() { + if (mc().player == null) { + return; + } + float targetYRot = alignYRot(stateHandler.getRealYRot(), stateHandler.getRotationYRot()); + float yRotDiff = targetYRot - stateHandler.getRotationYRot(); + float xRotDiff = stateHandler.getRealXRot() - stateHandler.getRotationXRot(); + interpolateRotation(yRotDiff, xRotDiff); + boolean backReached = Math.abs(yRotDiff) <= config.getRotationThreshold() + && Math.abs(xRotDiff) <= config.getRotationThreshold(); + if (backReached) { + returning = false; + stateHandler.updateRealRotation(targetYRot, stateHandler.getRealXRot()); + mc().player.setYRot(targetYRot); + stateHandler.setRotationYRot(stateHandler.getRealYRot()); + stateHandler.setRotationXRot(stateHandler.getRealXRot()); + requestHandler.clearLastActiveId(); + } + } + + private void interpolateRotation(float yRotDiff, float xRotDiff) { + currentYRotSpeed = lerp(currentYRotSpeed, yRotDiff, (float) config.getRotationEase()); + currentXRotSpeed = lerp(currentXRotSpeed, xRotDiff, (float) config.getRotationEase()); + float yRotSpeed = Mth.clamp( + currentYRotSpeed, + (float) -config.getRotationSpeed(), + (float) config.getRotationSpeed() + ); + float xRotSpeed = Mth.clamp( + currentXRotSpeed, + (float) -config.getRotationSpeed(), + (float) config.getRotationSpeed() + ); + float newYRot = stateHandler.getRotationYRot() + yRotSpeed; + float newXRot = stateHandler.getRotationXRot() + xRotSpeed; + if (config.getJitterMode() == JitterMode.NORMAL) { + float minJitter = (float) (config.getRotationThreshold() / 4f); + float maxJitter = (float) (config.getRotationThreshold() / 2f); + float jY = minJitter + (float) (Math.random() * (maxJitter - minJitter)); + float jX = minJitter + (float) (Math.random() * (maxJitter - minJitter)); + jY *= Math.random() < 0.5 ? -1 : 1; + jX *= Math.random() < 0.5 ? -1 : 1; + newYRot += jY; + newXRot = Mth.clamp(newXRot + jX, -90f, 90f); + } else if (config.getJitterMode() == JitterMode.GRIM) { + float f = (float) ((Math.random() * 2.0 - 1.0) * 0.001f); + newXRot = Mth.clamp(newXRot + f, -90f, 90f); + } + stateHandler.setRotationYRot(newYRot); + stateHandler.setRotationXRot(newXRot); + stateHandler.setServerYRot(newYRot); + stateHandler.setServerXRot(newXRot); + stateHandler.setServerDeltaYRot(yRotSpeed); + } + + private void idleReset() { + requestHandler.clearLastActiveId(); + stateHandler.setRotationYRot(stateHandler.getRealYRot()); + stateHandler.setRotationXRot(stateHandler.getRealXRot()); + currentYRotSpeed = 0f; + currentXRotSpeed = 0f; + } + + private void fixMovementForSpoof() { + if (mc().player == null) { + return; + } + float realYRot = mc().player.getYRot(); + float spoofYRot = stateHandler.getRotationYRot(); + float delta = Mth.wrapDegrees(realYRot - spoofYRot); + boolean forward = mc().options.keyUp.isDown(); + boolean back = mc().options.keyDown.isDown(); + boolean left = mc().options.keyLeft.isDown(); + boolean right = mc().options.keyRight.isDown(); + float inputX = (right ? 1 : 0) - (left ? 1 : 0); + float inputZ = (forward ? 1 : 0) - (back ? 1 : 0); + if (inputX == 0 && inputZ == 0) { + stateHandler.setMoveFix(true, false, false, false, false); + return; + } + double moveAngle = Math.toDegrees(Math.atan2(inputX, inputZ)); + double finalAngle = moveAngle + delta; + int sector = (int) Math.round(finalAngle / 45.0) & 7; + boolean f = false; + boolean b = false; + boolean l = false; + boolean r = false; + switch (sector) { + case 0 -> f = true; + case 1 -> { + f = true; + r = true; + } + case 2 -> r = true; + case 3 -> { + b = true; + r = true; + } + case 4 -> b = true; + case 5 -> { + b = true; + l = true; + } + case 6 -> l = true; + case 7 -> { + f = true; + l = true; + } + } + stateHandler.setMoveFix(true, f, b, l, r); + } + + public boolean isRotating() { + return requestHandler.getActiveRequest() != null || returning; + } + } + + private static final class LegacyRotationRequest { + final float yaw; + final float pitch; + final int priority; + final long time; + + LegacyRotationRequest(float yaw, float pitch, int priority) { + this.yaw = yaw; + this.pitch = Mth.clamp(pitch, -90f, 90f); + this.priority = priority; + this.time = System.currentTimeMillis(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/ServerManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/ServerManager.java new file mode 100644 index 0000000..3aff6c5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/ServerManager.java @@ -0,0 +1,88 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.features.Feature; +import me.humanbeing.nolongerhuman.util.models.Timer; + +import java.util.Arrays; + +public class ServerManager + extends Feature { + private final float[] tpsCounts = new float[10]; + private final Timer timer = new Timer(); + private float tps = 20.0f; + private long lastUpdate = -1L; + private String serverBrand = ""; + + public void onPacketReceived() { + this.timer.reset(); + } + + public void update() { + float tps; + long currentTime = System.currentTimeMillis(); + if (this.lastUpdate == -1L) { + this.lastUpdate = currentTime; + return; + } + long timeDiff = currentTime - this.lastUpdate; + float tickTime = (float) timeDiff / 20.0f; + if (tickTime == 0.0f) { + tickTime = 50.0f; + } + if ((tps = 1000.0f / tickTime) > 20.0f) { + tps = 20.0f; + } + System.arraycopy(this.tpsCounts, 0, this.tpsCounts, 1, this.tpsCounts.length - 1); + this.tpsCounts[0] = tps; + double total = 0.0; + for (float f : this.tpsCounts) { + total += f; + } + if ((total /= this.tpsCounts.length) > 20.0) { + total = 20.0; + } + this.tps = (float) total; + this.lastUpdate = currentTime; + } + + @Override + public void reset() { + Arrays.fill(this.tpsCounts, 20.0f); + this.tps = 20.0f; + } + + public boolean isServerNotResponding() { + return this.timer.passedMs(2000); + } + + public long serverRespondingTime() { + return this.timer.getPassedTimeMs(); + } + + public float getTpsFactor() { + return 20.0f / this.tps; + } + + public float getTps() { + return this.tps; + } + + public String getServerBrand() { + return this.serverBrand; + } + + public void setServerBrand(String brand) { + this.serverBrand = brand; + } + + public int getPing() { + if (ServerManager.nullCheck()) { + return 0; + } + try { + return mc.getConnection().getPlayerInfo(mc.player.getGameProfile().name()).getLatency(); + } catch (Throwable e) { + return 0; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/manager/SpeedManager.java b/src/main/java/me/humanbeing/nolongerhuman/manager/SpeedManager.java new file mode 100644 index 0000000..b48ee6f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/manager/SpeedManager.java @@ -0,0 +1,47 @@ +package me.humanbeing.nolongerhuman.manager; + +import me.humanbeing.nolongerhuman.features.Feature; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; + +import java.util.ArrayList; +import java.util.List; + +public class SpeedManager extends Feature { + private static final int SPEED_NORMALIZATION = 20; + + private final List localSpeed = new ArrayList<>(); + private float localSpeedNormal = 0f; + + public void update() { + localSpeed.add(getCurrentSpeed(mc.player)); + while (localSpeed.size() > SPEED_NORMALIZATION) localSpeed.removeFirst(); + + localSpeedNormal = localSpeed.stream().reduce(0f, Float::sum) / localSpeed.size(); + } + + public double getSpeed(Player player) { + if (mc.player == player) return localSpeedNormal; + return getCurrentSpeed(player); + } + + public double getSpeedBpS(Player player) { + return getSpeed(player) * 20; + } + + public double getSpeedKmH(Player player) { + return getSpeedBpS(player) * 3.6; + } + + public float getCurrentSpeed(Entity entity) { + Entity vehicle = entity.getVehicle(); + double distTraveledX = entity.getX() - entity.xo; + double distTraveledZ = entity.getZ() - entity.zo; + if (vehicle != null) { + distTraveledX = vehicle.getX() - vehicle.xo; + distTraveledZ = vehicle.getZ() - vehicle.zo; + } + + return (float) Math.hypot(distTraveledX, distTraveledZ); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/ChinaGUINoBlurMixin.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/ChinaGUINoBlurMixin.java new file mode 100644 index 0000000..be8d877 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/ChinaGUINoBlurMixin.java @@ -0,0 +1,72 @@ +package me.humanbeing.nolongerhuman.mixin; + +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +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(Screen.class) +public abstract class ChinaGUINoBlurMixin { + + @Inject( + method = "renderBackground(Lnet/minecraft/client/gui/GuiGraphics;IIF)V", + at = @At("HEAD"), + cancellable = true + ) + private void china$cancelBackground(GuiGraphics context, int mouseX, int mouseY, float delta, CallbackInfo ci) { + if ((Object) this instanceof ChinaGUI) { + ci.cancel(); + } + } + + @Inject( + method = "renderTransparentBackground", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void china$cancelTransparentBackground(GuiGraphics context, CallbackInfo ci) { + if ((Object) this instanceof ChinaGUI) { + ci.cancel(); + } + } + + @Inject( + method = "renderMenuBackground(Lnet/minecraft/client/gui/GuiGraphics;)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void china$cancelMenuBackground(GuiGraphics context, CallbackInfo ci) { + if ((Object) this instanceof ChinaGUI) { + ci.cancel(); + } + } + + @Inject( + method = "renderMenuBackground(Lnet/minecraft/client/gui/GuiGraphics;IIII)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void china$cancelMenuBackgroundArea(GuiGraphics context, int x1, int y1, int x2, int y2, CallbackInfo ci) { + if ((Object) this instanceof ChinaGUI) { + ci.cancel(); + } + } + + @Inject( + method = "renderBlurredBackground", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void china$cancelBlurredBackground(GuiGraphics context, CallbackInfo ci) { + if ((Object) this instanceof ChinaGUI) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/accessor/IMultiPlayerGameMode.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/accessor/IMultiPlayerGameMode.java new file mode 100644 index 0000000..15cdb97 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/accessor/IMultiPlayerGameMode.java @@ -0,0 +1,21 @@ +package me.humanbeing.nolongerhuman.mixin.accessor; + +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.core.BlockPos; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(MultiPlayerGameMode.class) +public interface IMultiPlayerGameMode { + @Accessor("destroyProgress") + float nolongerhuman$getDestroyProgress(); + + @Accessor("destroyProgress") + void nolongerhuman$setDestroyProgress(float progress); + + @Accessor("destroyBlockPos") + BlockPos nolongerhuman$getDestroyBlockPos(); + + @Accessor("destroyBlockPos") + void nolongerhuman$setDestroyBlockPos(BlockPos pos); +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/accessor/MouseHandlerAccessor.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/accessor/MouseHandlerAccessor.java new file mode 100644 index 0000000..3ab46a4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/accessor/MouseHandlerAccessor.java @@ -0,0 +1,12 @@ +package me.humanbeing.nolongerhuman.mixin.accessor; + +import net.minecraft.client.MouseHandler; +import net.minecraft.client.input.MouseButtonInfo; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(MouseHandler.class) +public interface MouseHandlerAccessor { + @Invoker("onButton") + void nolongerhuman$invokeOnButton(long window, MouseButtonInfo input, int action); +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/effect/MixinMobEffectInstance.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/effect/MixinMobEffectInstance.java new file mode 100644 index 0000000..f9e6271 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/effect/MixinMobEffectInstance.java @@ -0,0 +1,23 @@ +package me.humanbeing.nolongerhuman.mixin.effect; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.world.effect.MobEffectInstance; +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(MobEffectInstance.class) +public class MixinMobEffectInstance { + + @Inject( + method = "showIcon", + at = @At("HEAD"), + cancellable = true + ) + private void chinaware$showIcon(CallbackInfoReturnable cir) { + if (NoRender.shouldCancelPotionIcons()) { + cir.setReturnValue(false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinClientPlayerEntity.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinClientPlayerEntity.java new file mode 100644 index 0000000..d9d4749 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinClientPlayerEntity.java @@ -0,0 +1,30 @@ +package me.humanbeing.nolongerhuman.mixin.entity; + +import me.humanbeing.nolongerhuman.event.Stage; +import me.humanbeing.nolongerhuman.event.impl.entity.player.TickEvent; +import me.humanbeing.nolongerhuman.event.impl.entity.player.UpdateWalkingPlayerEvent; +import net.minecraft.client.player.LocalPlayer; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(LocalPlayer.class) +public class MixinClientPlayerEntity { + @Inject(method = "tick", at = @At("TAIL")) + private void tickHook(CallbackInfo ci) { + EVENT_BUS.post(new TickEvent()); + } + + @Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/AbstractClientPlayer;tick()V", shift = At.Shift.AFTER)) + private void tickHook2(CallbackInfo ci) { + EVENT_BUS.post(new UpdateWalkingPlayerEvent(Stage.PRE)); + } + + @Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;sendPosition()V", shift = At.Shift.AFTER)) + private void tickHook3(CallbackInfo ci) { + EVENT_BUS.post(new UpdateWalkingPlayerEvent(Stage.POST)); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinEntity.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinEntity.java new file mode 100644 index 0000000..f87794e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinEntity.java @@ -0,0 +1,53 @@ +package me.humanbeing.nolongerhuman.mixin.entity; + +import me.humanbeing.nolongerhuman.features.modules.player.Velocity; +import net.minecraft.client.Minecraft; +import net.minecraft.world.entity.Entity; +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(Entity.class) +public abstract class MixinEntity { + + @Inject( + method = "push(DDD)V", + at = @At("HEAD"), + cancellable = true + ) + private void nolongerhuman$pushVelocity(double x, double y, double z, CallbackInfo ci) { + Minecraft mc = Minecraft.getInstance(); + + if (mc.player == null) { + return; + } + + if ((Object) this != mc.player) { + return; + } + + if (Velocity.shouldCancelPush(mc.player)) { + ci.cancel(); + } + } + + @Inject( + method = "push(Lnet/minecraft/world/entity/Entity;)V", + at = @At("HEAD"), + cancellable = true + ) + private void nolongerhuman$pushEntity(Entity entity, CallbackInfo ci) { + Minecraft mc = Minecraft.getInstance(); + + if (mc.player == null) { + return; + } + + Entity self = (Entity) (Object) this; + + if (Velocity.shouldCancelCollision(self, entity)) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinEntityNoRenderCrystals.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinEntityNoRenderCrystals.java new file mode 100644 index 0000000..a2183d9 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinEntityNoRenderCrystals.java @@ -0,0 +1,34 @@ +package me.humanbeing.nolongerhuman.mixin.entity; + +import me.humanbeing.nolongerhuman.features.modules.render.CrystalChams; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +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(Entity.class) +public class MixinEntityNoRenderCrystals { + @Inject( + method = "shouldRender", + at = @At("HEAD"), + cancellable = true + ) + private void nolongerhuman$shouldRenderCrystalChamsOnly( + double cameraX, + double cameraY, + double cameraZ, + CallbackInfoReturnable cir + ) { + Entity entity = (Entity) (Object) this; + + if (!(entity instanceof EndCrystal crystal)) { + return; + } + + if (CrystalChams.shouldCancelVanillaCrystalRender(crystal)) { + cir.setReturnValue(false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinLivingEntity.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinLivingEntity.java new file mode 100644 index 0000000..59ea0a5 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinLivingEntity.java @@ -0,0 +1,55 @@ +package me.humanbeing.nolongerhuman.mixin.entity; + +import me.humanbeing.nolongerhuman.features.modules.movement.AntiClimb; +import me.humanbeing.nolongerhuman.features.modules.player.Velocity; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.LivingEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(LivingEntity.class) +public abstract class MixinLivingEntity { + @Inject( + method = "knockback(DDD)V", + at = @At("HEAD"), + cancellable = true + ) + private void nolongerhuman$knockback( + double strength, + double x, + double z, + CallbackInfo ci + ) { + Minecraft mc = Minecraft.getInstance(); + + if (mc.player == null) { + return; + } + + if ((Object) this != mc.player) { + return; + } + + if (Velocity.shouldCancelVelocity()) { + ci.cancel(); + } + } + + @Inject( + method = "onClimbable", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$onClimbable(CallbackInfoReturnable cir) { + Object self = this; + + if (self instanceof LocalPlayer player && AntiClimb.shouldCancelClimb(player)) { + cir.setReturnValue(false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinLivingEntityNoRenderArmor.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinLivingEntityNoRenderArmor.java new file mode 100644 index 0000000..bf3ea38 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/entity/MixinLivingEntityNoRenderArmor.java @@ -0,0 +1,35 @@ +package me.humanbeing.nolongerhuman.mixin.entity; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +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(LivingEntity.class) +public class MixinLivingEntityNoRenderArmor { + + @Inject( + method = "getItemBySlot", + at = @At("HEAD"), + cancellable = true + ) + private void chinaware$getItemBySlot( + EquipmentSlot slot, + CallbackInfoReturnable cir + ) { + if (!NoRender.shouldCancelArmor()) { + return; + } + + if (slot == EquipmentSlot.HEAD + || slot == EquipmentSlot.CHEST + || slot == EquipmentSlot.LEGS + || slot == EquipmentSlot.FEET) { + cir.setReturnValue(ItemStack.EMPTY); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/input/MixinKeyboardHandler.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/input/MixinKeyboardHandler.java new file mode 100644 index 0000000..6237815 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/input/MixinKeyboardHandler.java @@ -0,0 +1,56 @@ +package me.humanbeing.nolongerhuman.mixin.input; + +import me.humanbeing.nolongerhuman.event.impl.input.KeyInputEvent; +import me.humanbeing.nolongerhuman.event.impl.input.UnfilteredKeyInputEvent; +import net.minecraft.client.KeyboardHandler; +import net.minecraft.client.input.KeyEvent; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(KeyboardHandler.class) +public class MixinKeyboardHandler { + @Inject( + method = "keyPress", + at = @At("HEAD"), + cancellable = true + ) + private void nolongerhuman$unfilteredKeyPress( + long window, + int action, + KeyEvent input, + CallbackInfo ci + ) { + if (EVENT_BUS.post(new UnfilteredKeyInputEvent( + input.key(), + input.scancode(), + action, + input.modifiers() + ))) { + ci.cancel(); + } + } + + @Inject( + method = "keyPress", + at = @At("TAIL"), + cancellable = true + ) + private void keyPress( + long window, + int action, + KeyEvent input, + CallbackInfo ci + ) { + if (action != 1) { + return; + } + + if (EVENT_BUS.post(new KeyInputEvent(input.key()))) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/input/MixinMouseHandler.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/input/MixinMouseHandler.java new file mode 100644 index 0000000..2f1c8d0 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/input/MixinMouseHandler.java @@ -0,0 +1,88 @@ +package me.humanbeing.nolongerhuman.mixin.input; + +import me.humanbeing.nolongerhuman.event.impl.input.MouseInputEvent; +import me.humanbeing.nolongerhuman.event.impl.input.UnfilteredMouseInputEvent; +import me.humanbeing.nolongerhuman.features.modules.render.Freecam; +import net.minecraft.client.Minecraft; +import net.minecraft.client.MouseHandler; +import net.minecraft.client.input.MouseButtonInfo; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(MouseHandler.class) +public class MixinMouseHandler { + @Shadow + @Final + private Minecraft minecraft; + + @Shadow + private double accumulatedDX; + + @Shadow + private double accumulatedDY; + + @Inject( + method = "onButton", + at = @At("HEAD"), + cancellable = true + ) + private void nolongerhuman$unfilteredMouseButton( + long window, + MouseButtonInfo input, + int action, + CallbackInfo ci + ) { + if (EVENT_BUS.post(new UnfilteredMouseInputEvent( + input.button(), + action, + input.modifiers() + ))) { + ci.cancel(); + } + } + + @Inject( + method = "onButton", + at = @At("HEAD"), + cancellable = true + ) + private void onButton( + long window, + MouseButtonInfo input, + int action, + CallbackInfo ci + ) { + if (EVENT_BUS.post(new MouseInputEvent(input.button(), action))) { + ci.cancel(); + } + } + + @Inject( + method = "turnPlayer", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$turnPlayer(CallbackInfo ci) { + if (Freecam.shouldHandleCamera() && minecraft.player != null) { + double sensitivity = minecraft.options.sensitivity().get() * 0.6D + 0.2D; + double multiplier = sensitivity * sensitivity * sensitivity * 8.0D; + + Freecam.handleMouse( + accumulatedDX * multiplier, + accumulatedDY * multiplier + ); + + accumulatedDX = 0.0D; + accumulatedDY = 0.0D; + + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/network/MixinClientPacketListener.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/network/MixinClientPacketListener.java new file mode 100644 index 0000000..792c87c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/network/MixinClientPacketListener.java @@ -0,0 +1,101 @@ +package me.humanbeing.nolongerhuman.mixin.network; + +import me.humanbeing.nolongerhuman.event.impl.network.ChatEvent; +import me.humanbeing.nolongerhuman.event.impl.network.ChatSendEvent; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import me.humanbeing.nolongerhuman.features.modules.player.AuraFarmer; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.protocol.game.ClientboundExplodePacket; +import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(ClientPacketListener.class) +public abstract class MixinClientPacketListener { + + @Shadow + public abstract void sendChat(String content); + + @Unique + private boolean nolongerhuman$handlingModifiedChat = false; + + @Inject(method = "sendChat", at = @At("HEAD"), cancellable = true) + private void nolongerhumanl$sendChat(String content, CallbackInfo ci) { + + if (!nolongerhuman$handlingModifiedChat) { + ChatSendEvent sendEvent = new ChatSendEvent(content); + + if (EVENT_BUS.post(sendEvent) || sendEvent.isCancelled()) { + ci.cancel(); + return; + } + + String newContent = sendEvent.getMessage(); + + if (newContent == null || newContent.isBlank()) { + ci.cancel(); + return; + } + + if (!newContent.equals(content)) { + nolongerhuman$handlingModifiedChat = true; + + try { + this.sendChat(newContent); + } finally { + nolongerhuman$handlingModifiedChat = false; + } + + ci.cancel(); + return; + } + } + + + if (!nolongerhuman$handlingModifiedChat && AuraFarmer.shouldModifyChat(content)) { + String modified = AuraFarmer.modifyChat(content); + + nolongerhuman$handlingModifiedChat = true; + + try { + this.sendChat(modified); + } finally { + nolongerhuman$handlingModifiedChat = false; + } + + ci.cancel(); + return; + } + + + ChatEvent event = new ChatEvent(content); + + if (EVENT_BUS.post(event) || event.isCancelled()) { + ci.cancel(); + } + } + + @Inject(method = "handleSetEntityMotion", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$handleSetEntityMotion(ClientboundSetEntityMotionPacket packet, CallbackInfo ci) { + PacketEvent.Receive event = new PacketEvent.Receive(packet); + + if (EVENT_BUS.post(event) || event.isCancelled()) { + ci.cancel(); + } + } + + @Inject(method = "handleExplosion", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$handleExplosion(ClientboundExplodePacket packet, CallbackInfo ci) { + PacketEvent.Receive event = new PacketEvent.Receive(packet); + + if (EVENT_BUS.post(event) || event.isCancelled()) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/network/MixinConnection.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/network/MixinConnection.java new file mode 100644 index 0000000..84b9515 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/network/MixinConnection.java @@ -0,0 +1,68 @@ +package me.humanbeing.nolongerhuman.mixin.network; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import me.humanbeing.nolongerhuman.event.impl.network.PacketEvent; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(Connection.class) +public class MixinConnection { + @Shadow + private Channel channel; + + @Shadow + @Final + private PacketFlow receiving; + + @Inject(method = "channelRead0", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$channelRead0(ChannelHandlerContext context, Packet packet, CallbackInfo ci) { + if (packet == null) { + return; + } + + if (this.channel == null || !this.channel.isOpen()) { + return; + } + + PacketEvent.Receive event = new PacketEvent.Receive(packet); + + try { + if (EVENT_BUS.post(event) || event.isCancelled()) { + ci.cancel(); + } + } catch (Throwable ignored) { + } + } + + @Inject(method = "sendPacket", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$sendPacket(Packet packet, ChannelFutureListener listener, boolean flush, CallbackInfo ci) { + if (packet == null) { + return; + } + + + if (this.receiving != PacketFlow.CLIENTBOUND) { + return; + } + + PacketEvent.Send event = new PacketEvent.Send(packet); + + try { + if (EVENT_BUS.post(event) || event.isCancelled()) { + ci.cancel(); + } + } catch (Throwable ignored) { + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinMultiPlayerGameMode.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinMultiPlayerGameMode.java new file mode 100644 index 0000000..523eb21 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinMultiPlayerGameMode.java @@ -0,0 +1,25 @@ +package me.humanbeing.nolongerhuman.mixin.player; + +import me.humanbeing.nolongerhuman.event.impl.player.AttackBlockEvent; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(MultiPlayerGameMode.class) +public class MixinMultiPlayerGameMode { + @Inject(method = "startDestroyBlock", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$startDestroyBlock(BlockPos pos, Direction direction, CallbackInfoReturnable cir) { + AttackBlockEvent event = new AttackBlockEvent(pos, direction); + + if (EVENT_BUS.post(event) || event.isCancelled()) { + cir.setReturnValue(false); + cir.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinNoInteractGameMode.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinNoInteractGameMode.java new file mode 100644 index 0000000..d84d734 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinNoInteractGameMode.java @@ -0,0 +1,28 @@ +package me.humanbeing.nolongerhuman.mixin.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.player.NoInteract; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.phys.BlockHitResult; +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(MultiPlayerGameMode.class) +public class MixinNoInteractGameMode { + @Inject(method = "useItemOn", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$useItemOn(LocalPlayer player, InteractionHand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) { + if (nolongerhuman.moduleManager == null) return; + + NoInteract noInteract = nolongerhuman.moduleManager.getModuleByClass(NoInteract.class); + + if (noInteract != null && noInteract.shouldDisableInteract()) { + cir.setReturnValue(InteractionResult.PASS); + cir.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinNoInteractPlayer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinNoInteractPlayer.java new file mode 100644 index 0000000..df982c1 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/player/MixinNoInteractPlayer.java @@ -0,0 +1,24 @@ +package me.humanbeing.nolongerhuman.mixin.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.player.NoInteract; +import net.minecraft.world.entity.player.Player; +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(Player.class) +public class MixinNoInteractPlayer { + @Inject(method = "isSecondaryUseActive", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$isSecondaryUseActive(CallbackInfoReturnable cir) { + if (nolongerhuman.moduleManager == null) return; + + NoInteract noInteract = nolongerhuman.moduleManager.getModuleByClass(NoInteract.class); + + if (noInteract != null && noInteract.shouldSneakInteract()) { + cir.setReturnValue(true); + cir.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/ChatComponentMixin.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/ChatComponentMixin.java new file mode 100644 index 0000000..8397654 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/ChatComponentMixin.java @@ -0,0 +1,29 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.util.render.FontManager; +import net.minecraft.client.gui.components.ChatComponent; +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(ChatComponent.class) +public class ChatComponentMixin { + @Inject( + method = "render", + at = @At("HEAD"), + require = 0 + ) + private void nolongerhuman$beginChatRender(CallbackInfo ci) { + FontManager.beginChatRender(); + } + + @Inject( + method = "render", + at = @At("RETURN"), + require = 0 + ) + private void nolongerhuman$endChatRender(CallbackInfo ci) { + FontManager.endChatRender(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/FontMixin.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/FontMixin.java new file mode 100644 index 0000000..1bd1b36 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/FontMixin.java @@ -0,0 +1,56 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.util.render.FontManager; +import net.minecraft.client.gui.Font; +import net.minecraft.util.FormattedCharSequence; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +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(Font.class) +public class FontMixin { + @Mutable + @Final + @Shadow + public int lineHeight; + + @Inject( + method = "width(Ljava/lang/String;)I", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$widthString( + String text, + CallbackInfoReturnable cir + ) { + if (!FontManager.isEnabled()) { + return; + } + + this.lineHeight = FontManager.lineHeight(); + cir.setReturnValue(FontManager.width(text)); + } + + @Inject( + method = "width(Lnet/minecraft/util/FormattedCharSequence;)I", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$widthFormattedSequence( + FormattedCharSequence text, + CallbackInfoReturnable cir + ) { + if (!FontManager.isEnabled()) { + return; + } + + this.lineHeight = FontManager.lineHeight(); + cir.setReturnValue(FontManager.width(text)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinBossHealthOverlay.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinBossHealthOverlay.java new file mode 100644 index 0000000..600e1fc --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinBossHealthOverlay.java @@ -0,0 +1,25 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.BossHealthOverlay; +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(BossHealthOverlay.class) +public class MixinBossHealthOverlay { + + @Inject( + method = "render", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void chinaware$render(GuiGraphics context, CallbackInfo ci) { + if (NoRender.shouldCancelBossBars()) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinCamera.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinCamera.java new file mode 100644 index 0000000..3c0aed6 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinCamera.java @@ -0,0 +1,31 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.Freecam; +import net.minecraft.client.Camera; +import net.minecraft.world.phys.Vec3; +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(Camera.class) +public abstract class MixinCamera { + @Shadow + protected abstract void setPosition(Vec3 pos); + + @Shadow + protected abstract void setRotation(float yRot, float xRot); + + @Inject( + method = "setup", + at = @At("TAIL"), + require = 0 + ) + private void nolongerhuman$setupFreecam(CallbackInfo ci) { + if (Freecam.shouldHandleCamera()) { + setPosition(Freecam.getPosition(1.0F)); + setRotation(Freecam.getYaw(), Freecam.getPitch()); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinChatComponent.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinChatComponent.java new file mode 100644 index 0000000..cc44758 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinChatComponent.java @@ -0,0 +1,33 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.ducks.render.IChatComponent; +import net.minecraft.client.GuiMessage; +import net.minecraft.client.gui.components.ChatComponent; +import net.minecraft.network.chat.MessageSignature; + +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.List; + +@Mixin(ChatComponent.class) +public abstract class MixinChatComponent implements IChatComponent { + @Final @Shadow + private List allMessages; + + @Shadow + private void refreshTrimmedMessages() {} + + @Override + public void nolongerhuman$addMessage(GuiMessage message) { + this.allMessages.addFirst(message); + this.refreshTrimmedMessages(); + } + + @Override + public void nolongerhuman$removeMessage(MessageSignature signature) { + this.allMessages.removeIf(message -> signature.equals(message.signature())); + this.refreshTrimmedMessages(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinDeltaTrackerTimer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinDeltaTrackerTimer.java new file mode 100644 index 0000000..3e4861e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinDeltaTrackerTimer.java @@ -0,0 +1,21 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import net.minecraft.client.DeltaTracker; +import org.objectweb.asm.Opcodes; +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(DeltaTracker.Timer.class) +public class MixinDeltaTrackerTimer { + @Shadow + private float deltaTicks; + + @Inject(method = "advanceGameTime(J)I", at = @At(value = "FIELD", target = "Lnet/minecraft/client/DeltaTracker$Timer;lastMs:J", opcode = Opcodes.PUTFIELD)) + public void advanceGameTime(long timeMillis, CallbackInfoReturnable cir) { + this.deltaTicks *= nolongerhuman.TIMER; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinEntity.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinEntity.java new file mode 100644 index 0000000..2901627 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinEntity.java @@ -0,0 +1,60 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.world.entity.Entity; +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(Entity.class) +public class MixinEntity { + + @Inject( + method = "isCurrentlyGlowing", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$isCurrentlyGlowing(CallbackInfoReturnable cir) { + if (NoRender.shouldCancelGlowing()) { + cir.setReturnValue(false); + } + } + + @Inject( + method = "isOnFire", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$isOnFire(CallbackInfoReturnable cir) { + if (NoRender.shouldCancelEntityFire()) { + cir.setReturnValue(false); + } + } + + @Inject( + method = "isInvisible", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$isInvisible(CallbackInfoReturnable cir) { + if (NoRender.shouldRenderInvisibleEntities()) { + cir.setReturnValue(false); + } + } + + @Inject( + method = "isInvisibleTo", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhumanl$isInvisibleTo(CallbackInfoReturnable cir) { + if (NoRender.shouldRenderInvisibleEntities()) { + cir.setReturnValue(false); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinEntityRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinEntityRenderer.java new file mode 100644 index 0000000..953785c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinEntityRenderer.java @@ -0,0 +1,1205 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import me.humanbeing.nolongerhuman.features.modules.render.Nametags; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.entity.EntityRenderer; +import net.minecraft.client.renderer.entity.state.EntityRenderState; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.client.renderer.rendertype.RenderTypes; +import net.minecraft.client.renderer.state.CameraRenderState; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.phys.Vec3; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; + +@Mixin(EntityRenderer.class) +public abstract class MixinEntityRenderer { + @Unique + private static final Map nolongerhuman$entitiesByState = + Collections.synchronizedMap(new WeakHashMap<>()); + + @Unique + private static final Map nolongerhuman$iconsSubmittedByState = + Collections.synchronizedMap(new WeakHashMap<>()); + + @Unique + private static final EquipmentSlot[] nolongerhuman$ARMOR_ORDER = { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + + @Unique + private static final int nolongerhuman$ARMOR_ITEM_SPACING = 20; + + @Unique + private static final int nolongerhuman$ARMOR_ITEM_SIZE = 16; + + @Unique + private static final int nolongerhuman$BACKGROUND_PADDING_X = 4; + + @Unique + private static final int nolongerhuman$BACKGROUND_PADDING_Y = 3; + + @Unique + private static final int nolongerhuman$BACKGROUND_BORDER_THICKNESS = 1; + + @Unique + private static final int nolongerhuman$BOUNDS_VALID = 0; + + @Unique + private static final int nolongerhuman$BOUNDS_MIN_X = 1; + + @Unique + private static final int nolongerhuman$BOUNDS_MIN_Y = 2; + + @Unique + private static final int nolongerhuman$BOUNDS_MAX_X = 3; + + @Unique + private static final int nolongerhuman$BOUNDS_MAX_Y = 4; + + @Unique + private static final int nolongerhuman$NAMETAG_LIGHT = 0xF000F0; + + @Unique + private static final int nolongerhuman$NAMETAG_RENDER_ORDER = Integer.MAX_VALUE - 1000; + + @Unique + private static final float nolongerhuman$NAMETAG_BASE_SCALE = 0.025F; + + @Unique + private static Method nolongerhuman$itemStateSubmitMethod; + + @Unique + private static boolean nolongerhuman$lookedUpItemStateSubmitMethod; + + @Unique + private static Field nolongerhuman$itemStateLayerCountField; + + @Unique + private static Field nolongerhuman$itemStateLayersField; + + @Unique + private static Field nolongerhuman$itemLayerQuadsField; + + @Unique + private static Field nolongerhuman$itemLayerRenderTypeField; + + @Unique + private static Field nolongerhuman$itemLayerFoilTypeField; + + @Unique + private static Field nolongerhuman$itemLayerTintLayersField; + + @Unique + private static Method nolongerhuman$itemLayerSetRenderTypeMethod; + + @Unique + private static Method nolongerhuman$itemLayerSetUsesBlockLightMethod; + + @Unique + private static Method nolongerhuman$orderedSubmitItemMethod; + + @Unique + private static boolean nolongerhuman$lookedUpItemLayerFields; + + @Inject( + method = "extractRenderState(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/client/renderer/entity/state/EntityRenderState;F)V", + at = @At("TAIL") + ) + private void nolongerhuman$extractRenderState( + Entity entity, + EntityRenderState state, + float partialTick, + CallbackInfo ci + ) { + nolongerhuman$entitiesByState.put(state, entity); + nolongerhuman$iconsSubmittedByState.remove(state); + + if (!Nametags.shouldRenderNametag(entity)) { + return; + } + + state.nameTagAttachment = Nametags.getNameTagAttachment(entity, partialTick); + state.nameTag = null; + } + + @Inject( + method = "submit(Lnet/minecraft/client/renderer/entity/state/EntityRenderState;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/SubmitNodeCollector;Lnet/minecraft/client/renderer/state/CameraRenderState;)V", + at = @At("TAIL") + ) + private void nolongerhuman$submitCustomNametag( + EntityRenderState state, + PoseStack poseStack, + SubmitNodeCollector submitNodeCollector, + CameraRenderState cameraRenderState, + CallbackInfo ci + ) { + Entity entity = nolongerhuman$entitiesByState.get(state); + + if (!Nametags.shouldRenderNametag(entity)) { + return; + } + + Vec3 attachment = state.nameTagAttachment; + + if (attachment == null) { + return; + } + + Component armorText = Nametags.getArmorText(entity); + Component mainText = Nametags.getMainText(entity); + float scale = Nametags.getNametagScale(entity, state.distanceToCameraSq); + + nolongerhuman$submitNametagBillboard( + entity, + poseStack, + submitNodeCollector, + state, + attachment, + armorText, + mainText, + scale + ); + } + + @Unique + private void nolongerhuman$submitNametagBillboard( + Entity entity, + PoseStack poseStack, + SubmitNodeCollector submitNodeCollector, + EntityRenderState state, + Vec3 attachment, + Component armorText, + Component mainText, + float scale + ) { + Minecraft minecraft = Minecraft.getInstance(); + + if (minecraft.player == null || minecraft.level == null) { + return; + } + + float rootScale = nolongerhuman$getRootNametagScale(scale); + + OrderedSubmitNodeCollector nametagCollector = + submitNodeCollector.order(nolongerhuman$NAMETAG_RENDER_ORDER); + + poseStack.pushPose(); + + poseStack.translate( + attachment.x, + attachment.y, + attachment.z + ); + + poseStack.mulPose(minecraft.gameRenderer.getMainCamera().rotation()); + + poseStack.scale( + rootScale, + -rootScale, + rootScale + ); + + int[] bounds = nolongerhuman$calculateBounds( + entity, + minecraft, + armorText, + mainText + ); + + if (bounds[nolongerhuman$BOUNDS_VALID] != 0 && Nametags.shouldRenderBackground()) { + nolongerhuman$submitBackgroundRectangle( + nametagCollector, + poseStack, + bounds, + nolongerhuman$NAMETAG_LIGHT + ); + } + + nolongerhuman$submitArmorOverlayInCurrentPose( + entity, + minecraft, + poseStack, + submitNodeCollector, + nametagCollector, + state + ); + + if (armorText != null) { + nolongerhuman$submitComponentTextCentered( + minecraft, + nametagCollector, + poseStack, + armorText, + Nametags.getArmorTextYOffset(), + nolongerhuman$NAMETAG_LIGHT + ); + } + + if (mainText != null) { + nolongerhuman$submitComponentTextCentered( + minecraft, + nametagCollector, + poseStack, + mainText, + Nametags.getMainYOffset(), + nolongerhuman$NAMETAG_LIGHT + ); + } + + poseStack.popPose(); + } + + @Unique + private float nolongerhuman$getRootNametagScale(float scale) { + if (scale <= 0.0F || Float.isNaN(scale) || Float.isInfinite(scale)) { + scale = 1.0F; + } + + return nolongerhuman$NAMETAG_BASE_SCALE * scale; + } + + @Unique + private int[] nolongerhuman$calculateBounds( + Entity entity, + Minecraft minecraft, + Component armorText, + Component mainText + ) { + int[] bounds = new int[5]; + + if (armorText != null) { + int width = minecraft.font.width(armorText); + + nolongerhuman$includeCenteredText( + bounds, + width, + Nametags.getArmorTextYOffset(), + minecraft.font.lineHeight + ); + } + + if (mainText != null) { + int width = minecraft.font.width(mainText); + + nolongerhuman$includeCenteredText( + bounds, + width, + Nametags.getMainYOffset(), + minecraft.font.lineHeight + ); + } + + if (entity instanceof Player player) { + boolean renderIcons = Nametags.shouldRenderArmorIcons(entity); + boolean renderDurability = Nametags.shouldRenderArmorDurability(); + + if (renderIcons || renderDurability) { + int visibleArmor = nolongerhuman$getVisibleArmorCount(player); + + if (visibleArmor > 0) { + int iconTotalWidth = visibleArmor * nolongerhuman$ARMOR_ITEM_SPACING - 4; + int iconStartX = -iconTotalWidth / 2; + int itemY = Nametags.getMainYOffset() + - nolongerhuman$ARMOR_ITEM_SIZE + - Nametags.getArmorNameGap(); + int durabilityY = itemY + nolongerhuman$ARMOR_ITEM_SIZE + 1; + + int visibleIndex = 0; + + for (EquipmentSlot slot : nolongerhuman$ARMOR_ORDER) { + ItemStack stack = player.getItemBySlot(slot); + + if (stack.isEmpty()) { + continue; + } + + int itemX = iconStartX + visibleIndex * nolongerhuman$ARMOR_ITEM_SPACING; + int iconCenterX = itemX + nolongerhuman$ARMOR_ITEM_SIZE / 2; + + if (renderIcons) { + nolongerhuman$includeBounds( + bounds, + itemX, + itemY, + itemX + nolongerhuman$ARMOR_ITEM_SIZE, + itemY + nolongerhuman$ARMOR_ITEM_SIZE + ); + } + + if (renderIcons && Nametags.shouldRenderArmorText()) { + String pieceText = Nametags.getArmorPieceText(stack, slot); + + if (!pieceText.isEmpty()) { + int textWidth = minecraft.font.width(pieceText); + int textX = iconCenterX - textWidth / 2; + int textY = itemY + 4; + + nolongerhuman$includeBounds( + bounds, + textX, + textY, + textX + textWidth, + textY + minecraft.font.lineHeight + ); + } + } + + if (renderDurability) { + String pieceDurabilityText = Nametags.getArmorDurabilityText(stack); + + if (!pieceDurabilityText.isEmpty()) { + int durabilityX = nolongerhuman$getArmorDurabilityTextX( + minecraft, + player, + slot, + pieceDurabilityText + ); + + int textWidth = minecraft.font.width(pieceDurabilityText); + + nolongerhuman$includeBounds( + bounds, + durabilityX, + durabilityY, + durabilityX + textWidth, + durabilityY + minecraft.font.lineHeight + ); + } + } + + visibleIndex++; + } + } + } + } + + return bounds; + } + + @Unique + private void nolongerhuman$includeCenteredText( + int[] bounds, + int width, + int y, + int height + ) { + int x = -width / 2; + + nolongerhuman$includeBounds( + bounds, + x, + y, + x + width, + y + height + ); + } + + @Unique + private void nolongerhuman$includeBounds( + int[] bounds, + int minX, + int minY, + int maxX, + int maxY + ) { + if (bounds[nolongerhuman$BOUNDS_VALID] == 0) { + bounds[nolongerhuman$BOUNDS_VALID] = 1; + bounds[nolongerhuman$BOUNDS_MIN_X] = minX; + bounds[nolongerhuman$BOUNDS_MIN_Y] = minY; + bounds[nolongerhuman$BOUNDS_MAX_X] = maxX; + bounds[nolongerhuman$BOUNDS_MAX_Y] = maxY; + return; + } + + bounds[nolongerhuman$BOUNDS_MIN_X] = Math.min(bounds[nolongerhuman$BOUNDS_MIN_X], minX); + bounds[nolongerhuman$BOUNDS_MIN_Y] = Math.min(bounds[nolongerhuman$BOUNDS_MIN_Y], minY); + bounds[nolongerhuman$BOUNDS_MAX_X] = Math.max(bounds[nolongerhuman$BOUNDS_MAX_X], maxX); + bounds[nolongerhuman$BOUNDS_MAX_Y] = Math.max(bounds[nolongerhuman$BOUNDS_MAX_Y], maxY); + } + + @Unique + private void nolongerhuman$submitBackgroundRectangle( + OrderedSubmitNodeCollector submitNodeCollector, + PoseStack poseStack, + int[] bounds, + int lightCoords + ) { + float x0 = bounds[nolongerhuman$BOUNDS_MIN_X] - nolongerhuman$BACKGROUND_PADDING_X; + float y0 = bounds[nolongerhuman$BOUNDS_MIN_Y] - nolongerhuman$BACKGROUND_PADDING_Y; + float x1 = bounds[nolongerhuman$BOUNDS_MAX_X] + nolongerhuman$BACKGROUND_PADDING_X; + float y1 = bounds[nolongerhuman$BOUNDS_MAX_Y] + nolongerhuman$BACKGROUND_PADDING_Y; + + if (x1 <= x0 || y1 <= y0) { + return; + } + + int fillColor = Nametags.getBackgroundColor(); + int borderColor = Nametags.getBackgroundBorderColor(); + + submitNodeCollector.submitCustomGeometry( + poseStack, + RenderTypes.textBackgroundSeeThrough(), + (pose, vertexConsumer) -> { + nolongerhuman$drawRectangle( + pose, + vertexConsumer, + x0, + y0, + x1, + y1, + fillColor, + lightCoords + ); + + nolongerhuman$drawBackgroundBorder( + pose, + vertexConsumer, + x0, + y0, + x1, + y1, + borderColor, + lightCoords + ); + } + ); + } + + @Unique + private void nolongerhuman$drawBackgroundBorder( + PoseStack.Pose pose, + VertexConsumer vertexConsumer, + float x0, + float y0, + float x1, + float y1, + int color, + int lightCoords + ) { + float thickness = nolongerhuman$BACKGROUND_BORDER_THICKNESS; + + nolongerhuman$drawRectangle( + pose, + vertexConsumer, + x0, + y0, + x1, + y0 + thickness, + color, + lightCoords + ); + + nolongerhuman$drawRectangle( + pose, + vertexConsumer, + x0, + y1 - thickness, + x1, + y1, + color, + lightCoords + ); + + nolongerhuman$drawRectangle( + pose, + vertexConsumer, + x0, + y0, + x0 + thickness, + y1, + color, + lightCoords + ); + + nolongerhuman$drawRectangle( + pose, + vertexConsumer, + x1 - thickness, + y0, + x1, + y1, + color, + lightCoords + ); + } + + @Unique + private void nolongerhuman$drawRectangle( + PoseStack.Pose pose, + VertexConsumer vertexConsumer, + float x0, + float y0, + float x1, + float y1, + int color, + int lightCoords + ) { + float z = 0.0F; + + vertexConsumer.addVertex(pose, x0, y1, z).setColor(color).setLight(lightCoords); + vertexConsumer.addVertex(pose, x1, y1, z).setColor(color).setLight(lightCoords); + vertexConsumer.addVertex(pose, x1, y0, z).setColor(color).setLight(lightCoords); + vertexConsumer.addVertex(pose, x0, y0, z).setColor(color).setLight(lightCoords); + } + + @Unique + private void nolongerhuman$submitArmorOverlayInCurrentPose( + Entity entity, + Minecraft minecraft, + PoseStack poseStack, + SubmitNodeCollector fallbackSubmitNodeCollector, + OrderedSubmitNodeCollector nametagCollector, + EntityRenderState state + ) { + if (!(entity instanceof Player player)) { + return; + } + + boolean renderIcons = Nametags.shouldRenderArmorIcons(entity); + boolean renderDurability = Nametags.shouldRenderArmorDurability(); + + if (!renderIcons && !renderDurability) { + return; + } + + int visibleArmor = nolongerhuman$getVisibleArmorCount(player); + + if (visibleArmor <= 0) { + return; + } + + int iconTotalWidth = visibleArmor * nolongerhuman$ARMOR_ITEM_SPACING - 4; + int iconStartX = -iconTotalWidth / 2; + int itemY = Nametags.getMainYOffset() + - nolongerhuman$ARMOR_ITEM_SIZE + - Nametags.getArmorNameGap(); + int durabilityY = itemY + nolongerhuman$ARMOR_ITEM_SIZE + 1; + + boolean submitIcons = renderIcons && !nolongerhuman$iconsSubmittedByState.containsKey(state); + + if (submitIcons) { + nolongerhuman$iconsSubmittedByState.put(state, Boolean.TRUE); + } + + int visibleIndex = 0; + + for (EquipmentSlot slot : nolongerhuman$ARMOR_ORDER) { + ItemStack stack = player.getItemBySlot(slot); + + if (stack.isEmpty()) { + continue; + } + + int itemX = iconStartX + visibleIndex * nolongerhuman$ARMOR_ITEM_SPACING; + int iconCenterX = itemX + nolongerhuman$ARMOR_ITEM_SIZE / 2; + + if (submitIcons) { + nolongerhuman$submitArmorItem( + minecraft, + nametagCollector, + fallbackSubmitNodeCollector, + poseStack, + player, + stack, + itemX, + itemY, + nolongerhuman$NAMETAG_LIGHT + ); + } + + if (renderIcons && Nametags.shouldRenderArmorText()) { + String pieceText = Nametags.getArmorPieceText(stack, slot); + + if (!pieceText.isEmpty()) { + int textX = iconCenterX - minecraft.font.width(pieceText) / 2; + int textY = itemY + 4; + + nolongerhuman$submitStringText( + nametagCollector, + poseStack, + pieceText, + textX, + textY, + Nametags.getArmorPieceTextColor(stack), + Nametags.shouldRenderArmorShadow(), + nolongerhuman$NAMETAG_LIGHT + ); + } + } + + if (renderDurability) { + String pieceDurabilityText = Nametags.getArmorDurabilityText(stack); + + if (!pieceDurabilityText.isEmpty()) { + int durabilityX = nolongerhuman$getArmorDurabilityTextX( + minecraft, + player, + slot, + pieceDurabilityText + ); + + nolongerhuman$submitStringText( + nametagCollector, + poseStack, + pieceDurabilityText, + durabilityX, + durabilityY, + Nametags.getArmorDurabilityTextColor(stack), + Nametags.shouldRenderArmorShadow(), + nolongerhuman$NAMETAG_LIGHT + ); + } + } + + visibleIndex++; + } + } + + @Unique + private int nolongerhuman$getArmorDurabilityTextX( + Minecraft minecraft, + Player player, + EquipmentSlot targetSlot, + String targetText + ) { + int gap = Math.max(0, Nametags.getArmorDurabilitySpacing()); + int totalWidth = 0; + int visibleDurabilityPieces = 0; + + for (EquipmentSlot slot : nolongerhuman$ARMOR_ORDER) { + ItemStack stack = player.getItemBySlot(slot); + + if (stack.isEmpty()) { + continue; + } + + String durabilityText = Nametags.getArmorDurabilityText(stack); + + if (durabilityText.isEmpty()) { + continue; + } + + if (visibleDurabilityPieces > 0) { + totalWidth += gap; + } + + totalWidth += minecraft.font.width(durabilityText); + visibleDurabilityPieces++; + } + + if (visibleDurabilityPieces <= 0) { + return -minecraft.font.width(targetText) / 2; + } + + int visualCursorX = -totalWidth / 2; + + for (EquipmentSlot slot : nolongerhuman$ARMOR_ORDER) { + ItemStack stack = player.getItemBySlot(slot); + + if (stack.isEmpty()) { + continue; + } + + String durabilityText = Nametags.getArmorDurabilityText(stack); + + if (durabilityText.isEmpty()) { + continue; + } + + int width = minecraft.font.width(durabilityText); + + if (slot == targetSlot) { + return visualCursorX; + } + + visualCursorX += width + gap; + } + + return -minecraft.font.width(targetText) / 2; + } + + @Unique + private void nolongerhuman$submitArmorItem( + Minecraft minecraft, + OrderedSubmitNodeCollector nametagCollector, + SubmitNodeCollector fallbackSubmitNodeCollector, + PoseStack poseStack, + Player player, + ItemStack stack, + int itemX, + int itemY, + int lightCoords + ) { + poseStack.pushPose(); + + poseStack.translate( + itemX + nolongerhuman$ARMOR_ITEM_SIZE / 2.0F, + itemY + nolongerhuman$ARMOR_ITEM_SIZE / 2.0F, + 0.0F + ); + + poseStack.scale( + nolongerhuman$ARMOR_ITEM_SIZE, + -nolongerhuman$ARMOR_ITEM_SIZE, + nolongerhuman$ARMOR_ITEM_SIZE + ); + + ItemStackRenderState itemRenderState = new ItemStackRenderState(); + + minecraft.getItemModelResolver().updateForTopItem( + itemRenderState, + stack, + ItemDisplayContext.GUI, + player.level(), + player, + 0 + ); + + nolongerhuman$forceItemStateSeeThrough(itemRenderState); + + boolean submittedInNametagLayer = nolongerhuman$submitItemRenderStateOrdered( + itemRenderState, + poseStack, + nametagCollector, + lightCoords + ); + + if (!submittedInNametagLayer) { + nolongerhuman$submitItemRenderStateFallback( + itemRenderState, + poseStack, + fallbackSubmitNodeCollector, + lightCoords + ); + } + + poseStack.popPose(); + } + + @Unique + private boolean nolongerhuman$submitItemRenderStateOrdered( + ItemStackRenderState itemRenderState, + PoseStack poseStack, + OrderedSubmitNodeCollector submitNodeCollector, + int lightCoords + ) { + nolongerhuman$lookupItemLayerFields(); + + if (nolongerhuman$itemStateLayerCountField == null + || nolongerhuman$itemStateLayersField == null + || nolongerhuman$itemLayerQuadsField == null + || nolongerhuman$itemLayerRenderTypeField == null + || nolongerhuman$itemLayerFoilTypeField == null + || nolongerhuman$itemLayerTintLayersField == null + || nolongerhuman$orderedSubmitItemMethod == null) { + return false; + } + + try { + int layerCount = nolongerhuman$itemStateLayerCountField.getInt(itemRenderState); + Object layersObject = nolongerhuman$itemStateLayersField.get(itemRenderState); + + if (!(layersObject instanceof Object[] layers)) { + return false; + } + + boolean submitted = false; + + for (int i = 0; i < layerCount && i < layers.length; i++) { + Object layer = layers[i]; + + if (layer == null) { + continue; + } + + Object quadsObject = nolongerhuman$itemLayerQuadsField.get(layer); + + if (!(quadsObject instanceof List quads) || quads.isEmpty()) { + continue; + } + + Object renderTypeObject = nolongerhuman$itemLayerRenderTypeField.get(layer); + RenderType itemRenderType; + + if (renderTypeObject instanceof RenderType) { + itemRenderType = (RenderType) renderTypeObject; + } else { + itemRenderType = RenderTypes.textSeeThrough(TextureAtlas.LOCATION_ITEMS); + } + + Object tintLayersObject = nolongerhuman$itemLayerTintLayersField.get(layer); + int[] tintLayers = tintLayersObject instanceof int[] ints ? ints : new int[0]; + Object foilType = nolongerhuman$itemLayerFoilTypeField.get(layer); + + nolongerhuman$orderedSubmitItemMethod.invoke( + submitNodeCollector, + poseStack, + ItemDisplayContext.GUI, + lightCoords, + 0, + 0, + tintLayers, + quads, + itemRenderType, + foilType + ); + + submitted = true; + } + + return submitted; + } catch (Throwable ignored) { + return false; + } + } + + @Unique + private void nolongerhuman$forceItemStateSeeThrough(ItemStackRenderState itemRenderState) { + nolongerhuman$lookupItemLayerFields(); + + if (nolongerhuman$itemStateLayerCountField == null + || nolongerhuman$itemStateLayersField == null + || nolongerhuman$itemLayerSetRenderTypeMethod == null) { + return; + } + + try { + int layerCount = nolongerhuman$itemStateLayerCountField.getInt(itemRenderState); + Object layersObject = nolongerhuman$itemStateLayersField.get(itemRenderState); + + if (!(layersObject instanceof Object[] layers)) { + return; + } + + RenderType seeThroughItemRenderType = RenderTypes.textSeeThrough(TextureAtlas.LOCATION_ITEMS); + + for (int i = 0; i < layerCount && i < layers.length; i++) { + Object layer = layers[i]; + + if (layer == null) { + continue; + } + + nolongerhuman$itemLayerSetRenderTypeMethod.invoke(layer, seeThroughItemRenderType); + + if (nolongerhuman$itemLayerSetUsesBlockLightMethod != null) { + nolongerhuman$itemLayerSetUsesBlockLightMethod.invoke(layer, false); + } + } + } catch (Throwable ignored) { + } + } + + @Unique + private static void nolongerhuman$lookupItemLayerFields() { + if (nolongerhuman$lookedUpItemLayerFields) { + return; + } + + nolongerhuman$lookedUpItemLayerFields = true; + + try { + for (Field field : ItemStackRenderState.class.getDeclaredFields()) { + Class type = field.getType(); + + if (type == int.class && nolongerhuman$itemStateLayerCountField == null) { + field.setAccessible(true); + nolongerhuman$itemStateLayerCountField = field; + continue; + } + + if (type.isArray() + && type.getComponentType().getName().contains("LayerRenderState")) { + field.setAccessible(true); + nolongerhuman$itemStateLayersField = field; + } + } + + if (nolongerhuman$itemStateLayersField == null) { + return; + } + + Class layerClass = nolongerhuman$itemStateLayersField.getType().getComponentType(); + + for (Field field : layerClass.getDeclaredFields()) { + Class type = field.getType(); + + if (List.class.isAssignableFrom(type) && nolongerhuman$itemLayerQuadsField == null) { + field.setAccessible(true); + nolongerhuman$itemLayerQuadsField = field; + continue; + } + + if (type == RenderType.class && nolongerhuman$itemLayerRenderTypeField == null) { + field.setAccessible(true); + nolongerhuman$itemLayerRenderTypeField = field; + continue; + } + + if (type == int[].class && nolongerhuman$itemLayerTintLayersField == null) { + field.setAccessible(true); + nolongerhuman$itemLayerTintLayersField = field; + continue; + } + + if (type.getName().contains("FoilType") && nolongerhuman$itemLayerFoilTypeField == null) { + field.setAccessible(true); + nolongerhuman$itemLayerFoilTypeField = field; + } + } + + for (Method method : layerClass.getDeclaredMethods()) { + Class[] parameters = method.getParameterTypes(); + + if (parameters.length == 1 && parameters[0] == RenderType.class) { + method.setAccessible(true); + nolongerhuman$itemLayerSetRenderTypeMethod = method; + continue; + } + + if (parameters.length == 1 && parameters[0] == boolean.class) { + method.setAccessible(true); + nolongerhuman$itemLayerSetUsesBlockLightMethod = method; + } + } + + for (Method method : OrderedSubmitNodeCollector.class.getMethods()) { + Class[] parameters = method.getParameterTypes(); + + if (parameters.length != 9) { + continue; + } + + if (parameters[0] != PoseStack.class) { + continue; + } + + if (parameters[1] != ItemDisplayContext.class) { + continue; + } + + if (parameters[2] != int.class + || parameters[3] != int.class + || parameters[4] != int.class) { + continue; + } + + if (parameters[5] != int[].class) { + continue; + } + + if (!List.class.isAssignableFrom(parameters[6])) { + continue; + } + + if (parameters[7] != RenderType.class) { + continue; + } + + if (!parameters[8].getName().contains("FoilType")) { + continue; + } + + method.setAccessible(true); + nolongerhuman$orderedSubmitItemMethod = method; + break; + } + } catch (Throwable ignored) { + } + } + + @Unique + private void nolongerhuman$submitItemRenderStateFallback( + ItemStackRenderState itemRenderState, + PoseStack poseStack, + SubmitNodeCollector submitNodeCollector, + int lightCoords + ) { + Method method = nolongerhuman$getItemStateSubmitMethod(); + + if (method == null) { + return; + } + + try { + Class[] parameterTypes = method.getParameterTypes(); + + if (parameterTypes.length == 5) { + method.invoke( + itemRenderState, + poseStack, + submitNodeCollector, + lightCoords, + 0, + 0 + ); + } else if (parameterTypes.length == 4) { + method.invoke( + itemRenderState, + poseStack, + submitNodeCollector, + lightCoords, + 0 + ); + } else if (parameterTypes.length == 3) { + method.invoke( + itemRenderState, + poseStack, + submitNodeCollector, + lightCoords + ); + } + } catch (Throwable ignored) { + } + } + + @Unique + private static Method nolongerhuman$getItemStateSubmitMethod() { + if (nolongerhuman$lookedUpItemStateSubmitMethod) { + return nolongerhuman$itemStateSubmitMethod; + } + + nolongerhuman$lookedUpItemStateSubmitMethod = true; + + Method[] methods = ItemStackRenderState.class.getDeclaredMethods(); + + for (Method method : methods) { + Class[] parameters = method.getParameterTypes(); + + if (parameters.length < 3 || parameters.length > 5) { + continue; + } + + if (parameters[0] != PoseStack.class) { + continue; + } + + if (parameters[1] != SubmitNodeCollector.class) { + continue; + } + + if (parameters[2] != int.class) { + continue; + } + + boolean valid = true; + + for (int i = 3; i < parameters.length; i++) { + if (parameters[i] != int.class) { + valid = false; + break; + } + } + + if (!valid) { + continue; + } + + method.setAccessible(true); + nolongerhuman$itemStateSubmitMethod = method; + return method; + } + + return null; + } + + @Unique + private void nolongerhuman$submitComponentTextCentered( + Minecraft minecraft, + OrderedSubmitNodeCollector submitNodeCollector, + PoseStack poseStack, + Component text, + int y, + int lightCoords + ) { + if (text == null) { + return; + } + + FormattedCharSequence sequence = text.getVisualOrderText(); + int width = minecraft.font.width(sequence); + int x = -width / 2; + + submitNodeCollector.submitText( + poseStack, + x, + y, + sequence, + false, + Font.DisplayMode.SEE_THROUGH, + lightCoords, + 0xFFFFFFFF, + 0, + 0 + ); + } + + @Unique + private void nolongerhuman$submitStringText( + OrderedSubmitNodeCollector submitNodeCollector, + PoseStack poseStack, + String text, + float x, + float y, + int color, + boolean shadow, + int lightCoords + ) { + if (text == null || text.isEmpty()) { + return; + } + + submitNodeCollector.submitText( + poseStack, + x, + y, + Component.literal(text).getVisualOrderText(), + shadow, + Font.DisplayMode.SEE_THROUGH, + lightCoords, + color, + 0, + 0 + ); + } + + @Unique + private int nolongerhuman$getVisibleArmorCount(Player player) { + int count = 0; + + for (EquipmentSlot slot : nolongerhuman$ARMOR_ORDER) { + if (!player.getItemBySlot(slot).isEmpty()) { + count++; + } + } + + return count; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinFogRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinFogRenderer.java new file mode 100644 index 0000000..1dd74ff --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinFogRenderer.java @@ -0,0 +1,29 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +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(targets = "net.minecraft.client.renderer.fog.FogRenderer") +public class MixinFogRenderer { + @Inject( + method = "setupFog", + at = @At("RETURN"), + cancellable = true, + require = 0 + ) + private static void chinaware$setupFog(CallbackInfoReturnable cir) { + Object fogData = cir.getReturnValue(); + + if (fogData == null) { + return; + } + + if (NoRender.shouldCancelFog()) { + NoRender.applyNoFogToFogData(fogData); + cir.setReturnValue(fogData); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRenderer.java new file mode 100644 index 0000000..1511291 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRenderer.java @@ -0,0 +1,25 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.renderer.GameRenderer; +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(GameRenderer.class) +public class MixinGameRenderer { + + @Inject( + method = "bobHurt", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void chinaware$bobHurt(PoseStack poseStack, float tickDelta, CallbackInfo ci) { + if (NoRender.shouldCancelHurtCam()) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRendererNoEntityTrace.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRendererNoEntityTrace.java new file mode 100644 index 0000000..628c376 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRendererNoEntityTrace.java @@ -0,0 +1,39 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.player.NoEntityTrace; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.world.phys.EntityHitResult; +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(GameRenderer.class) +public class MixinGameRendererNoEntityTrace { + @Shadow + @Final + private Minecraft minecraft; + + @Inject(method = "pick", at = @At("TAIL")) + private void nolongerhuman$pick(float partialTick, CallbackInfo ci) { + if (minecraft.player == null) return; + if (minecraft.hitResult == null) return; + if (!(minecraft.hitResult instanceof EntityHitResult)) return; + if (nolongerhuman.moduleManager == null) return; + + NoEntityTrace noEntityTrace = nolongerhuman.moduleManager.getModuleByClass(NoEntityTrace.class); + + if (noEntityTrace == null || !noEntityTrace.shouldIgnore()) { + return; + } + + double range = minecraft.player.isCreative() ? 5.0 : 4.5; + + minecraft.hitResult = minecraft.player.pick(range, partialTick, false); + minecraft.crosshairPickEntity = null; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRendererViewModel.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRendererViewModel.java new file mode 100644 index 0000000..2079406 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinGameRendererViewModel.java @@ -0,0 +1,33 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.ViewModel; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.GameRenderer; +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(GameRenderer.class) +public class MixinGameRendererViewModel { + + @Inject( + method = "getFov", + at = @At("RETURN"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$modifyWorldFov( + Camera camera, + float tickDelta, + boolean changingFov, + CallbackInfoReturnable cir + ) { + float originalFov = cir.getReturnValue(); + float modifiedFov = ViewModel.modifyWorldFov(originalFov); + + if (Float.compare(originalFov, modifiedFov) != 0) { + cir.setReturnValue(modifiedFov); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinHandAnimations.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinHandAnimations.java new file mode 100644 index 0000000..1ba8c8f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinHandAnimations.java @@ -0,0 +1,68 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.features.modules.render.AttackAnimations; +import me.humanbeing.nolongerhuman.features.modules.render.BreakAnimations; +import me.humanbeing.nolongerhuman.features.modules.render.PlaceAnimations; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.world.entity.HumanoidArm; +import net.minecraft.world.item.ItemDisplayContext; +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(ItemInHandRenderer.class) +public class MixinHandAnimations { + + @Inject( + method = "applyItemArmAttackTransform", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$applyItemArmAttackTransform( + CallbackInfo ci, + @Local(argsOnly = true) HumanoidArm arm + ) { + if (BreakAnimations.shouldCancelVanillaBreak(arm)) { + ci.cancel(); + return; + } + + if (AttackAnimations.shouldCancelVanillaAttack(arm)) { + ci.cancel(); + return; + } + + if (PlaceAnimations.shouldCancelVanillaPlace(arm)) { + ci.cancel(); + return; + } + + if (BreakAnimations.shouldReplaceVanillaBreak(arm)) { + ci.cancel(); + return; + } + + if (AttackAnimations.shouldReplaceVanillaAttack(arm)) { + ci.cancel(); + } + } + + @Inject( + method = "renderItem", + at = @At("HEAD"), + require = 0 + ) + private void nolongerhuman$renderItem( + CallbackInfo ci, + @Local(argsOnly = true) PoseStack poseStack, + @Local(argsOnly = true) ItemDisplayContext displayContext + ) { + BreakAnimations.applyAnimation(poseStack, displayContext); + AttackAnimations.applyAnimation(poseStack, displayContext); + PlaceAnimations.applyAnimation(poseStack, displayContext); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinItemInHandRendererViewModel.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinItemInHandRendererViewModel.java new file mode 100644 index 0000000..f440593 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinItemInHandRendererViewModel.java @@ -0,0 +1,28 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.blaze3d.vertex.PoseStack; +import me.humanbeing.nolongerhuman.features.modules.render.ViewModel; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.world.item.ItemDisplayContext; +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(ItemInHandRenderer.class) +public class MixinItemInHandRendererViewModel { + + @Inject( + method = "renderItem", + at = @At("HEAD"), + require = 0 + ) + private void nolongerhuman$renderItem( + CallbackInfo ci, + @Local(argsOnly = true) PoseStack poseStack, + @Local(argsOnly = true) ItemDisplayContext displayContext + ) { + ViewModel.applyItemTransform(poseStack, displayContext); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinLevelRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinLevelRenderer.java new file mode 100644 index 0000000..61a0e6b --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinLevelRenderer.java @@ -0,0 +1,167 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.resource.GraphicsResourceAllocator; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.event.impl.render.Render3DEvent; +import me.humanbeing.nolongerhuman.event.impl.render.RenderBlockOutlineEvent; +import me.humanbeing.nolongerhuman.features.modules.render.Ambience; +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.Camera; +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.state.LevelRenderState; +import net.minecraft.core.BlockPos; +import net.minecraft.util.profiling.ProfilerFiller; +import org.joml.Matrix4f; +import org.joml.Vector4f; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.awt.Color; + +import static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; +import static me.humanbeing.nolongerhuman.util.traits.Util.mc; + +@Mixin(LevelRenderer.class) +public class MixinLevelRenderer { + @Inject(method = "renderBlockOutline", at = @At("HEAD"), cancellable = true) + public void renderBlockOutline( + MultiBufferSource.BufferSource bufferSource, + PoseStack poseStack, + boolean bl, + LevelRenderState levelRenderState, + CallbackInfo ci + ) { + if (EVENT_BUS.post(new RenderBlockOutlineEvent())) { + ci.cancel(); + } + } + + @Inject(method = "renderLevel", at = @At("HEAD")) + private void chinaware$renderLevelHead( + GraphicsResourceAllocator allocator, + DeltaTracker tickCounter, + boolean renderBlockOutline, + Camera camera, + Matrix4f positionMatrix, + Matrix4f matrix4f, + Matrix4f projectionMatrix, + GpuBufferSlice fogBuffer, + Vector4f fogColor, + boolean renderSky, + CallbackInfo ci + ) { + if (NoRender.shouldCancelWeather() && mc.level != null) { + mc.level.setRainLevel(0.0f); + mc.level.setThunderLevel(0.0f); + } + + NoRender.shouldCancelWorldBorder(); + NoRender.shouldCancelCaveCulling(); + NoRender.shouldCancelTextureRotations(); + NoRender.shouldCancelMapMarkers(); + NoRender.shouldCancelMapContents(); + NoRender.shouldCancelBarrierInvisibility(); + NoRender.shouldCancelFallingBlocks(); + NoRender.shouldCancelBeaconBeams(); + NoRender.shouldCancelEnchantTableBook(); + NoRender.shouldCancelSignText(); + NoRender.shouldCancelBlockBreakOverlay(); + + nolongerhuman$applyBackgroundOrFogColor(fogColor); + } + + @Unique + private void nolongerhuman$applyBackgroundOrFogColor(Vector4f fogColor) { + if (fogColor == null) { + return; + } + + Color color = null; + + if (Ambience.shouldUseBackgroundColor()) { + color = Ambience.getBackgroundColor(); + } else if (Ambience.shouldUseFogColor()) { + color = Ambience.getFogColor(); + } + + if (color == null) { + return; + } + + fogColor.set( + Ambience.red(color), + Ambience.green(color), + Ambience.blue(color), + Ambience.alpha(color) + ); + } + + @Inject( + method = "destroyBlockProgress", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void chinaware$destroyBlockProgress( + int id, + BlockPos pos, + int progress, + CallbackInfo ci + ) { + if (NoRender.shouldCancelBlockBreakOverlay()) { + ci.cancel(); + } + } + + @Inject( + method = "allChanged", + at = @At("HEAD"), + require = 0 + ) + private void chinaware$allChanged(CallbackInfo ci) { + NoRender.shouldCancelCaveCulling(); + NoRender.shouldCancelTextureRotations(); + } + + @Inject(method = "renderLevel", at = @At("RETURN")) + private void render( + GraphicsResourceAllocator allocator, + DeltaTracker tickCounter, + boolean renderBlockOutline, + Camera camera, + Matrix4f positionMatrix, + Matrix4f matrix4f, + Matrix4f projectionMatrix, + GpuBufferSlice fogBuffer, + Vector4f fogColor, + boolean renderSky, + CallbackInfo ci, + @Local ProfilerFiller profiler + ) { + PoseStack stack = new PoseStack(); + + stack.pushPose(); + stack.mulPose(Axis.XP.rotationDegrees(mc.gameRenderer.getMainCamera().xRot())); + stack.mulPose(Axis.YP.rotationDegrees(mc.gameRenderer.getMainCamera().yRot() + 180f)); + + profiler.push("nolongerhuman-render-3d"); + + Render3DEvent event = new Render3DEvent( + stack, + tickCounter.getGameTimeDeltaPartialTick(true) + ); + + EVENT_BUS.post(event); + + stack.popPose(); + profiler.pop(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinLivingEntityRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinLivingEntityRenderer.java new file mode 100644 index 0000000..a8d8f65 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinLivingEntityRenderer.java @@ -0,0 +1,27 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.renderer.entity.LivingEntityRenderer; +import net.minecraft.client.renderer.entity.state.LivingEntityRenderState; +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(LivingEntityRenderer.class) +public class MixinLivingEntityRenderer { + + @Inject( + method = "isBodyVisible", + at = @At("HEAD"), + cancellable = true + ) + private void chinaware$isBodyVisible( + LivingEntityRenderState renderState, + CallbackInfoReturnable cir + ) { + if (NoRender.shouldRenderInvisibleEntities()) { + cir.setReturnValue(true); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinNoEatingAnimation.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinNoEatingAnimation.java new file mode 100644 index 0000000..dce3843 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinNoEatingAnimation.java @@ -0,0 +1,36 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoEatingAnimation; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ItemInHandRenderer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.item.ItemStack; +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(ItemInHandRenderer.class) +public class MixinNoEatingAnimation { + + @Inject( + method = "applyEatTransform", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$applyEatTransform(CallbackInfo ci) { + Minecraft minecraft = Minecraft.getInstance(); + LocalPlayer player = minecraft.player; + + if (player == null) { + return; + } + + ItemStack usingStack = player.getUseItem(); + + if (NoEatingAnimation.shouldCancelEatingAnimation(usingStack)) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinParticleEngine.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinParticleEngine.java new file mode 100644 index 0000000..3f053ba --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinParticleEngine.java @@ -0,0 +1,25 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.event.impl.render.ParticleEvent; +import net.minecraft.client.particle.Particle; +import net.minecraft.client.particle.ParticleEngine; +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 static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(ParticleEngine.class) +public class MixinParticleEngine { + + @Inject(method = "add", at = @At("HEAD"), cancellable = true) + private void chinaware$addParticle(Particle particle, CallbackInfo ci) { + ParticleEvent.Add event = new ParticleEvent.Add(particle); + EVENT_BUS.post(event); + + if (event.isCancelled()) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinScreenEffectRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinScreenEffectRenderer.java new file mode 100644 index 0000000..417987e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinScreenEffectRenderer.java @@ -0,0 +1,33 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.renderer.ScreenEffectRenderer; +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(ScreenEffectRenderer.class) +public class MixinScreenEffectRenderer { + + @Inject(method = "renderFire", at = @At("HEAD"), cancellable = true) + private static void nolongerhuman$renderFire(CallbackInfo ci) { + if (NoRender.shouldCancelFireOverlay()) { + ci.cancel(); + } + } + + @Inject(method = "renderWater", at = @At("HEAD"), cancellable = true) + private static void nolongerhuman$renderWater(CallbackInfo ci) { + if (NoRender.shouldCancelWaterOverlay() || NoRender.shouldCancelLiquidOverlay()) { + ci.cancel(); + } + } + + @Inject(method = "renderTex", at = @At("HEAD"), cancellable = true) + private static void nolongerhuman$renderTex(CallbackInfo ci) { + if (NoRender.shouldCancelBlockOverlay() || NoRender.shouldCancelInWallOverlay()) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinSkyRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinSkyRenderer.java new file mode 100644 index 0000000..817e530 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinSkyRenderer.java @@ -0,0 +1,29 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.Ambience; +import net.minecraft.client.renderer.SkyRenderer; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; + +import java.awt.Color; + +@Mixin(SkyRenderer.class) +public class MixinSkyRenderer { + @ModifyVariable( + method = "renderSkyDisc", + at = @At("HEAD"), + argsOnly = true, + ordinal = 0, + require = 0 + ) + private int nolongerhuman$modifySkyDiscColor(int originalColor) { + if (!Ambience.shouldUseSkyColor()) { + return originalColor; + } + + Color color = Ambience.getSkyColor(); + + return Ambience.toArgb(color); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinWorldBorderRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinWorldBorderRenderer.java new file mode 100644 index 0000000..f8ae4e6 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/MixinWorldBorderRenderer.java @@ -0,0 +1,19 @@ +package me.humanbeing.nolongerhuman.mixin.render; + +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.renderer.WorldBorderRenderer; +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(WorldBorderRenderer.class) +public class MixinWorldBorderRenderer { + + @Inject(method = "render", at = @At("HEAD"), cancellable = true) + private void nolongerhuman$render(CallbackInfo ci) { + if (NoRender.shouldCancelWorldBorder()) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/GuiGraphicsMixin.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/GuiGraphicsMixin.java new file mode 100644 index 0000000..74addaf --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/GuiGraphicsMixin.java @@ -0,0 +1,197 @@ +package me.humanbeing.nolongerhuman.mixin.render.gui; + +import me.humanbeing.nolongerhuman.util.render.FontManager; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; +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(GuiGraphics.class) +public class GuiGraphicsMixin { + @Inject( + method = "drawString(Lnet/minecraft/client/gui/Font;Ljava/lang/String;III)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$drawStringStringNoShadow( + Font font, + String text, + int x, + int y, + int color, + CallbackInfo ci + ) { + if (!FontManager.isEnabled()) { + return; + } + + FontManager.drawString( + (GuiGraphics) (Object) this, + text, + x, + y, + color, + false + ); + + ci.cancel(); + } + + @Inject( + method = "drawString(Lnet/minecraft/client/gui/Font;Ljava/lang/String;IIIZ)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$drawStringStringShadow( + Font font, + String text, + int x, + int y, + int color, + boolean shadow, + CallbackInfo ci + ) { + if (!FontManager.isEnabled()) { + return; + } + + FontManager.drawString( + (GuiGraphics) (Object) this, + text, + x, + y, + color, + shadow + ); + + ci.cancel(); + } + + @Inject( + method = "drawString(Lnet/minecraft/client/gui/Font;Lnet/minecraft/network/chat/Component;III)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$drawStringComponentNoShadow( + Font font, + Component text, + int x, + int y, + int color, + CallbackInfo ci + ) { + if (!FontManager.isEnabled()) { + return; + } + + FontManager.drawString( + (GuiGraphics) (Object) this, + text, + x, + y, + color, + false + ); + + ci.cancel(); + } + + @Inject( + method = "drawString(Lnet/minecraft/client/gui/Font;Lnet/minecraft/network/chat/Component;IIIZ)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$drawStringComponentShadow( + Font font, + Component text, + int x, + int y, + int color, + boolean shadow, + CallbackInfo ci + ) { + if (!FontManager.isEnabled()) { + return; + } + + FontManager.drawString( + (GuiGraphics) (Object) this, + text, + x, + y, + color, + shadow + ); + + ci.cancel(); + } + + @Inject( + method = "drawString(Lnet/minecraft/client/gui/Font;Lnet/minecraft/util/FormattedCharSequence;III)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$drawStringFormattedNoShadow( + Font font, + FormattedCharSequence text, + int x, + int y, + int color, + CallbackInfo ci + ) { + if (!FontManager.isEnabled()) { + return; + } + + FontManager.drawString( + (GuiGraphics) (Object) this, + text, + x, + y, + color, + false + ); + + ci.cancel(); + } + + @Inject( + method = "drawString(Lnet/minecraft/client/gui/Font;Lnet/minecraft/util/FormattedCharSequence;IIIZ)V", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void nolongerhuman$drawStringFormattedShadow( + Font font, + FormattedCharSequence text, + int x, + int y, + int color, + boolean shadow, + CallbackInfo ci + ) { + if (!FontManager.isEnabled()) { + return; + } + + FontManager.drawString( + (GuiGraphics) (Object) this, + text, + x, + y, + color, + shadow + ); + + ci.cancel(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinCommandSuggestions.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinCommandSuggestions.java new file mode 100644 index 0000000..0f25e34 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinCommandSuggestions.java @@ -0,0 +1,60 @@ +package me.humanbeing.nolongerhuman.mixin.render.gui; + +import com.llamalad7.mixinextras.sugar.Local; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.ParseResults; +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.suggestion.Suggestions; +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.manager.CommandManager; +import net.minecraft.client.gui.components.CommandSuggestions; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.multiplayer.ClientSuggestionProvider; +import org.jspecify.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.concurrent.CompletableFuture; + +@Mixin(CommandSuggestions.class) +public abstract class MixinCommandSuggestions { + @Shadow + private CommandSuggestions.SuggestionsList suggestions; + @Shadow + private @Nullable CompletableFuture pendingSuggestions; + @Shadow + private @Nullable ParseResults currentParse; + @Shadow + boolean keepSuggestions; + @Shadow + @Final + EditBox input; + + @Shadow + protected abstract void updateUsageInfo(); + + @SuppressWarnings("unchecked") + @Inject(method = "updateCommandInfo", at = @At("RETURN")) + public void updateCommandInfo(CallbackInfo ci, @Local StringReader stringReader) { + if (!stringReader.canRead() || !stringReader.getString().startsWith(nolongerhuman.commandManager.getCommandPrefix())) { + return; + } + stringReader.skip(); + + CommandDispatcher dispatcher = nolongerhuman.commandManager.getDispatcher(); + ParseResults parse = dispatcher.parse(stringReader, nolongerhuman.commandManager); + currentParse = (ParseResults) (Object) parse; + if (suggestions == null || !keepSuggestions) { + pendingSuggestions = dispatcher.getCompletionSuggestions(parse, input.getCursorPosition()); + pendingSuggestions.thenRun(() -> { + if (pendingSuggestions.isDone()) { + updateUsageInfo(); + } + }); + } + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinGui.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinGui.java new file mode 100644 index 0000000..2154ffc --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinGui.java @@ -0,0 +1,292 @@ +package me.humanbeing.nolongerhuman.mixin.render.gui; + +import me.humanbeing.nolongerhuman.event.impl.render.Render2DEvent; +import me.humanbeing.nolongerhuman.features.modules.render.NoRender; +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.lang.reflect.Field; + +import static me.humanbeing.nolongerhuman.util.traits.Util.EVENT_BUS; + +@Mixin(Gui.class) +public class MixinGui { + + @Inject(method = "render", at = @At("HEAD")) + private void chinaware$preRender(GuiGraphics context, DeltaTracker tickCounter, CallbackInfo ci) { + if (NoRender.shouldCancelBossBars()) { + chinaware$clearBossOverlay(); + } + + if (NoRender.shouldCancelTotemAnimation()) { + chinaware$clearItemActivationAnimation(); + } + + if (NoRender.shouldCancelTitle()) { + chinaware$clearTitle(); + } + + if (NoRender.shouldCancelHeldItemName()) { + chinaware$clearHeldItemName(); + } + + NoRender.shouldCancelPotionIcons(); + NoRender.shouldCancelCrosshair(); + NoRender.shouldCancelScoreboard(); + NoRender.shouldCancelVignette(); + NoRender.shouldCancelSpyglassOverlay(); + NoRender.shouldCancelPumpkinOverlay(); + NoRender.shouldCancelPowderedSnowOverlay(); + NoRender.shouldCancelFireOverlay(); + NoRender.shouldCancelWaterOverlay(); + NoRender.shouldCancelLiquidOverlay(); + NoRender.shouldCancelBlockOverlay(); + NoRender.shouldCancelInWallOverlay(); + NoRender.shouldCancelGuiBackground(); + NoRender.shouldCancelObfuscation(); + NoRender.shouldCancelMessageSignatureIndicator(); + NoRender.shouldCancelNausea(); + } + + @Inject( + method = "renderCrosshair", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void chinaware$renderCrosshair(CallbackInfo ci) { + if (NoRender.shouldCancelCrosshair()) { + ci.cancel(); + } + } + + @Inject( + method = "renderEffects", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void chinaware$renderEffects(CallbackInfo ci) { + if (NoRender.shouldCancelPotionIcons()) { + ci.cancel(); + } + } + + @Inject( + method = "displayScoreboardSidebar", + at = @At("HEAD"), + cancellable = true, + require = 0 + ) + private void chinaware$displayScoreboardSidebar(CallbackInfo ci) { + if (NoRender.shouldCancelScoreboard()) { + ci.cancel(); + } + } + + @Inject(method = "render", at = @At("RETURN")) + public void render(GuiGraphics context, DeltaTracker tickCounter, CallbackInfo ci) { + if (Minecraft.getInstance().gui.getDebugOverlay().showDebugScreen()) { + return; + } + + Render2DEvent event = new Render2DEvent( + context, + tickCounter.getGameTimeDeltaPartialTick(true) + ); + + EVENT_BUS.post(event); + } + + @Unique + private void chinaware$clearItemActivationAnimation() { + Object gui = this; + + Class clazz = gui.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + + Class type = field.getType(); + String name = field.getName().toLowerCase(); + + if (type == ItemStack.class + && ( + name.contains("item") + || name.contains("activation") + || name.contains("overlay") + || name.contains("tool") + )) { + field.set(gui, ItemStack.EMPTY); + continue; + } + + if ((type == int.class || type == Integer.class) + && ( + name.contains("activation") + || name.contains("overlay") + || name.contains("animation") + || name.contains("time") + || name.contains("remaining") + )) { + field.setInt(gui, 0); + continue; + } + + if ((type == float.class || type == Float.class) + && ( + name.contains("activation") + || name.contains("overlay") + || name.contains("animation") + || name.contains("scale") + || name.contains("time") + )) { + field.setFloat(gui, 0.0f); + } + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } + + @Unique + private void chinaware$clearTitle() { + Object gui = this; + + Class clazz = gui.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + + Class type = field.getType(); + String name = field.getName().toLowerCase(); + + if ((type == String.class || type.getName().toLowerCase().contains("component")) + && ( + name.contains("title") + || name.contains("subtitle") + )) { + field.set(gui, null); + continue; + } + + if ((type == int.class || type == Integer.class) + && ( + name.contains("title") + || name.contains("subtitle") + || name.contains("fade") + )) { + field.setInt(gui, 0); + } + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } + + @Unique + private void chinaware$clearHeldItemName() { + Object gui = this; + + Class clazz = gui.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + + Class type = field.getType(); + String name = field.getName().toLowerCase(); + + if ((type == int.class || type == Integer.class) + && ( + name.contains("tool") + || name.contains("item") + || name.contains("highlight") + || name.contains("remaining") + )) { + field.setInt(gui, 0); + } + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } + + @Unique + private void chinaware$clearBossOverlay() { + Object gui = Minecraft.getInstance().gui; + + Class clazz = gui.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + + String name = field.getName().toLowerCase(); + + if (!name.contains("boss")) { + continue; + } + + Object bossOverlay = field.get(gui); + + if (bossOverlay == null) { + continue; + } + + chinaware$clearCollections(bossOverlay); + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } + + @Unique + private void chinaware$clearCollections(Object object) { + Class clazz = object.getClass(); + + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + + Object value = field.get(object); + + if (value instanceof java.util.Map map) { + map.clear(); + continue; + } + + if (value instanceof java.util.Collection collection) { + collection.clear(); + } + } catch (Throwable ignored) { + } + } + + clazz = clazz.getSuperclass(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinNoScreenBlur.java b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinNoScreenBlur.java new file mode 100644 index 0000000..5bfdd5f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/mixin/render/gui/MixinNoScreenBlur.java @@ -0,0 +1,30 @@ +package me.humanbeing.nolongerhuman.mixin.render.gui; + +import me.humanbeing.nolongerhuman.features.gui.ChinaGUI; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +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(Screen.class) +public abstract class MixinNoScreenBlur { + + @Inject( + method = "renderBackground", + at = @At("HEAD"), + cancellable = true + ) + private void chinaware$cancelChinaGuiBackground( + GuiGraphics context, + int mouseX, + int mouseY, + float delta, + CallbackInfo ci + ) { + if ((Object) this instanceof ChinaGUI) { + ci.cancel(); + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/nolongerhuman.java b/src/main/java/me/humanbeing/nolongerhuman/nolongerhuman.java new file mode 100644 index 0000000..57503cf --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/nolongerhuman.java @@ -0,0 +1,75 @@ +package me.humanbeing.nolongerhuman; + +import me.humanbeing.nolongerhuman.manager.*; +import me.humanbeing.chinaware.util.BuildConfig; +import me.humanbeing.nolongerhuman.util.TextUtil; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.api.ModInitializer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +//import me.humanbeing.nolongerhuman.util.BackupTrackerWithWebhook; + + + +public class nolongerhuman implements ModInitializer, ClientModInitializer { + public static float TIMER = 1f; + + public static final Logger LOGGER = LogManager.getLogger("nolongerhuman"); + public static ServerManager serverManager; + public static ColorManager colorManager; + public static RotationManager rotationManager; + public static PositionManager positionManager; + public static HoleManager holeManager; + public static EventManager eventManager; + public static SpeedManager speedManager; + public static CommandManager commandManager; + public static FriendManager friendManager; + public static ModuleManager moduleManager; + public static ConfigManager configManager; + public static BoostManager boostManager; + + + @Override + public void onInitialize() { + LOGGER.info("Pre-initializing {} v{}", + BuildConfig.NAME, BuildConfig.VERSION); + configManager = new ConfigManager(); + eventManager = new EventManager(); + serverManager = new ServerManager(); + rotationManager = new RotationManager(); + positionManager = new PositionManager(); + friendManager = new FriendManager(); + colorManager = new ColorManager(); + commandManager = new CommandManager(); + moduleManager = new ModuleManager(); + speedManager = new SpeedManager(); + holeManager = new HoleManager(); + + TextUtil.init(); + } + + @Override + public void onInitializeClient() { + LOGGER.info("Initializing {}", BuildConfig.NAME); + //BackupTrackerWithWebhook.start(); + + long startTime = System.nanoTime(); + + eventManager.init(); + commandManager.init(); + moduleManager.init(); + friendManager.init(); + + configManager.load(); + colorManager.init(); + Runtime.getRuntime().addShutdownHook(new Thread(() -> configManager.save())); + + long endTime = System.nanoTime(); + + LOGGER.info("Initialized {} in {}ms", + BuildConfig.NAME, (endTime - startTime) / 1000000.0); + + + } + +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/ColorUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/ColorUtil.java new file mode 100644 index 0000000..3e23b7a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/ColorUtil.java @@ -0,0 +1,52 @@ +package me.humanbeing.nolongerhuman.util; + +import java.awt.Color; + +public class ColorUtil { + public static Color withAlpha(Color color, int alpha) { + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + clamp(alpha, 0, 255) + ); + } + + public static Color interpolate(Color first, Color second, float factor) { + factor = Math.max(0.0F, Math.min(1.0F, factor)); + + int red = (int) (first.getRed() + (second.getRed() - first.getRed()) * factor); + int green = (int) (first.getGreen() + (second.getGreen() - first.getGreen()) * factor); + int blue = (int) (first.getBlue() + (second.getBlue() - first.getBlue()) * factor); + int alpha = (int) (first.getAlpha() + (second.getAlpha() - first.getAlpha()) * factor); + + return new Color( + clamp(red, 0, 255), + clamp(green, 0, 255), + clamp(blue, 0, 255), + clamp(alpha, 0, 255) + ); + } + + public static Color brighter(Color color, int amount) { + return new Color( + clamp(color.getRed() + amount, 0, 255), + clamp(color.getGreen() + amount, 0, 255), + clamp(color.getBlue() + amount, 0, 255), + color.getAlpha() + ); + } + + public static Color darker(Color color, int amount) { + return new Color( + clamp(color.getRed() - amount, 0, 255), + clamp(color.getGreen() - amount, 0, 255), + clamp(color.getBlue() - amount, 0, 255), + color.getAlpha() + ); + } + + private static int clamp(int value, int min, int max) { + return Math.max(min, Math.min(max, value)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/DiscordWebhook.java b/src/main/java/me/humanbeing/nolongerhuman/util/DiscordWebhook.java new file mode 100644 index 0000000..e6e6622 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/DiscordWebhook.java @@ -0,0 +1,56 @@ +package me.humanbeing.nolongerhuman.util; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; + +public final class DiscordWebhook { + + private static final HttpClient HTTP = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .build(); + + private DiscordWebhook() { + } + + public static void send(String webhookUrl, String message) { + if (webhookUrl == null || webhookUrl.isBlank()) { + return; + } + + String json = "{\"content\":\"" + escape(message) + "\"}"; + + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(webhookUrl)) + .timeout(Duration.ofSeconds(10)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(json, StandardCharsets.UTF_8)) + .build(); + + HTTP.sendAsync(req, HttpResponse.BodyHandlers.discarding()) + .exceptionally(e -> { + System.err.println("[nolongerhuman] Webhook failed: " + e.getMessage()); + return null; + }); + } + + private static String escape(String s) { + StringBuilder sb = new StringBuilder(s.length() + 16); + + for (char c : s.toCharArray()) { + switch (c) { + case '"' -> sb.append("\\\""); + case '\\' -> sb.append("\\\\"); + case '\n' -> sb.append("\\n"); + case '\r' -> sb.append("\\r"); + case '\t' -> sb.append("\\t"); + default -> sb.append(c); + } + } + + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/EnchantmentUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/EnchantmentUtil.java new file mode 100644 index 0000000..9585efb --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/EnchantmentUtil.java @@ -0,0 +1,44 @@ +package me.humanbeing.nolongerhuman.util; + +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.core.Holder; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.Enchantment; + +public final class EnchantmentUtil implements Util { + private EnchantmentUtil() { + throw new IllegalArgumentException(); + } + + public static int getLevel(ResourceKey key, ItemStack stack) { + if (stack.isEmpty()) return 0; + for (Object2IntMap.Entry> enchantment : stack.getEnchantments().entrySet()) { + if (enchantment.getKey().is(key)) return enchantment.getIntValue(); + } + return 0; + } + + public static int getLevel(ResourceKey key, EquipmentSlot slot, LivingEntity entity) { + return getLevel(key, entity.getItemBySlot(slot)); + } + + public static int getLevel(ResourceKey key, EquipmentSlot slot) { + return getLevel(key, slot, mc.player); + } + + public static boolean has(ResourceKey key, ItemStack stack) { + return getLevel(key, stack) > 0; + } + + public static boolean has(ResourceKey key, EquipmentSlot slot, LivingEntity entity) { + return getLevel(key, slot, entity) > 0; + } + + public static boolean has(ResourceKey key, EquipmentSlot slot) { + return getLevel(key, slot) > 0; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/InteractionUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/InteractionUtil.java new file mode 100644 index 0000000..0dfad2a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/InteractionUtil.java @@ -0,0 +1,167 @@ +package me.humanbeing.nolongerhuman.util; + +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.tags.FluidTags; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.effect.MobEffectUtil; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.projectile.throwableitemprojectile.ThrownExperienceBottle; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; + +public class InteractionUtil implements Util { + public static boolean canBreak(BlockPos blockPos, BlockState state) { + if (!mc.player.isCreative() && state.getDestroySpeed(mc.level, blockPos) < 0) return false; + return state.getShape(mc.level, blockPos) != Shapes.empty(); + } + + public static boolean isPlaceable(BlockPos pos, boolean entityCheck) { + if (!mc.level.getBlockState(pos).canBeReplaced()) return false; + for (Entity e : mc.level.getEntitiesOfClass(Entity.class, new AABB(pos), e -> !(e instanceof ThrownExperienceBottle || e instanceof ItemEntity || e instanceof ExperienceOrb))) { + if (e instanceof Player) return false; + return !entityCheck; + } + return true; + } + + public static boolean breakBlock(BlockPos pos) { + if (!canBreak(pos, mc.level.getBlockState(pos))) return false; + BlockPos bp = pos instanceof BlockPos.MutableBlockPos ? new BlockPos(pos) : pos; + + mc.getConnection().send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, bp, Direction.UP)); + mc.player.swing(InteractionHand.MAIN_HAND); + mc.getConnection().send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, bp, Direction.UP)); + + mc.getConnection().send(new ServerboundSwingPacket(InteractionHand.MAIN_HAND)); + + return true; + } + + public static void useItem(BlockPos pos) { + useItem(pos, InteractionHand.MAIN_HAND); + } + + public static void useItem(BlockPos pos, InteractionHand hand) { + if (mc.level == null || mc.player == null || mc.gameMode == null) return; + Direction direction = mc.hitResult != null ? ((BlockHitResult) mc.hitResult).getDirection() : Direction.DOWN; + InteractionResult result = mc.gameMode.useItemOn(mc.player, hand, new BlockHitResult( + Vec3.atCenterOf(pos), direction, pos, false + )); + if (result instanceof InteractionResult.Success success && success.swingSource() != InteractionResult.SwingSource.NONE) { + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + } + + public static boolean place(BlockPos pos, boolean airPlace) { + return place(pos, airPlace, InteractionHand.MAIN_HAND); + } + + public static boolean place(BlockPos pos, boolean airPlace, InteractionHand hand) { + if (mc.level == null || mc.player == null || mc.gameMode == null) return false; + if (!isPlaceable(pos, false)) return false; + Direction direction = calcSide(pos); + if (direction == null) { + if (airPlace) + direction = mc.hitResult != null ? ((BlockHitResult) mc.hitResult).getDirection() : Direction.DOWN; + else return false; + } + BlockPos bp = airPlace ? pos : pos.relative(direction); + InteractionResult result = mc.gameMode.useItemOn(mc.player, hand, new BlockHitResult( + airPlace ? Vec3.atCenterOf(pos) : Vec3.atCenterOf(bp).relative(direction.getOpposite(), 0.5), + airPlace ? direction : direction.getOpposite(), bp, false + )); + if (result instanceof InteractionResult.Success success && success.swingSource() != InteractionResult.SwingSource.NONE) { + mc.player.connection.send(new ServerboundSwingPacket(hand)); + } + return true; + } + + public static Direction calcSide(BlockPos pos) { + for (Direction d : Direction.values()) + if (!mc.level.getBlockState(pos.offset(d.getUnitVec3i())).canBeReplaced()) return d; + return null; + } + + public static double getBlockBreakingSpeed(int slot, BlockPos pos) { + return getBlockBreakingSpeed(slot, mc.level.getBlockState(pos)); + } + + public static double getBlockBreakingSpeed(int slot, BlockState block) { + double speed = mc.player.getInventory().getNonEquipmentItems().get(slot).getDestroySpeed(block); + + if (speed > 1) { + ItemStack tool = mc.player.getInventory().getItem(slot); + + int efficiency = EnchantmentUtil.getLevel(Enchantments.EFFICIENCY, tool); + + if (efficiency > 0 && !tool.isEmpty()) speed += efficiency * efficiency + 1; + } + + if (MobEffectUtil.hasDigSpeed(mc.player)) { + speed *= 1 + (MobEffectUtil.getDigSpeedAmplification(mc.player) + 1) * 0.2F; + } + + if (mc.player.hasEffect(MobEffects.MINING_FATIGUE)) { + float k = switch (mc.player.getEffect(MobEffects.MINING_FATIGUE).getAmplifier()) { + case 0 -> 0.3F; + case 1 -> 0.09F; + case 2 -> 0.0027F; + default -> 8.1E-4F; + }; + + speed *= k; + } + + if (mc.player.isEyeInFluid(FluidTags.WATER) && EnchantmentUtil.has(Enchantments.AQUA_AFFINITY, EquipmentSlot.HEAD)) { + speed /= 5.0F; + } + + if (!mc.player.onGround()) { + speed /= 5.0F; + } + + float hardness = block.getDestroySpeed(null, null); + if (hardness == -1) return 0; + + speed /= hardness / (!block.requiresCorrectToolForDrops() || mc.player.getInventory().getNonEquipmentItems().get(slot).isCorrectToolForDrops(block) ? 30 : 100); + + float ticks = (float) (Math.floor(1.0f / speed) + 1.0f); + + return (long) ((ticks / 20.0f) * 1000); + } + + public static Direction right(Direction direction) { + return switch (direction) { + case EAST -> Direction.SOUTH; + case SOUTH -> Direction.WEST; + case WEST -> Direction.NORTH; + case NORTH -> Direction.EAST; + default -> throw new IllegalStateException("Unexpected value: " + direction); + }; + } + + public static Direction left(Direction direction) { + return switch (direction) { + case EAST -> Direction.NORTH; + case NORTH -> Direction.WEST; + case WEST -> Direction.SOUTH; + case SOUTH -> Direction.EAST; + default -> throw new IllegalStateException("Unexpected value: " + direction); + }; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/KeyboardUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/KeyboardUtil.java new file mode 100644 index 0000000..9530f88 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/KeyboardUtil.java @@ -0,0 +1,11 @@ +package me.humanbeing.nolongerhuman.util; + +import me.humanbeing.nolongerhuman.features.settings.Bind; + +public class KeyboardUtil { + public static String getKeyName(int key) { + String str = new Bind(key).toString().toUpperCase(); + str = str.replace("KEY.KEYBOARD", "").replace(".", " "); + return str; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/MathUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/MathUtil.java new file mode 100644 index 0000000..21d66ea --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/MathUtil.java @@ -0,0 +1,207 @@ +package me.humanbeing.nolongerhuman.util; + +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.core.BlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.*; + +public class MathUtil + implements Util { + private static final Random random = new Random(); + + public static int getRandom(int min, int max) { + return min + random.nextInt(max - min + 1); + } + + public static double getRandom(double min, double max) { + return Mth.clamp(min + random.nextDouble() * max, min, max); + } + + public static float getRandom(float min, float max) { + return Mth.clamp(min + random.nextFloat() * max, min, max); + } + + public static int clamp(int num, int min, int max) { + return num < min ? min : Math.min(num, max); + } + + public static float clamp(float num, float min, float max) { + return num < min ? min : Math.min(num, max); + } + + public static double clamp(double num, double min, double max) { + return num < min ? min : Math.min(num, max); + } + + public static float sin(float value) { + return Mth.sin(value); + } + + public static float cos(float value) { + return Mth.cos(value); + } + + public static float wrapDegrees(float value) { + return Mth.wrapDegrees(value); + } + + public static double wrapDegrees(double value) { + return Mth.wrapDegrees(value); + } + + public static Vec3 roundVec(Vec3 vec3d, int places) { + return new Vec3(MathUtil.round(vec3d.x, places), MathUtil.round(vec3d.y, places), MathUtil.round(vec3d.z, places)); + } + + public static double square(double input) { + return input * input; + } + + public static double round(double value, int places) { + if (places < 0) { + throw new IllegalArgumentException(); + } + BigDecimal bd = BigDecimal.valueOf(value); + bd = bd.setScale(places, RoundingMode.FLOOR); + return bd.doubleValue(); + } + + public static float wrap(float valI) { + float val = valI % 360.0f; + if (val >= 180.0f) { + val -= 360.0f; + } + if (val < -180.0f) { + val += 360.0f; + } + return val; + } + + public static Vec3 direction(float yaw) { + return new Vec3(Math.cos(MathUtil.degToRad(yaw + 90.0f)), 0.0, Math.sin(MathUtil.degToRad(yaw + 90.0f))); + } + + public static float round(float value, int places) { + if (places < 0) { + throw new IllegalArgumentException(); + } + BigDecimal bd = BigDecimal.valueOf(value); + bd = bd.setScale(places, RoundingMode.FLOOR); + return bd.floatValue(); + } + + public static > Map sortByValue(Map map, boolean descending) { + LinkedList> list = new LinkedList<>(map.entrySet()); + if (descending) { + list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); + } else { + list.sort(Map.Entry.comparingByValue()); + } + LinkedHashMap result = new LinkedHashMap<>(); + for (Map.Entry entry : list) { + result.put(entry.getKey(), entry.getValue()); + } + return result; + } + + public static String getTimeOfDay() { + Calendar c = Calendar.getInstance(); + int timeOfDay = c.get(Calendar.HOUR_OF_DAY); + if (timeOfDay < 12) { + return "Good Morning "; + } + if (timeOfDay < 16) { + return "Good Afternoon "; + } + if (timeOfDay < 21) { + return "Good Evening "; + } + return "Good Night "; + } + + public static double radToDeg(double rad) { + return rad * (double) 57.29578f; + } + + public static double degToRad(double deg) { + return deg * 0.01745329238474369; + } + + public static double getIncremental(double val, double inc) { + double one = 1.0 / inc; + return (double) Math.round(val * one) / one; + } + + public static double[] directionSpeed(double speed) { + float forward = MathUtil.mc.player.input.getMoveVector().y; + float side = MathUtil.mc.player.input.getMoveVector().x; + float yaw = MathUtil.mc.player.yRotO + (MathUtil.mc.player.getYRot() - MathUtil.mc.player.yRotO) * mc.getDeltaTracker().getGameTimeDeltaPartialTick(false); + if (forward != 0.0f) { + if (side > 0.0f) { + yaw += (float) (forward > 0.0f ? -45 : 45); + } else if (side < 0.0f) { + yaw += (float) (forward > 0.0f ? 45 : -45); + } + side = 0.0f; + if (forward > 0.0f) { + forward = 1.0f; + } else if (forward < 0.0f) { + forward = -1.0f; + } + } + double sin = Math.sin(Math.toRadians(yaw + 90.0f)); + double cos = Math.cos(Math.toRadians(yaw + 90.0f)); + double posX = (double) forward * speed * cos + (double) side * speed * sin; + double posZ = (double) forward * speed * sin - (double) side * speed * cos; + return new double[]{posX, posZ}; + } + + public static List getBlockBlocks(Entity entity) { + ArrayList vec3ds = new ArrayList<>(); + AABB bb = entity.getBoundingBox(); + double y = entity.getY(); + double minX = MathUtil.round(bb.minX, 0); + double minZ = MathUtil.round(bb.minZ, 0); + double maxX = MathUtil.round(bb.maxX, 0); + double maxZ = MathUtil.round(bb.maxZ, 0); + if (minX != maxX) { + vec3ds.add(new Vec3(minX, y, minZ)); + vec3ds.add(new Vec3(maxX, y, minZ)); + if (minZ != maxZ) { + vec3ds.add(new Vec3(minX, y, maxZ)); + vec3ds.add(new Vec3(maxX, y, maxZ)); + return vec3ds; + } + } else if (minZ != maxZ) { + vec3ds.add(new Vec3(minX, y, minZ)); + vec3ds.add(new Vec3(minX, y, maxZ)); + return vec3ds; + } + vec3ds.add(entity.position()); + return vec3ds; + } + + public static boolean areVec3dsAligned(Vec3 vec3d1, Vec3 vec3d2) { + return MathUtil.areVec3dsAlignedRetarded(vec3d1, vec3d2); + } + + public static boolean areVec3dsAlignedRetarded(Vec3 vec3d1, Vec3 vec3d2) { + BlockPos pos1 = BlockPos.containing(vec3d1); + BlockPos pos2 = BlockPos.containing(vec3d2.x, vec3d1.y, vec3d2.z); + return pos1.equals(pos2); + } + + public static float[] calcAngle(Vec3 from, Vec3 to) { + double difX = to.x - from.x; + double difY = (to.y - from.y) * -1.0; + double difZ = to.z - from.z; + double dist = Math.sqrt(difX * difX + difZ * difZ); + return new float[]{(float) Mth.wrapDegrees(Math.toDegrees(Math.atan2(difZ, difX)) - 90.0), (float) Mth.wrapDegrees(Math.toDegrees(Math.atan2(difY, dist)))}; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/TextUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/TextUtil.java new file mode 100644 index 0000000..b6f8396 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/TextUtil.java @@ -0,0 +1,35 @@ +package me.humanbeing.nolongerhuman.util; + +import dev.cattyn.catformat.CatFormat; +import dev.cattyn.catformat.fabric.FabricCatFormat; +import me.humanbeing.nolongerhuman.nolongerhuman; +import net.minecraft.network.chat.MutableComponent; + +public final class TextUtil { + private static CatFormat formatter; + + private TextUtil() { + throw new AssertionError("Can't create an instance of utility class"); + } + + public static void init() { + if (formatter != null) throw new IllegalStateException("Formatter is already initialized"); + formatter = new FabricCatFormat(true); + initColors(); + } + + public static MutableComponent text(String content, Object... obj) { + if (obj == null || obj.length == 0) { + return formatter.format(content); + } + return formatter.format(content, obj); + } + + public static CatFormat getFormatter() { + return formatter; + } + + private static void initColors() { + formatter.add("global", () -> nolongerhuman.colorManager.getColorAsInt()); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/TickShiftUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/TickShiftUtil.java new file mode 100644 index 0000000..33e4568 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/TickShiftUtil.java @@ -0,0 +1,38 @@ +package me.humanbeing.nolongerhuman.util; + +import net.minecraft.client.player.LocalPlayer; + +public final class TickShiftUtil { + private static boolean tickShifting; + + private TickShiftUtil() { + } + + public static boolean isTickShifting() { + return tickShifting; + } + + public static int runExtraTicks(LocalPlayer player, int requestedTicks) { + if (player == null || requestedTicks <= 0 || tickShifting) { + return 0; + } + + int shifted = 0; + tickShifting = true; + + try { + for (int i = 0; i < requestedTicks; i++) { + player.tick(); + shifted++; + } + } finally { + tickShifting = false; + } + + return shifted; + } + + public static int runExtraTick(LocalPlayer player) { + return runExtraTicks(player, 1); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/combat/CombatPositionCoordinator.java b/src/main/java/me/humanbeing/nolongerhuman/util/combat/CombatPositionCoordinator.java new file mode 100644 index 0000000..4e42f3e --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/combat/CombatPositionCoordinator.java @@ -0,0 +1,135 @@ +package me.humanbeing.nolongerhuman.util.combat; + +import net.minecraft.core.BlockPos; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class CombatPositionCoordinator { + private static final long DEFAULT_RESERVATION_MS = 750L; + + public enum Source { + AUTO_CRYSTAL, + AUTO_CITY, + ROBOTICS_REMOTE + } + + public enum Type { + CRYSTAL_BASE, + CITY_MINE + } + + public record Reservation(Type type, Source source, BlockPos pos, long expiresAt) { + } + + private record ReservationKey(Type type, BlockPos pos) { + } + + private static final ConcurrentHashMap RESERVATIONS = new ConcurrentHashMap<>(); + + private CombatPositionCoordinator() { + } + + public static void reserveCrystalBase(Source source, BlockPos pos) { + reserve(Type.CRYSTAL_BASE, source, pos, DEFAULT_RESERVATION_MS); + } + + public static void reserveCityMine(Source source, BlockPos pos) { + reserve(Type.CITY_MINE, source, pos, DEFAULT_RESERVATION_MS); + } + + public static void reserve(Type type, Source source, BlockPos pos, long durationMs) { + if (type == null || source == null || pos == null) { + return; + } + + cleanupExpired(); + + BlockPos immutablePos = pos.immutable(); + long expiresAt = System.currentTimeMillis() + Math.max(50L, durationMs); + + RESERVATIONS.put( + new ReservationKey(type, immutablePos), + new Reservation(type, source, immutablePos, expiresAt) + ); + } + + public static void applyRemoteReservation(Type type, BlockPos pos) { + reserve(type, Source.ROBOTICS_REMOTE, pos, DEFAULT_RESERVATION_MS); + } + + public static boolean isCrystalBaseReservedByOther(Source source, BlockPos pos) { + return isReservedByOther(Type.CRYSTAL_BASE, source, pos); + } + + public static boolean isCityMineReservedByOther(Source source, BlockPos pos) { + return isReservedByOther(Type.CITY_MINE, source, pos); + } + + public static boolean isReservedByOther(Type type, Source source, BlockPos pos) { + if (type == null || source == null || pos == null) { + return false; + } + + cleanupExpired(); + + Reservation reservation = RESERVATIONS.get(new ReservationKey(type, pos)); + + return reservation != null && reservation.source() != source; + } + + public static List snapshotLocalReservations() { + cleanupExpired(); + + List reservations = new ArrayList<>(); + + for (Reservation reservation : RESERVATIONS.values()) { + if (reservation.source() == Source.ROBOTICS_REMOTE) { + continue; + } + + reservations.add(reservation); + } + + return reservations; + } + + public static List snapshotAllReservations() { + cleanupExpired(); + + return new ArrayList<>(RESERVATIONS.values()); + } + + public static void clearSource(Source source) { + if (source == null) { + return; + } + + RESERVATIONS.entrySet().removeIf(entry -> entry.getValue().source() == source); + } + + public static void clearRemoteReservations() { + clearSource(Source.ROBOTICS_REMOTE); + } + + public static void clear() { + RESERVATIONS.clear(); + } + + private static void cleanupExpired() { + long now = System.currentTimeMillis(); + + Iterator> iterator = RESERVATIONS.entrySet().iterator(); + + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + + if (entry.getValue().expiresAt() <= now) { + iterator.remove(); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/InventoryUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/InventoryUtil.java new file mode 100644 index 0000000..e5a1146 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/InventoryUtil.java @@ -0,0 +1,107 @@ +package me.humanbeing.nolongerhuman.util.inventory; + +import me.humanbeing.nolongerhuman.util.inventory.strategy.HoldingStrategy; +import me.humanbeing.nolongerhuman.util.inventory.strategy.HotbarStrategy; +import me.humanbeing.nolongerhuman.util.inventory.strategy.InventoryStrategy; +import me.humanbeing.nolongerhuman.util.inventory.strategy.SwapStrategy; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; + +import java.util.EnumSet; +import java.util.List; +import java.util.function.BiPredicate; +import java.util.function.Consumer; +import java.util.function.Predicate; + +public final class InventoryUtil implements Util { + static final Result NONE = new Result(-1, ItemStack.EMPTY, ResultType.NONE); + + public static final EnumSet HOTBAR_SCOPE = EnumSet.of(ResultType.OFFHAND, ResultType.HOTBAR); + public static final EnumSet INVENTORY_SCOPE = EnumSet.of(ResultType.OFFHAND, ResultType.INVENTORY); + public static final EnumSet FULL_SCOPE = EnumSet.of(ResultType.OFFHAND, ResultType.HOTBAR, ResultType.INVENTORY); + + private static final List STRATEGIES = List.of( + HoldingStrategy.INSTANCE, + HotbarStrategy.INSTANCE, + InventoryStrategy.INSTANCE + ); + + + private InventoryUtil() { + throw new AssertionError(); + } + + public static ItemStack cursor() { + return mc.player.containerMenu.getCarried(); + } + + public static int selected() { + return mc.player.getInventory().getSelectedSlot(); + } + + public static void click(int slot, int button, ClickType type) { + int id = mc.player.containerMenu.containerId; + mc.gameMode.handleInventoryMouseClick(id, slot, button, type, mc.player); + } + + public static void withSwap(Result result, Runnable action) { + withSwap(result, r -> action.run()); + } + + public static void withSwap(Result result, Consumer action) { + int lastSlot = selected(); + if (InventoryUtil.swap(result)) { + action.accept(result); + InventoryUtil.swapBack(result, lastSlot); + } + } + + public static void swap(int to) { + if (to < 0 || to > 8) return; + mc.player.getInventory().setSelectedSlot(to); + mc.gameMode.ensureHasSentCarriedItem(); + } + + public static boolean swap(Result result) { + for (SwapStrategy strategy : STRATEGIES) { + if (strategy.swap(result)) + return true; + } + return false; + } + + public static boolean swapBack(Result result, int last) { + for (SwapStrategy strategy : STRATEGIES) { + if (strategy.swapBack(last, result)) + return true; + } + return false; + } + + public static Result find(Item target, EnumSet scopes) { + return find(stack -> stack.is(target), scopes); + } + + public static Result find(Predicate predicate, EnumSet scopes) { + return find((item, scope) -> scopes.contains(scope) && predicate.test(item)); + } + + public static Result find(BiPredicate predicate) { + ItemStack offhand = mc.player.getOffhandItem(); + if (predicate.test(offhand, ResultType.OFFHAND)) { + return Result.fromOffhand(offhand); + } + + for (int i = 0; i < 36; i++) { + ItemStack item = mc.player.getInventory().getItem(i); + ResultType type = i < 9 ? ResultType.HOTBAR : ResultType.INVENTORY; + if (predicate.test(item, type)) { + return new Result(i, item, type); + } + } + + return NONE; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/Result.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/Result.java new file mode 100644 index 0000000..6935ae2 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/Result.java @@ -0,0 +1,26 @@ +package me.humanbeing.nolongerhuman.util.inventory; + +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; + +public record Result(int slot, ItemStack stack, ResultType type, boolean holding) { + public Result(int slot, ItemStack stack, ResultType type) { + this(slot, stack, type, isHolding(type, slot)); + } + + static Result fromOffhand(ItemStack stack) { + return new Result(-1, stack, ResultType.OFFHAND); + } + + public InteractionHand hand() { + return type == ResultType.OFFHAND ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND; + } + + public boolean found() { + return type != ResultType.NONE; + } + + private static boolean isHolding(ResultType type, int slot) { + return type == ResultType.OFFHAND || type == ResultType.HOTBAR && slot == InventoryUtil.selected(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/ResultType.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/ResultType.java new file mode 100644 index 0000000..cccf57d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/ResultType.java @@ -0,0 +1,8 @@ +package me.humanbeing.nolongerhuman.util.inventory; + +public enum ResultType { + HOTBAR, + INVENTORY, + OFFHAND, + NONE +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/HoldingStrategy.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/HoldingStrategy.java new file mode 100644 index 0000000..273a105 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/HoldingStrategy.java @@ -0,0 +1,20 @@ +package me.humanbeing.nolongerhuman.util.inventory.strategy; + +import me.humanbeing.nolongerhuman.util.inventory.Result; + +public final class HoldingStrategy implements SwapStrategy{ + public static final HoldingStrategy INSTANCE = new HoldingStrategy(); + + private HoldingStrategy() { + } + + @Override + public boolean swap(Result result) { + return result.holding(); + } + + @Override + public boolean swapBack(int last, Result result) { + return result.holding(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/HotbarStrategy.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/HotbarStrategy.java new file mode 100644 index 0000000..afb337c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/HotbarStrategy.java @@ -0,0 +1,30 @@ +package me.humanbeing.nolongerhuman.util.inventory.strategy; + +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; + +public final class HotbarStrategy implements SwapStrategy { + public static final HotbarStrategy INSTANCE = new HotbarStrategy(); + + private HotbarStrategy() { + } + + @Override + public boolean swap(Result result) { + if (result.type() == ResultType.HOTBAR) { + InventoryUtil.swap(result.slot()); + return true; + } + return false; + } + + @Override + public boolean swapBack(int last, Result result) { + if (result.type() == ResultType.HOTBAR) { + InventoryUtil.swap(last); + return true; + } + return false; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/InventoryStrategy.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/InventoryStrategy.java new file mode 100644 index 0000000..ba74d8c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/InventoryStrategy.java @@ -0,0 +1,31 @@ +package me.humanbeing.nolongerhuman.util.inventory.strategy; + +import me.humanbeing.nolongerhuman.util.inventory.InventoryUtil; +import me.humanbeing.nolongerhuman.util.inventory.Result; +import me.humanbeing.nolongerhuman.util.inventory.ResultType; +import net.minecraft.world.inventory.ClickType; + +public final class InventoryStrategy implements SwapStrategy { + public static final InventoryStrategy INSTANCE = new InventoryStrategy(); + + private InventoryStrategy() { + } + + @Override + public boolean swap(Result result) { + if (result.type() != ResultType.INVENTORY && result.type() != ResultType.HOTBAR) + return false; + int slot = inventorySlot(result); + InventoryUtil.click(slot, InventoryUtil.selected(), ClickType.SWAP); + return true; + } + + @Override + public boolean swapBack(int last, Result result) { + return swap(result); + } + + private static int inventorySlot(Result result) { + return result.type() == ResultType.HOTBAR ? result.slot() + 36 : result.slot(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/SwapStrategy.java b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/SwapStrategy.java new file mode 100644 index 0000000..470c2a2 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/inventory/strategy/SwapStrategy.java @@ -0,0 +1,9 @@ +package me.humanbeing.nolongerhuman.util.inventory.strategy; + +import me.humanbeing.nolongerhuman.util.inventory.Result; + +public interface SwapStrategy { + boolean swap(Result result); + + boolean swapBack(int last, Result result); +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/models/Timer.java b/src/main/java/me/humanbeing/nolongerhuman/util/models/Timer.java new file mode 100644 index 0000000..b424417 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/models/Timer.java @@ -0,0 +1,45 @@ +package me.humanbeing.nolongerhuman.util.models; + +public class Timer { + private long time = -1L; + + public boolean passedS(double s) { + return this.getMs(System.nanoTime() - this.time) >= (long) (s * 1000.0); + } + + public boolean passedM(double m) { + return this.getMs(System.nanoTime() - this.time) >= (long) (m * 1000.0 * 60.0); + } + + public boolean passedDms(double dms) { + return this.getMs(System.nanoTime() - this.time) >= (long) (dms * 10.0); + } + + public boolean passedDs(double ds) { + return this.getMs(System.nanoTime() - this.time) >= (long) (ds * 100.0); + } + + public boolean passedMs(long ms) { + return this.getMs(System.nanoTime() - this.time) >= ms; + } + + public boolean passedNS(long ns) { + return System.nanoTime() - this.time >= ns; + } + + public void setMs(long ms) { + this.time = System.nanoTime() - ms * 1000000L; + } + + public long getPassedTimeMs() { + return this.getMs(System.nanoTime() - this.time); + } + + public void reset() { + this.time = System.nanoTime(); + } + + public long getMs(long time) { + return time / 1000000L; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/player/ChatUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/player/ChatUtil.java new file mode 100644 index 0000000..d2feefd --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/player/ChatUtil.java @@ -0,0 +1,51 @@ +package me.humanbeing.nolongerhuman.util.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.ducks.render.IChatComponent; +import me.humanbeing.nolongerhuman.features.commands.Command; +import net.minecraft.ChatFormatting; +import net.minecraft.client.GuiMessage; +import net.minecraft.client.GuiMessageTag; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MessageSignature; +import net.minecraft.network.chat.Style; + +import java.nio.charset.StandardCharsets; + +import static me.humanbeing.nolongerhuman.util.traits.Util.mc; + +public class ChatUtil { + public static void sendMessage(Component message, String identifier) { + sendClientSideMessage(Component.empty() + .setStyle(Style.EMPTY.withColor(ChatFormatting.GRAY)) + .append("<") + .append(getClientNameComponent()) + .append(">") + .append(" ") + .append(message), identifier); + } + + public static void sendClientSideMessage(Component message, String identifier) { + if (Command.nullCheck()) return; + + IChatComponent chat = (IChatComponent) mc.gui.getChat(); + MessageSignature signature = new MessageSignature(get256Bytes(identifier)); + chat.nolongerhuman$removeMessage(signature); + chat.nolongerhuman$addMessage(new GuiMessage(mc.gui.getGuiTicks(), message, signature, getMessageTag())); + } + + public static Component getClientNameComponent() { + return Component.empty().withColor(nolongerhuman.colorManager.getColorAsInt()).append("NoLongerHuman"); + } + + private static GuiMessageTag getMessageTag() { + return new GuiMessageTag(nolongerhuman.colorManager.getColorAsInt(), null, null, null); + } + + private static byte[] get256Bytes(String identifier) { + byte[] bytes = new byte[256]; + byte[] identifierBytes = identifier.getBytes(StandardCharsets.UTF_8); + System.arraycopy(identifierBytes, 0, bytes, 0, Math.min(bytes.length, identifierBytes.length)); + return bytes; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/player/RoboticsMovementUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/player/RoboticsMovementUtil.java new file mode 100644 index 0000000..c123782 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/player/RoboticsMovementUtil.java @@ -0,0 +1,213 @@ +package me.humanbeing.nolongerhuman.util.player; + +import me.humanbeing.nolongerhuman.nolongerhuman; +import me.humanbeing.nolongerhuman.features.modules.movement.Anchor; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.phys.Vec3; + +import java.lang.reflect.Field; + +public final class RoboticsMovementUtil { + private static final Minecraft mc = Minecraft.getInstance(); + + + private static final double WALK_BLOCKS_PER_TICK = 0.21585D; + private static final double SPRINT_BLOCKS_PER_TICK = 0.28060D; + private static final double SNEAK_BLOCKS_PER_TICK = 0.06550D; + + private RoboticsMovementUtil() { + } + + public static Vec3 getCorrectionMovement( + LocalPlayer player, + Vec3 targetPosition, + double tolerance, + double strength, + double maxStep, + boolean correctY, + boolean slideCompensation + ) { + if (player == null || targetPosition == null) { + return Vec3.ZERO; + } + + Vec3 playerPosition = player.position(); + + double differenceX = targetPosition.x - playerPosition.x; + double differenceY = correctY ? targetPosition.y - playerPosition.y : 0.0D; + double differenceZ = targetPosition.z - playerPosition.z; + + Vec3 difference = new Vec3(differenceX, differenceY, differenceZ); + double distance = difference.length(); + + if (distance <= tolerance) { + return Vec3.ZERO; + } + + double clampedStrength = clamp(strength, 0.05D, 1.0D); + Vec3 correction = difference.scale(clampedStrength); + + if (slideCompensation) { + correction = correction.subtract(getPredictedSlide(player, correctY)); + } + + double stepCap = Math.max(0.001D, Math.abs(maxStep)); + + if (correction.length() > stepCap) { + correction = correction.normalize().scale(stepCap); + } + + if (correction.length() > distance) { + return difference; + } + + return correction; + } + + public static double getCorrectionDistance(Vec3 playerPosition, Vec3 targetPosition, boolean correctY) { + if (playerPosition == null || targetPosition == null) { + return 0.0D; + } + + double differenceX = targetPosition.x - playerPosition.x; + double differenceY = correctY ? targetPosition.y - playerPosition.y : 0.0D; + double differenceZ = targetPosition.z - playerPosition.z; + + return Math.sqrt( + differenceX * differenceX + + differenceY * differenceY + + differenceZ * differenceZ + ); + } + + public static double getCorrectionPathStep( + LocalPlayer player, + boolean sneaking, + boolean sprinting, + boolean forceSprint, + boolean applyPotionSpeed + ) { + double step; + + if (forceSprint) { + step = SPRINT_BLOCKS_PER_TICK; + } else if (sneaking) { + step = SNEAK_BLOCKS_PER_TICK; + } else if (sprinting) { + step = SPRINT_BLOCKS_PER_TICK; + } else { + step = WALK_BLOCKS_PER_TICK; + } + + if (applyPotionSpeed) { + step = getPotionSpeed(player, step); + } + + return step; + } + + private static Vec3 getPredictedSlide(LocalPlayer player, boolean vertical) { + Vec3 velocity = player.getDeltaMovement(); + + double horizontalFriction = player.onGround() ? 0.546D : 0.91D; + + double slideX = velocity.x * horizontalFriction; + double slideZ = velocity.z * horizontalFriction; + + double slideY = 0.0D; + + if (vertical && !player.onGround()) { + slideY = (velocity.y - 0.08D) * 0.98D; + } + + return new Vec3(slideX, slideY, slideZ); + } + + public static double getPotionSpeed(LocalPlayer player, double baseSpeed) { + if (player == null) { + return baseSpeed; + } + + double speed = baseSpeed; + + MobEffectInstance speedEffect = player.getEffect(MobEffects.SPEED); + + if (speedEffect != null) { + speed *= 1.0D + 0.2D * (speedEffect.getAmplifier() + 1); + } + + MobEffectInstance slownessEffect = player.getEffect(MobEffects.SLOWNESS); + + if (slownessEffect != null) { + speed /= 1.0D + 0.2D * (slownessEffect.getAmplifier() + 1); + } + + return speed; + } + + public static boolean isBeingPulledByAnchor() { + if (mc.player == null || nolongerhuman.moduleManager == null) { + return false; + } + + Anchor anchor = nolongerhuman.moduleManager.getModuleByClass(Anchor.class); + + if (anchor == null || !anchor.isEnabled()) { + return false; + } + + BlockPos anchorPos = getAnchorPosition(anchor); + + if (anchorPos == null) { + return false; + } + + double centerX = anchorPos.getX() + 0.5D; + double centerZ = anchorPos.getZ() + 0.5D; + + double differenceX = centerX - mc.player.getX(); + double differenceZ = centerZ - mc.player.getZ(); + + return differenceX * differenceX + differenceZ * differenceZ > 0.0036D; + } + + private static BlockPos getAnchorPosition(Anchor anchor) { + BlockPos anchoredIn = getBlockPosField(anchor, "anchoredIn"); + + if (anchoredIn != null) { + return anchoredIn; + } + + return getBlockPosField(anchor, "lastAnchoredHole"); + } + + private static BlockPos getBlockPosField(Object object, String fieldName) { + for (Class clazz = object.getClass(); clazz != null; clazz = clazz.getSuperclass()) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + + Object value = field.get(object); + + if (value instanceof BlockPos pos) { + return pos; + } + + return null; + } catch (NoSuchFieldException ignored) { + } catch (IllegalAccessException ignored) { + return null; + } + } + + return null; + } + + private static double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/AWTFontRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/AWTFontRenderer.java new file mode 100644 index 0000000..bea986a --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/AWTFontRenderer.java @@ -0,0 +1,721 @@ +package me.humanbeing.nolongerhuman.util.render; + +import com.mojang.blaze3d.platform.NativeImage; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.network.chat.Style; +import net.minecraft.network.chat.TextColor; +import net.minecraft.resources.Identifier; +import net.minecraft.util.FormattedCharSequence; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.util.HashMap; +import java.util.Map; + +public class AWTFontRenderer { + private static final int SUPERSAMPLE = 2; + private static final int PADDING = 3; + private static final int ATLAS_WIDTH = 1024; + private static final float SHADOW_ALPHA = 0.34f; + private static final float SHADOW_BRIGHTNESS = 0.25f; + + private static final int[] MC_COLORS = new int[]{ + 0x000000, + 0x0000AA, + 0x00AA00, + 0x00AAAA, + 0xAA0000, + 0xAA00AA, + 0xFFAA00, + 0xAAAAAA, + 0x555555, + 0x5555FF, + 0x55FF55, + 0x55FFFF, + 0xFF5555, + 0xFF55FF, + 0xFFFF55, + 0xFFFFFF + }; + + private final Font baseFont; + private final Map fonts = new HashMap<>(); + private final Map metrics = new HashMap<>(); + private final Map glyphs = new HashMap<>(); + + private final int ascent; + private final int fontHeight; + private final int cellHeight; + + private BufferedImage atlasImage; + private int atlasHeight; + private int cursorX; + private int cursorY; + + private DynamicTexture texture; + private Identifier atlasId; + + public AWTFontRenderer(String fontName, float size) { + this.baseFont = createFont(fontName, size * SUPERSAMPLE); + + FontMetrics baseMetrics = getMetrics(false, false); + this.ascent = baseMetrics.getAscent(); + this.fontHeight = baseMetrics.getHeight(); + this.cellHeight = fontHeight + PADDING * 2; + + this.atlasHeight = cellHeight * 8; + this.atlasImage = new BufferedImage(ATLAS_WIDTH, atlasHeight, BufferedImage.TYPE_INT_ARGB); + this.atlasId = Identifier.fromNamespaceAndPath( + "nolongerhuman", + "awt_font_atlas_" + System.nanoTime() + ); + + rebuildTexture(); + preloadAscii(); + } + + private Font createFont(String fontName, float size) { + String safeName = fontName == null || fontName.isBlank() ? "Arial" : fontName; + + for (String available : GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()) { + if (available.equalsIgnoreCase(safeName)) { + return new Font(available, Font.PLAIN, 1).deriveFont(size); + } + } + + return new Font("Arial", Font.PLAIN, 1).deriveFont(size); + } + + private Font getFont(boolean bold, boolean italic) { + FontKey key = new FontKey(bold, italic); + Font cached = fonts.get(key); + + if (cached != null) { + return cached; + } + + int style = Font.PLAIN; + + if (bold) { + style |= Font.BOLD; + } + + if (italic) { + style |= Font.ITALIC; + } + + Font font = baseFont.deriveFont(style); + fonts.put(key, font); + return font; + } + + private FontMetrics getMetrics(boolean bold, boolean italic) { + FontKey key = new FontKey(bold, italic); + FontMetrics cached = metrics.get(key); + + if (cached != null) { + return cached; + } + + BufferedImage probe = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D probeGraphics = probe.createGraphics(); + + applyHints(probeGraphics); + probeGraphics.setFont(getFont(bold, italic)); + + FontMetrics fontMetrics = probeGraphics.getFontMetrics(); + probeGraphics.dispose(); + + metrics.put(key, fontMetrics); + return fontMetrics; + } + + private void preloadAscii() { + for (char c = 32; c < 127; c++) { + putGlyph(c, false, false, false); + putGlyph(c, true, false, false); + putGlyph(c, false, true, false); + putGlyph(c, true, true, false); + } + + uploadFull(); + } + + private Glyph loadGlyph(char c, boolean bold, boolean italic) { + GlyphKey key = new GlyphKey(c, bold, italic); + Glyph cached = glyphs.get(key); + + if (cached != null) { + return cached; + } + + return putGlyph(c, bold, italic, true); + } + + private Glyph putGlyph(char c, boolean bold, boolean italic, boolean upload) { + Font font = getFont(bold, italic); + FontMetrics fontMetrics = getMetrics(bold, italic); + + int advance = Math.max(fontMetrics.charWidth(c), 1); + int width = advance + PADDING * 2 + (italic ? SUPERSAMPLE * 2 : 0); + int height = cellHeight; + + if (cursorX + width > ATLAS_WIDTH) { + cursorX = 0; + cursorY += cellHeight; + } + + if (cursorY + height > atlasHeight) { + growAtlas(); + } + + Graphics2D graphics = atlasImage.createGraphics(); + + applyHints(graphics); + graphics.setFont(font); + graphics.setColor(Color.WHITE); + graphics.drawString(String.valueOf(c), cursorX + PADDING, cursorY + PADDING + ascent); + graphics.dispose(); + + Glyph glyph = new Glyph(cursorX, cursorY, width, height, advance); + glyphs.put(new GlyphKey(c, bold, italic), glyph); + + if (upload) { + uploadRegion(cursorX, cursorY, width, height); + } + + cursorX += width; + return glyph; + } + + private void growAtlas() { + int newHeight = atlasHeight * 2; + + BufferedImage bigger = new BufferedImage(ATLAS_WIDTH, newHeight, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = bigger.createGraphics(); + + graphics.drawImage(atlasImage, 0, 0, null); + graphics.dispose(); + + atlasImage = bigger; + atlasHeight = newHeight; + + rebuildTexture(); + } + + private void rebuildTexture() { + Minecraft mc = Minecraft.getInstance(); + + if (texture != null && atlasId != null) { + mc.getTextureManager().release(atlasId); + } + + texture = new DynamicTexture(() -> "awt_font_atlas", ATLAS_WIDTH, atlasHeight, false); + mc.getTextureManager().register(atlasId, texture); + + uploadFull(); + } + + private void uploadFull() { + if (texture == null || texture.getPixels() == null) { + return; + } + + NativeImage pixels = texture.getPixels(); + + for (int py = 0; py < atlasHeight; py++) { + for (int px = 0; px < ATLAS_WIDTH; px++) { + pixels.setPixel(px, py, toAbgr(atlasImage.getRGB(px, py))); + } + } + + texture.upload(); + } + + private void uploadRegion(int u, int v, int width, int height) { + if (texture == null || texture.getPixels() == null) { + return; + } + + NativeImage pixels = texture.getPixels(); + + int maxX = Math.min(u + width, ATLAS_WIDTH); + int maxY = Math.min(v + height, atlasHeight); + + for (int py = v; py < maxY; py++) { + for (int px = u; px < maxX; px++) { + pixels.setPixel(px, py, toAbgr(atlasImage.getRGB(px, py))); + } + } + + texture.upload(); + } + + private void applyHints(Graphics2D graphics) { + graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + } + + public float drawChar(GuiGraphics context, char c, float x, float y, int color, boolean shadow) { + context.pose().pushMatrix(); + context.pose().scale(1.0f / SUPERSAMPLE, 1.0f / SUPERSAMPLE); + + float width = drawStyledChar( + context, + c, + x, + y, + normalize(color), + shadow, + false, + false, + false, + false, + false, + 0 + ); + + context.pose().popMatrix(); + + return width; + } + + public float drawChar(GuiGraphics context, char c, float x, float y, int color) { + return drawChar(context, c, x, y, color, false); + } + + public float drawString(GuiGraphics context, String text, float x, float y, int color, boolean shadow) { + if (text == null || text.isEmpty()) { + return 0.0f; + } + + int baseColor = normalize(color); + int currentColor = baseColor; + + boolean bold = false; + boolean italic = false; + boolean underline = false; + boolean strikethrough = false; + boolean obfuscated = false; + + float cursor = x; + int visibleIndex = 0; + + context.pose().pushMatrix(); + context.pose().scale(1.0f / SUPERSAMPLE, 1.0f / SUPERSAMPLE); + + for (int i = 0; i < text.length(); i++) { + char character = text.charAt(i); + + if (character == '\n' || character == '\r') { + continue; + } + + if (character == '§' && i + 1 < text.length()) { + char code = Character.toLowerCase(text.charAt(++i)); + + int colorIndex = getColorIndex(code); + + if (colorIndex >= 0) { + currentColor = withAlpha(MC_COLORS[colorIndex], baseColor); + bold = false; + italic = false; + underline = false; + strikethrough = false; + obfuscated = false; + continue; + } + + switch (code) { + case 'k' -> obfuscated = true; + case 'l' -> bold = true; + case 'm' -> strikethrough = true; + case 'n' -> underline = true; + case 'o' -> italic = true; + case 'r' -> { + currentColor = baseColor; + bold = false; + italic = false; + underline = false; + strikethrough = false; + obfuscated = false; + } + default -> { + } + } + + continue; + } + + cursor += drawStyledChar( + context, + character, + cursor, + y, + currentColor, + shadow, + bold, + italic, + underline, + strikethrough, + obfuscated, + visibleIndex + ); + + visibleIndex++; + } + + context.pose().popMatrix(); + + return cursor - x; + } + + public float drawString(GuiGraphics context, String text, float x, float y, int color) { + return drawString(context, text, x, y, color, false); + } + + public float drawFormattedCharSequence( + GuiGraphics context, + FormattedCharSequence sequence, + float x, + float y, + int color, + boolean shadow + ) { + if (sequence == null) { + return 0.0f; + } + + int baseColor = normalize(color); + float[] cursor = new float[]{x}; + int[] visibleIndex = new int[]{0}; + + context.pose().pushMatrix(); + context.pose().scale(1.0f / SUPERSAMPLE, 1.0f / SUPERSAMPLE); + + sequence.accept((index, style, codePoint) -> { + char character = codePointToRenderableChar(codePoint); + + if (character == '\n' || character == '\r') { + return true; + } + + int styledColor = getStyleColor(style, baseColor); + + boolean bold = style != null && style.isBold(); + boolean italic = style != null && style.isItalic(); + boolean underline = style != null && style.isUnderlined(); + boolean strikethrough = style != null && style.isStrikethrough(); + boolean obfuscated = style != null && style.isObfuscated(); + + cursor[0] += drawStyledChar( + context, + character, + cursor[0], + y, + styledColor, + shadow, + bold, + italic, + underline, + strikethrough, + obfuscated, + visibleIndex[0] + ); + + visibleIndex[0]++; + return true; + }); + + context.pose().popMatrix(); + + return cursor[0] - x; + } + + private float drawStyledChar( + GuiGraphics context, + char character, + float x, + float y, + int color, + boolean shadow, + boolean bold, + boolean italic, + boolean underline, + boolean strikethrough, + boolean obfuscated, + int visibleIndex + ) { + char renderChar = obfuscated && character != ' ' + ? getObfuscatedChar(visibleIndex) + : character; + + Glyph glyph = loadGlyph(renderChar, bold, italic); + + int baseColor = normalize(color); + int shadowColor = applyShadow(baseColor); + + int sx = Math.round(x * SUPERSAMPLE) - PADDING; + int sy = Math.round(y * SUPERSAMPLE) - PADDING; + + if (shadow) { + blitGlyph( + context, + glyph, + sx + SUPERSAMPLE, + sy + SUPERSAMPLE, + shadowColor + ); + } + + blitGlyph(context, glyph, sx, sy, baseColor); + + if (underline) { + int lineY = sy + PADDING + ascent + 1; + drawLine(context, sx + PADDING, lineY, sx + PADDING + glyph.advance, lineY + Math.max(1, SUPERSAMPLE), baseColor); + } + + if (strikethrough) { + int lineY = sy + PADDING + ascent / 2; + drawLine(context, sx + PADDING, lineY, sx + PADDING + glyph.advance, lineY + Math.max(1, SUPERSAMPLE), baseColor); + } + + return glyph.advance / (float) SUPERSAMPLE; + } + + private void drawLine(GuiGraphics context, int x1, int y1, int x2, int y2, int color) { + context.fill(x1, y1, x2, y2, color); + } + + public float getStringWidth(String text) { + if (text == null || text.isEmpty()) { + return 0.0f; + } + + boolean bold = false; + boolean italic = false; + boolean underline = false; + boolean strikethrough = false; + boolean obfuscated = false; + + float width = 0.0f; + + for (int i = 0; i < text.length(); i++) { + char character = text.charAt(i); + + if (character == '\n' || character == '\r') { + continue; + } + + if (character == '§' && i + 1 < text.length()) { + char code = Character.toLowerCase(text.charAt(++i)); + + int colorIndex = getColorIndex(code); + + if (colorIndex >= 0) { + bold = false; + italic = false; + underline = false; + strikethrough = false; + obfuscated = false; + continue; + } + + switch (code) { + case 'k' -> obfuscated = true; + case 'l' -> bold = true; + case 'm' -> strikethrough = true; + case 'n' -> underline = true; + case 'o' -> italic = true; + case 'r' -> { + bold = false; + italic = false; + underline = false; + strikethrough = false; + obfuscated = false; + } + default -> { + } + } + + continue; + } + + width += loadGlyph(character, bold, italic).advance; + } + + return width / SUPERSAMPLE; + } + + public float getFormattedWidth(FormattedCharSequence sequence) { + if (sequence == null) { + return 0.0f; + } + + float[] width = new float[]{0.0f}; + + sequence.accept((index, style, codePoint) -> { + char character = codePointToRenderableChar(codePoint); + + if (character == '\n' || character == '\r') { + return true; + } + + boolean bold = style != null && style.isBold(); + boolean italic = style != null && style.isItalic(); + + width[0] += loadGlyph(character, bold, italic).advance; + return true; + }); + + return width[0] / SUPERSAMPLE; + } + + public float getFontHeight() { + return fontHeight / (float) SUPERSAMPLE; + } + + public void destroy() { + if (atlasId != null) { + Minecraft.getInstance().getTextureManager().release(atlasId); + } + + glyphs.clear(); + fonts.clear(); + metrics.clear(); + texture = null; + atlasId = null; + } + + private void blitGlyph(GuiGraphics context, Glyph glyph, int x, int y, int color) { + context.blit( + RenderPipelines.GUI_TEXTURED, + atlasId, + x, + y, + (float) glyph.u, + (float) glyph.v, + glyph.width, + glyph.height, + ATLAS_WIDTH, + atlasHeight, + color + ); + } + + private int getStyleColor(Style style, int fallbackColor) { + if (style == null) { + return fallbackColor; + } + + TextColor color = style.getColor(); + + if (color == null) { + return fallbackColor; + } + + return withAlpha(color.getValue(), fallbackColor); + } + + private static char codePointToRenderableChar(int codePoint) { + if (Character.isValidCodePoint(codePoint) && codePoint <= Character.MAX_VALUE) { + return (char) codePoint; + } + + return '?'; + } + + private static char getObfuscatedChar(int visibleIndex) { + long seed = System.currentTimeMillis() / 60L + visibleIndex * 31L; + return (char) (33 + Math.floorMod(seed, 94)); + } + + private static int getColorIndex(char code) { + return switch (code) { + case '0' -> 0; + case '1' -> 1; + case '2' -> 2; + case '3' -> 3; + case '4' -> 4; + case '5' -> 5; + case '6' -> 6; + case '7' -> 7; + case '8' -> 8; + case '9' -> 9; + case 'a' -> 10; + case 'b' -> 11; + case 'c' -> 12; + case 'd' -> 13; + case 'e' -> 14; + case 'f' -> 15; + default -> -1; + }; + } + + private static int withAlpha(int rgb, int alphaSource) { + int alpha = (alphaSource >>> 24) & 0xFF; + + if (alpha == 0) { + alpha = 0xFF; + } + + return (alpha << 24) | (rgb & 0xFFFFFF); + } + + private static int toAbgr(int argb) { + int a = (argb >>> 24) & 0xFF; + int r = (argb >> 16) & 0xFF; + int g = (argb >> 8) & 0xFF; + int b = argb & 0xFF; + + return (a << 24) | (b << 16) | (g << 8) | r; + } + + private static int normalize(int color) { + return (color >>> 24) == 0 ? color | 0xFF000000 : color; + } + + private static int applyShadow(int color) { + int a = (color >>> 24) & 0xFF; + int r = (int) (((color >> 16) & 0xFF) * SHADOW_BRIGHTNESS); + int g = (int) (((color >> 8) & 0xFF) * SHADOW_BRIGHTNESS); + int b = (int) ((color & 0xFF) * SHADOW_BRIGHTNESS); + int shadowAlpha = (int) (a * SHADOW_ALPHA); + + return (shadowAlpha << 24) | (r << 16) | (g << 8) | b; + } + + private record FontKey(boolean bold, boolean italic) { + } + + private record GlyphKey(char character, boolean bold, boolean italic) { + } + + private static final class Glyph { + private final int u; + private final int v; + private final int width; + private final int height; + private final int advance; + + private Glyph(int u, int v, int width, int height, int advance) { + this.u = u; + this.v = v; + this.width = width; + this.height = height; + this.advance = advance; + } + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/CrystalChamsRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/CrystalChamsRenderer.java new file mode 100644 index 0000000..eeae1f4 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/CrystalChamsRenderer.java @@ -0,0 +1,1099 @@ +package me.humanbeing.nolongerhuman.util.render; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.boss.enderdragon.EndCrystal; +import net.minecraft.world.phys.Vec3; +import org.joml.Quaternionf; + +import java.awt.Color; + +public final class CrystalChamsRenderer implements Util { + private static final float SINE_45_DEGREES = (float) Math.sin(Math.PI / 4.0D); + private static final float FRAME_HALF_SIZE = 0.25F; + private static final float CORE_HALF_SIZE = 0.16F; + private static final float VANILLA_Y_OFFSET_FIX = -1.41F; + + private CrystalChamsRenderer() { + } + + public static void renderCrystal( + PoseStack stack, + EndCrystal crystal, + float tickDelta, + Color outerFillColor, + Color outerWireColor, + Color coreFillColor, + Color coreWireColor, + float lineWidth, + boolean lines, + boolean fill, + boolean renderCore, + boolean throughWalls, + + boolean gradient, + Color gradientColorA, + Color gradientColorB, + float gradientSpeed, + float gradientScale, + float gradientStrength, + + boolean ripple, + Color rippleColorA, + Color rippleColorB, + float rippleSpeed, + float rippleScale, + float rippleStrength, + + boolean shine, + Color shineColor, + float shineSpeed, + float shineWidth, + float shineStrength, + + boolean alternating, + Color alternatingColor, + float alternatingSpeed, + float alternatingScale, + float alternatingStrength, + + boolean waves, + Color waveColorA, + Color waveColorB, + float waveSpeed, + float waveScale, + float waveStrength, + + boolean glint, + Color glintColor, + float glintSpeed, + float glintWidth, + float glintStrength, + + boolean glow, + Color glowColor, + float glowSpeed, + float glowStrength, + + boolean smoke, + Color smokeColorA, + Color smokeColorB, + float smokeSpeed, + float smokeScale, + float smokeStrength, + + boolean water, + Color waterColorA, + Color waterColorB, + float waterSpeed, + float waterScale, + float waterStrength, + + boolean blurry, + Color blurryColor, + float blurryStrength, + + boolean snow, + Color snowColor, + float snowSpeed, + float snowScale, + float snowStrength, + + boolean aurora, + Color auroraColorA, + Color auroraColorB, + float auroraSpeed, + float auroraScale, + float auroraStrength, + + boolean plasma, + Color plasmaColorA, + Color plasmaColorB, + float plasmaSpeed, + float plasmaScale, + float plasmaStrength, + + boolean scanlines, + Color scanlineColor, + float scanlineSpeed, + float scanlineScale, + float scanlineStrength, + + boolean electric, + Color electricColor, + float electricSpeed, + float electricScale, + float electricStrength, + + boolean rainbow, + float rainbowSpeed, + float rainbowScale, + float rainbowSaturation, + float rainbowStrength + ) { + if (crystal == null) { + return; + } + + RenderStyle style = new RenderStyle( + throughWalls, + + gradient, + gradientColorA, + gradientColorB, + gradientSpeed, + gradientScale, + gradientStrength, + + ripple, + rippleColorA, + rippleColorB, + rippleSpeed, + rippleScale, + rippleStrength, + + shine, + shineColor, + shineSpeed, + shineWidth, + shineStrength, + + alternating, + alternatingColor, + alternatingSpeed, + alternatingScale, + alternatingStrength, + + waves, + waveColorA, + waveColorB, + waveSpeed, + waveScale, + waveStrength, + + glint, + glintColor, + glintSpeed, + glintWidth, + glintStrength, + + glow, + glowColor, + glowSpeed, + glowStrength, + + smoke, + smokeColorA, + smokeColorB, + smokeSpeed, + smokeScale, + smokeStrength, + + water, + waterColorA, + waterColorB, + waterSpeed, + waterScale, + waterStrength, + + blurry, + blurryColor, + blurryStrength, + + snow, + snowColor, + snowSpeed, + snowScale, + snowStrength, + + aurora, + auroraColorA, + auroraColorB, + auroraSpeed, + auroraScale, + auroraStrength, + + plasma, + plasmaColorA, + plasmaColorB, + plasmaSpeed, + plasmaScale, + plasmaStrength, + + scanlines, + scanlineColor, + scanlineSpeed, + scanlineScale, + scanlineStrength, + + electric, + electricColor, + electricSpeed, + electricScale, + electricStrength, + + rainbow, + rainbowSpeed, + rainbowScale, + rainbowSaturation, + rainbowStrength + ); + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + double x = Mth.lerp(tickDelta, crystal.xo, crystal.getX()); + double y = Mth.lerp(tickDelta, crystal.yo, crystal.getY()); + double z = Mth.lerp(tickDelta, crystal.zo, crystal.getZ()); + + stack.pushPose(); + + stack.translate( + x - camera.x(), + y - camera.y() + VANILLA_Y_OFFSET_FIX, + z - camera.z() + ); + + float yOffset = getCrystalYOffset(crystal, tickDelta); + float rotation = ((float) crystal.time + tickDelta) * 3.0F; + + stack.pushPose(); + + stack.scale(2.0F, 2.0F, 2.0F); + stack.translate(0.0F, -0.5F, 0.0F); + stack.mulPose(Axis.YP.rotationDegrees(rotation)); + stack.translate(0.0F, 1.5F + yOffset / 2.0F, 0.0F); + + stack.mulPose(new Quaternionf().setAngleAxis( + 1.0471976F, + SINE_45_DEGREES, + 0.0F, + SINE_45_DEGREES + )); + + renderFrameCube(stack, outerFillColor, outerWireColor, lineWidth, lines, fill, style); + + stack.scale(0.875F, 0.875F, 0.875F); + stack.mulPose(new Quaternionf().setAngleAxis( + 1.0471976F, + SINE_45_DEGREES, + 0.0F, + SINE_45_DEGREES + )); + stack.mulPose(Axis.YP.rotationDegrees(rotation)); + + renderFrameCube(stack, outerFillColor, outerWireColor, lineWidth, lines, fill, style); + + stack.scale(0.875F, 0.875F, 0.875F); + stack.mulPose(new Quaternionf().setAngleAxis( + 1.0471976F, + SINE_45_DEGREES, + 0.0F, + SINE_45_DEGREES + )); + stack.mulPose(Axis.YP.rotationDegrees(rotation)); + + if (renderCore) { + renderCoreCube(stack, coreFillColor, coreWireColor, lineWidth, lines, fill, style); + } + + stack.popPose(); + stack.popPose(); + } + + private static float getCrystalYOffset(EndCrystal crystal, float tickDelta) { + float age = (float) crystal.time + tickDelta; + float bob = Mth.sin(age * 0.2F) / 2.0F + 0.5F; + return (bob * bob + bob) * 0.4F; + } + + private static void renderFrameCube( + PoseStack stack, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + renderCube(stack, -FRAME_HALF_SIZE, -FRAME_HALF_SIZE, -FRAME_HALF_SIZE, FRAME_HALF_SIZE, FRAME_HALF_SIZE, FRAME_HALF_SIZE, fillColor, wireColor, lineWidth, lines, fill, style); + } + + private static void renderCoreCube( + PoseStack stack, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + renderCube(stack, -CORE_HALF_SIZE, -CORE_HALF_SIZE, -CORE_HALF_SIZE, CORE_HALF_SIZE, CORE_HALF_SIZE, CORE_HALF_SIZE, fillColor, wireColor, lineWidth, lines, fill, style); + } + + private static void renderCube( + PoseStack stack, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + if (fill && fillColor.getAlpha() > 0) { + BufferBuilder quads = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + addCubeQuads(quads, stack, minX, minY, minZ, maxX, maxY, maxZ, fillColor, style); + + if (style.throughWalls()) { + Layers.quads().draw(quads.buildOrThrow()); + } else { + Layers.depthQuads().draw(quads.buildOrThrow()); + } + } + + if (lines && wireColor.getAlpha() > 0) { + BufferBuilder lineBuffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + addCubeLines(lineBuffer, stack.last(), minX, minY, minZ, maxX, maxY, maxZ, wireColor, lineWidth, style); + + if (style.throughWalls()) { + Layers.getGlobalLines(lineWidth).draw(lineBuffer.buildOrThrow()); + } else { + Layers.getDepthLines(lineWidth).draw(lineBuffer.buildOrThrow()); + } + } + } + + private static void addCubeQuads( + BufferBuilder buffer, + PoseStack stack, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ, + Color baseColor, + RenderStyle style + ) { + PoseStack.Pose pose = stack.last(); + + addQuad(buffer, pose, baseColor, style, minX, minY, minZ, maxX, minY, minZ, maxX, minY, maxZ, minX, minY, maxZ); + addQuad(buffer, pose, baseColor, style, minX, maxY, minZ, minX, maxY, maxZ, maxX, maxY, maxZ, maxX, maxY, minZ); + + addQuad(buffer, pose, baseColor, style, minX, minY, minZ, minX, maxY, minZ, maxX, maxY, minZ, maxX, minY, minZ); + addQuad(buffer, pose, baseColor, style, maxX, minY, minZ, maxX, maxY, minZ, maxX, maxY, maxZ, maxX, minY, maxZ); + + addQuad(buffer, pose, baseColor, style, minX, minY, maxZ, maxX, minY, maxZ, maxX, maxY, maxZ, minX, maxY, maxZ); + addQuad(buffer, pose, baseColor, style, minX, minY, minZ, minX, minY, maxZ, minX, maxY, maxZ, minX, maxY, minZ); + } + + private static void addQuad( + BufferBuilder buffer, + PoseStack.Pose pose, + Color baseColor, + RenderStyle style, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2, + float x3, + float y3, + float z3, + float x4, + float y4, + float z4 + ) { + buffer.addVertex(pose, x1, y1, z1).setColor(getVertexColor(baseColor, x1, y1, z1, style)); + buffer.addVertex(pose, x2, y2, z2).setColor(getVertexColor(baseColor, x2, y2, z2, style)); + buffer.addVertex(pose, x3, y3, z3).setColor(getVertexColor(baseColor, x3, y3, z3, style)); + buffer.addVertex(pose, x4, y4, z4).setColor(getVertexColor(baseColor, x4, y4, z4, style)); + } + + private static void addCubeLines( + BufferBuilder buffer, + PoseStack.Pose pose, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ, + Color baseColor, + float lineWidth, + RenderStyle style + ) { + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, minZ, maxX, minY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, minZ, maxX, minY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, maxZ, minX, minY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, maxZ, minX, minY, minZ); + + addLine(buffer, pose, baseColor, lineWidth, style, minX, maxY, minZ, maxX, maxY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, maxY, minZ, maxX, maxY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, maxY, maxZ, minX, maxY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, minX, maxY, maxZ, minX, maxY, minZ); + + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, minZ, minX, maxY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, minZ, maxX, maxY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, maxZ, maxX, maxY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, maxZ, minX, maxY, maxZ); + } + + private static void addLine( + BufferBuilder buffer, + PoseStack.Pose pose, + Color baseColor, + float lineWidth, + RenderStyle style, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2 + ) { + float nx = x2 - x1; + float ny = y2 - y1; + float nz = z2 - z1; + + buffer.addVertex(pose, x1, y1, z1) + .setColor(getVertexColor(baseColor, x1, y1, z1, style)) + .setNormal(pose, nx, ny, nz) + .setLineWidth(lineWidth); + + buffer.addVertex(pose, x2, y2, z2) + .setColor(getVertexColor(baseColor, x2, y2, z2, style)) + .setNormal(pose, nx, ny, nz) + .setLineWidth(lineWidth); + } + + private static int getVertexColor(Color baseColor, float x, float y, float z, RenderStyle style) { + Color color = baseColor; + + if (style.gradient()) { + color = applyGradient(color, x, y, z, style); + } + + if (style.ripple()) { + color = applyRipple(color, x, y, z, style); + } + + if (style.waves()) { + color = applyWaves(color, x, y, z, style); + } + + if (style.water()) { + color = applyWater(color, x, y, z, style); + } + + if (style.smoke()) { + color = applySmoke(color, x, y, z, style); + } + + if (style.alternating()) { + color = applyAlternating(color, x, y, z, style); + } + + if (style.snow()) { + color = applySnow(color, x, y, z, style); + } + + if (style.aurora()) { + color = applyAurora(color, x, y, z, style); + } + + if (style.plasma()) { + color = applyPlasma(color, x, y, z, style); + } + + if (style.scanlines()) { + color = applyScanlines(color, x, y, z, style); + } + + if (style.electric()) { + color = applyElectric(color, x, y, z, style); + } + + if (style.rainbow()) { + color = applyRainbow(color, x, y, z, style); + } + + if (style.glint()) { + color = applyGlint(color, x, y, z, style); + } + + if (style.shine()) { + color = applyShine(color, x, y, z, style); + } + + if (style.glow()) { + color = applyGlow(color, x, y, z, style); + } + + if (style.blurry()) { + color = applyBlurry(color, style); + } + + return color.getRGB(); + } + + private static Color applyGradient(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double phase = + ((x * 0.85D) + (y * 1.45D) + (z * 0.85D)) + * style.gradientScale() + + time * style.gradientSpeed(); + + double wave = wave01(phase); + + Color gradientColor = mixColor( + style.gradientColorA(), + style.gradientColorB(), + wave, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + gradientColor, + clamp01(style.gradientStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyRipple(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + double distance = Math.sqrt((x * x) + (z * z) + (y * y * 0.35D)); + double phase = distance * style.rippleScale() - time * style.rippleSpeed(); + + double ring = wave01(phase); + ring = ring * ring; + + Color rippleColor = mixColor( + style.rippleColorA(), + style.rippleColorB(), + ring, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + rippleColor, + clamp01(style.rippleStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyAlternating(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + double scale = Math.max(1.0D, style.alternatingScale()); + + int cellX = (int) Math.floor((x + 4.0D) * scale); + int cellY = (int) Math.floor((y + 4.0D + time * style.alternatingSpeed() * 0.25D) * scale); + int cellZ = (int) Math.floor((z + 4.0D) * scale); + + double random = hash01(cellX, cellY, cellZ); + double alternate = wave01(time * style.alternatingSpeed() + random * 12.0D); + + double amount = random > 0.68D ? alternate : 0.0D; + amount *= clamp01(style.alternatingStrength()); + amount *= style.alternatingColor().getAlpha() / 255.0D; + + if (amount <= 0.0D) { + return baseColor; + } + + return mixColor( + baseColor, + style.alternatingColor(), + amount, + baseColor.getAlpha() + ); + } + + private static Color applyWaves(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double waveA = wave01((x + z) * style.waveScale() + time * style.waveSpeed()); + double waveB = wave01((y * 1.7D - z * 0.5D) * style.waveScale() - time * style.waveSpeed() * 0.65D); + + double wave = (waveA * 0.65D) + (waveB * 0.35D); + + Color waveColor = mixColor( + style.waveColorA(), + style.waveColorB(), + wave, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + waveColor, + clamp01(style.waveStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyShine(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double phase = + (x * 0.65D) + + (y * 1.15D) + - (z * 0.65D) + + time * style.shineSpeed(); + + double wrapped = phase - Math.floor(phase); + double distanceFromCenter = Math.abs(wrapped - 0.5D) * 2.0D; + + double width = Math.max(0.01D, style.shineWidth()); + double amount = 1.0D - (distanceFromCenter / width); + + if (amount <= 0.0D) { + return baseColor; + } + + amount = clamp01(amount); + amount *= clamp01(style.shineStrength()); + amount *= style.shineColor().getAlpha() / 255.0D; + + return mixColor( + baseColor, + style.shineColor(), + amount, + baseColor.getAlpha() + ); + } + + private static Color applyGlint(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double phase = + (x * 1.8D) + + (y * 0.85D) + - (z * 1.8D) + + time * style.glintSpeed(); + + double wrapped = phase - Math.floor(phase); + double distance = Math.abs(wrapped - 0.5D) * 2.0D; + + double width = Math.max(0.01D, style.glintWidth()); + double amount = 1.0D - (distance / width); + + if (amount <= 0.0D) { + return baseColor; + } + + amount = clamp01(amount); + amount = amount * amount; + amount *= clamp01(style.glintStrength()); + amount *= style.glintColor().getAlpha() / 255.0D; + + return mixColor( + baseColor, + style.glintColor(), + amount, + baseColor.getAlpha() + ); + } + + private static Color applyGlow(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double distance = Math.sqrt((x * x) + (y * y) + (z * z)); + double pulse = wave01(time * style.glowSpeed()); + + double glow = 1.0D - clamp01(distance / 0.75D); + glow = Math.max(glow, pulse * 0.35D); + glow *= clamp01(style.glowStrength()); + glow *= style.glowColor().getAlpha() / 255.0D; + + return mixColor( + baseColor, + style.glowColor(), + glow, + baseColor.getAlpha() + ); + } + + private static Color applySmoke(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double noiseA = wave01((x * 1.7D + y * 0.8D + z * 1.2D) * style.smokeScale() + time * style.smokeSpeed()); + double noiseB = wave01((x * -0.8D + y * 1.9D - z * 1.4D) * style.smokeScale() - time * style.smokeSpeed() * 0.75D); + double smoke = (noiseA + noiseB) / 2.0D; + smoke = smoothstep(smoke); + + Color smokeColor = mixColor( + style.smokeColorA(), + style.smokeColorB(), + smoke, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + smokeColor, + clamp01(style.smokeStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyWater(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double rippleA = wave01((x * 1.4D + z * 1.4D + y * 0.25D) * style.waterScale() + time * style.waterSpeed()); + double rippleB = wave01((x * -0.9D + z * 1.1D - y * 0.35D) * style.waterScale() - time * style.waterSpeed() * 1.25D); + double water = (rippleA * 0.55D) + (rippleB * 0.45D); + + Color waterColor = mixColor( + style.waterColorA(), + style.waterColorB(), + water, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + waterColor, + clamp01(style.waterStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyBlurry(Color baseColor, RenderStyle style) { + double strength = clamp01(style.blurryStrength()); + int alpha = (int) Math.round(baseColor.getAlpha() * (1.0D - strength * 0.25D)); + + Color softened = mixColor( + baseColor, + style.blurryColor(), + strength, + alpha + ); + + return new Color( + softened.getRed(), + softened.getGreen(), + softened.getBlue(), + clampColor(alpha) + ); + } + + private static Color applySnow(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + double scale = Math.max(1.0D, style.snowScale()); + + double fallingY = y + time * style.snowSpeed(); + + int cellX = (int) Math.floor((x + 8.0D) * scale); + int cellY = (int) Math.floor((fallingY + 8.0D) * scale); + int cellZ = (int) Math.floor((z + 8.0D) * scale); + + double random = hash01(cellX, cellY, cellZ); + double flake = random > 0.72D ? 1.0D : 0.0D; + + double shimmer = wave01(time * style.snowSpeed() * 1.5D + random * 10.0D); + flake *= shimmer; + flake *= clamp01(style.snowStrength()); + flake *= style.snowColor().getAlpha() / 255.0D; + + if (flake <= 0.0D) { + return baseColor; + } + + return mixColor( + baseColor, + style.snowColor(), + flake, + baseColor.getAlpha() + ); + } + + private static Color applyAurora(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double curtain = + Math.sin((x * 1.7D + z * 0.8D) * style.auroraScale() + time * style.auroraSpeed()) + + Math.sin((z * 1.4D - x * 0.5D + y * 0.7D) * style.auroraScale() - time * style.auroraSpeed() * 0.8D); + + double amount = (curtain + 2.0D) / 4.0D; + amount = smoothstep(amount); + + double verticalFade = clamp01((y + 0.5D) / 1.5D); + amount *= verticalFade; + + Color auroraColor = mixColor( + style.auroraColorA(), + style.auroraColorB(), + amount, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + auroraColor, + amount * clamp01(style.auroraStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyPlasma(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + double scale = style.plasmaScale(); + + double plasma = + Math.sin((x * scale) + time * style.plasmaSpeed()) + + Math.sin((y * scale * 1.25D) - time * style.plasmaSpeed() * 0.7D) + + Math.sin((z * scale * 0.8D) + time * style.plasmaSpeed() * 1.3D) + + Math.sin((x + y + z) * scale * 0.65D); + + plasma = (plasma + 4.0D) / 8.0D; + plasma = smoothstep(plasma); + + Color plasmaColor = mixColor( + style.plasmaColorA(), + style.plasmaColorB(), + plasma, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + plasmaColor, + clamp01(style.plasmaStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyScanlines(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double phase = (y * style.scanlineScale()) - time * style.scanlineSpeed(); + double line = wave01(phase); + line = line > 0.72D ? line : 0.0D; + + double amount = line * clamp01(style.scanlineStrength()); + amount *= style.scanlineColor().getAlpha() / 255.0D; + + return mixColor( + baseColor, + style.scanlineColor(), + amount, + baseColor.getAlpha() + ); + } + + private static Color applyElectric(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double boltA = Math.abs(Math.sin((x * 2.0D + y * 0.8D - z) * style.electricScale() + time * style.electricSpeed())); + double boltB = Math.abs(Math.sin((z * 2.2D - y * 1.1D + x * 0.6D) * style.electricScale() - time * style.electricSpeed() * 1.3D)); + + double bolt = Math.max(boltA, boltB); + bolt = bolt > 0.86D ? bolt : 0.0D; + + double flicker = 0.65D + 0.35D * wave01(time * style.electricSpeed() * 3.0D + x * 10.0D + z * 8.0D); + bolt *= flicker; + bolt *= clamp01(style.electricStrength()); + bolt *= style.electricColor().getAlpha() / 255.0D; + + if (bolt <= 0.0D) { + return baseColor; + } + + return mixColor( + baseColor, + style.electricColor(), + bolt, + baseColor.getAlpha() + ); + } + + private static Color applyRainbow(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + float hue = (float) ( + ((x * 0.35D + y * 0.75D + z * 0.35D) * style.rainbowScale() + + time * style.rainbowSpeed()) % 1.0D + ); + + if (hue < 0.0F) { + hue += 1.0F; + } + + Color rainbowColor = Color.getHSBColor( + hue, + (float) clamp01(style.rainbowSaturation()), + 1.0F + ); + + return mixColor( + baseColor, + rainbowColor, + clamp01(style.rainbowStrength()), + baseColor.getAlpha() + ); + } + + private static double wave01(double value) { + return (Math.sin(value * Math.PI * 2.0D) + 1.0D) / 2.0D; + } + + private static double smoothstep(double value) { + double clamped = clamp01(value); + return clamped * clamped * (3.0D - 2.0D * clamped); + } + + private static double hash01(int x, int y, int z) { + int hash = x * 374761393 + y * 668265263 + z * 2147483647; + hash = (hash ^ (hash >> 13)) * 1274126177; + hash = hash ^ (hash >> 16); + return (hash & 0x7fffffff) / (double) 0x7fffffff; + } + + private static Color mixColor(Color first, Color second, double factor, int alpha) { + double clamped = clamp01(factor); + + int red = (int) Math.round(first.getRed() + (second.getRed() - first.getRed()) * clamped); + int green = (int) Math.round(first.getGreen() + (second.getGreen() - first.getGreen()) * clamped); + int blue = (int) Math.round(first.getBlue() + (second.getBlue() - first.getBlue()) * clamped); + + return new Color( + clampColor(red), + clampColor(green), + clampColor(blue), + clampColor(alpha) + ); + } + + private static double clamp01(double value) { + return Math.max(0.0D, Math.min(1.0D, value)); + } + + private static int clampColor(int value) { + return Math.max(0, Math.min(255, value)); + } + + private record RenderStyle( + boolean throughWalls, + + boolean gradient, + Color gradientColorA, + Color gradientColorB, + float gradientSpeed, + float gradientScale, + float gradientStrength, + + boolean ripple, + Color rippleColorA, + Color rippleColorB, + float rippleSpeed, + float rippleScale, + float rippleStrength, + + boolean shine, + Color shineColor, + float shineSpeed, + float shineWidth, + float shineStrength, + + boolean alternating, + Color alternatingColor, + float alternatingSpeed, + float alternatingScale, + float alternatingStrength, + + boolean waves, + Color waveColorA, + Color waveColorB, + float waveSpeed, + float waveScale, + float waveStrength, + + boolean glint, + Color glintColor, + float glintSpeed, + float glintWidth, + float glintStrength, + + boolean glow, + Color glowColor, + float glowSpeed, + float glowStrength, + + boolean smoke, + Color smokeColorA, + Color smokeColorB, + float smokeSpeed, + float smokeScale, + float smokeStrength, + + boolean water, + Color waterColorA, + Color waterColorB, + float waterSpeed, + float waterScale, + float waterStrength, + + boolean blurry, + Color blurryColor, + float blurryStrength, + + boolean snow, + Color snowColor, + float snowSpeed, + float snowScale, + float snowStrength, + + boolean aurora, + Color auroraColorA, + Color auroraColorB, + float auroraSpeed, + float auroraScale, + float auroraStrength, + + boolean plasma, + Color plasmaColorA, + Color plasmaColorB, + float plasmaSpeed, + float plasmaScale, + float plasmaStrength, + + boolean scanlines, + Color scanlineColor, + float scanlineSpeed, + float scanlineScale, + float scanlineStrength, + + boolean electric, + Color electricColor, + float electricSpeed, + float electricScale, + float electricStrength, + + boolean rainbow, + float rainbowSpeed, + float rainbowScale, + float rainbowSaturation, + float rainbowStrength + ) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/FadeRenderUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/FadeRenderUtil.java new file mode 100644 index 0000000..be34865 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/FadeRenderUtil.java @@ -0,0 +1,343 @@ +package me.humanbeing.nolongerhuman.util.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.AABB; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public final class FadeRenderUtil { + + private FadeRenderUtil() { + } + + public static final class FadeState { + private final Map boxes = new HashMap<>(); + + public void reset() { + boxes.clear(); + } + + public void remove(Object key) { + if (key != null) { + boxes.remove(key); + } + } + + public boolean contains(Object key) { + return key != null && boxes.containsKey(key); + } + } + + public static final class FadeBox { + private final Object key; + private final AABB box; + + public FadeBox(Object key, AABB box) { + this.key = key; + this.box = box; + } + + public Object getKey() { + return key; + } + + public AABB getBox() { + return box; + } + } + + private static final class BoxState { + private AABB box; + private long firstSeenMs; + private long lastSeenMs; + private long fadeOutStartMs; + private long growStartMs; + private boolean fadingOut; + + private BoxState(AABB box, long now) { + this.box = box; + this.firstSeenMs = now; + this.lastSeenMs = now; + this.fadeOutStartMs = 0L; + this.growStartMs = 0L; + this.fadingOut = false; + } + } + + public static void pulse(FadeState state, Object key) { + if (state == null || key == null) { + return; + } + + BoxState boxState = state.boxes.get(key); + + if (boxState != null) { + boxState.growStartMs = System.currentTimeMillis(); + } + } + + public static void renderBlockPositions( + PoseStack stack, + FadeState state, + Collection positions, + Color fill, + Color outline, + float lineWidth, + boolean fadeIn, + int fadeInTimeMs, + boolean fadeOut, + int fadeOutTimeMs + ) { + if (stack == null || state == null) { + return; + } + + List boxes = new ArrayList<>(); + + if (positions != null) { + for (BlockPos pos : positions) { + if (pos == null) { + continue; + } + + BlockPos immutable = pos.immutable(); + boxes.add(new FadeBox(immutable, new AABB(immutable))); + } + } + + renderBoxes( + stack, + state, + boxes, + fill, + outline, + lineWidth, + fadeIn, + fadeInTimeMs, + fadeOut, + fadeOutTimeMs, + 0.0D, + 0 + ); + } + + public static void renderBoxes( + PoseStack stack, + FadeState state, + Collection boxes, + Color fill, + Color outline, + float lineWidth, + boolean fadeIn, + int fadeInTimeMs, + boolean fadeOut, + int fadeOutTimeMs + ) { + renderBoxes( + stack, + state, + boxes, + fill, + outline, + lineWidth, + fadeIn, + fadeInTimeMs, + fadeOut, + fadeOutTimeMs, + 0.0D, + 0 + ); + } + + public static void renderBoxes( + PoseStack stack, + FadeState state, + Collection boxes, + Color fill, + Color outline, + float lineWidth, + boolean fadeIn, + int fadeInTimeMs, + boolean fadeOut, + int fadeOutTimeMs, + double growAmount, + int growTimeMs + ) { + if (stack == null || state == null) { + return; + } + + long now = System.currentTimeMillis(); + Set visibleKeys = new HashSet<>(); + + if (boxes != null) { + for (FadeBox fadeBox : boxes) { + if (fadeBox == null || fadeBox.getKey() == null || fadeBox.getBox() == null) { + continue; + } + + Object key = fadeBox.getKey(); + AABB box = fadeBox.getBox(); + + visibleKeys.add(key); + + BoxState boxState = state.boxes.get(key); + + if (boxState == null) { + state.boxes.put(key, new BoxState(box, now)); + continue; + } + + boxState.box = box; + boxState.lastSeenMs = now; + + if (boxState.fadingOut) { + boxState.firstSeenMs = now; + } + + boxState.fadingOut = false; + boxState.fadeOutStartMs = 0L; + } + } + + Iterator> iterator = state.boxes.entrySet().iterator(); + + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + Object key = entry.getKey(); + BoxState boxState = entry.getValue(); + + if (boxState == null || boxState.box == null) { + iterator.remove(); + continue; + } + + boolean currentlyVisible = visibleKeys.contains(key); + + if (!currentlyVisible && !boxState.fadingOut) { + if (!fadeOut || fadeOutTimeMs <= 0) { + iterator.remove(); + continue; + } + + boxState.fadingOut = true; + boxState.fadeOutStartMs = now; + boxState.lastSeenMs = now; + } + + double alphaMultiplier = getAlphaMultiplier( + boxState, + now, + fadeIn, + fadeInTimeMs, + fadeOut, + fadeOutTimeMs + ); + + if (alphaMultiplier <= 0.01D) { + if (boxState.fadingOut) { + iterator.remove(); + } + + continue; + } + + AABB renderBox = boxState.box; + double grow = getGrowAmount(boxState, now, growAmount, growTimeMs); + + if (grow > 0.0D) { + renderBox = renderBox.inflate(grow); + } + + Color fadedFill = withAlphaMultiplier(fill, alphaMultiplier); + Color fadedOutline = withAlphaMultiplier(outline, alphaMultiplier); + + if (fadedFill != null && fadedFill.getAlpha() > 0) { + RenderUtil.drawBoxFilled(stack, renderBox, fadedFill); + } + + if (fadedOutline != null && fadedOutline.getAlpha() > 0 && lineWidth > 0.0F) { + RenderUtil.drawBox(stack, renderBox, fadedOutline, lineWidth); + } + } + } + + private static double getAlphaMultiplier( + BoxState boxState, + long now, + boolean fadeIn, + int fadeInTimeMs, + boolean fadeOut, + int fadeOutTimeMs + ) { + if (boxState.fadingOut) { + if (!fadeOut || fadeOutTimeMs <= 0) { + return 0.0D; + } + + double progress = (double) (now - boxState.fadeOutStartMs) / (double) fadeOutTimeMs; + return 1.0D - clamp(progress, 0.0D, 1.0D); + } + + if (fadeIn && fadeInTimeMs > 0) { + double progress = (double) (now - boxState.firstSeenMs) / (double) fadeInTimeMs; + return clamp(progress, 0.0D, 1.0D); + } + + return 1.0D; + } + + private static double getGrowAmount(BoxState boxState, long now, double growAmount, int growTimeMs) { + if (growAmount <= 0.0D || growTimeMs <= 0 || boxState.growStartMs <= 0L) { + return 0.0D; + } + + double progress = (double) (now - boxState.growStartMs) / (double) growTimeMs; + + if (progress >= 1.0D) { + boxState.growStartMs = 0L; + return 0.0D; + } + + progress = clamp(progress, 0.0D, 1.0D); + + double eased = easeOutCubic(progress); + return growAmount * (1.0D - eased); + } + + private static double easeOutCubic(double progress) { + double inverse = 1.0D - clamp(progress, 0.0D, 1.0D); + return 1.0D - inverse * inverse * inverse; + } + + private static Color withAlphaMultiplier(Color color, double multiplier) { + if (color == null) { + return null; + } + + multiplier = clamp(multiplier, 0.0D, 1.0D); + + int alpha = (int) Math.round(color.getAlpha() * multiplier); + alpha = Math.max(0, Math.min(255, alpha)); + + return new Color( + color.getRed(), + color.getGreen(), + color.getBlue(), + alpha + ); + } + + private static double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/FontManager.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/FontManager.java new file mode 100644 index 0000000..bc93732 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/FontManager.java @@ -0,0 +1,171 @@ +package me.humanbeing.nolongerhuman.util.render; + +import me.humanbeing.nolongerhuman.features.modules.client.CustomFontModule; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; + +public final class FontManager { + private static AWTFontRenderer renderer; + private static boolean enabled; + private static boolean renderingChat; + private static String currentFont = ""; + private static float currentSize = -1.0f; + + private FontManager() { + throw new AssertionError("Can't create an instance of utility class"); + } + + public static void setEnabled(boolean value) { + enabled = value; + } + + public static boolean isEnabled() { + if (!enabled) { + return false; + } + + if (renderer == null) { + reload("Arial", 18.0f); + } + + CustomFontModule module = CustomFontModule.getInstance(); + + if (module != null) { + if (renderingChat && !module.shouldRenderChat()) { + return false; + } + + if (module.shouldRenderGuiOnly()) { + Minecraft mc = Minecraft.getInstance(); + + if (mc.screen == null && !renderingChat) { + return false; + } + } + } + + return renderer != null; + } + + public static void beginChatRender() { + renderingChat = true; + } + + public static void endChatRender() { + renderingChat = false; + } + + public static boolean isRenderingChat() { + return renderingChat; + } + + public static void reload(String fontName, float size) { + String safeFont = fontName == null || fontName.isBlank() ? "Arial" : fontName; + float safeSize = Math.max(8.0f, size); + + if (matches(safeFont, safeSize) && renderer != null) { + return; + } + + if (renderer != null) { + renderer.destroy(); + } + + currentFont = safeFont; + currentSize = safeSize; + renderer = new AWTFontRenderer(currentFont, currentSize); + } + + public static boolean matches(String fontName, float size) { + String safeFont = fontName == null || fontName.isBlank() ? "Arial" : fontName; + return currentFont.equalsIgnoreCase(safeFont) && Math.abs(currentSize - size) < 0.01f; + } + + public static float drawString(GuiGraphics context, String text, float x, float y, int color, boolean shadow) { + if (!isEnabled()) { + return 0.0f; + } + + CustomFontModule module = CustomFontModule.getInstance(); + boolean finalShadow = shadow || module == null || module.shouldForceShadow(); + + return renderer.drawString(context, text, x, y, color, finalShadow); + } + + public static float drawString(GuiGraphics context, Component component, float x, float y, int color, boolean shadow) { + if (!isEnabled() || component == null) { + return 0.0f; + } + + CustomFontModule module = CustomFontModule.getInstance(); + boolean finalShadow = shadow || module == null || module.shouldForceShadow(); + + return renderer.drawFormattedCharSequence( + context, + component.getVisualOrderText(), + x, + y, + color, + finalShadow + ); + } + + public static float drawString( + GuiGraphics context, + FormattedCharSequence sequence, + float x, + float y, + int color, + boolean shadow + ) { + if (!isEnabled() || sequence == null) { + return 0.0f; + } + + CustomFontModule module = CustomFontModule.getInstance(); + boolean finalShadow = shadow || module == null || module.shouldForceShadow(); + + return renderer.drawFormattedCharSequence( + context, + sequence, + x, + y, + color, + finalShadow + ); + } + + public static int width(String text) { + if (!isEnabled()) { + return 0; + } + + return Math.round(renderer.getStringWidth(text)); + } + + public static int width(Component component) { + if (!isEnabled() || component == null) { + return 0; + } + + return Math.round(renderer.getFormattedWidth(component.getVisualOrderText())); + } + + public static int width(FormattedCharSequence sequence) { + if (!isEnabled() || sequence == null) { + return 0; + } + + return Math.round(renderer.getFormattedWidth(sequence)); + } + + public static int lineHeight() { + if (!isEnabled()) { + return 9; + } + + return Math.round(renderer.getFontHeight()); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/Layers.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/Layers.java new file mode 100644 index 0000000..8bd19c3 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/Layers.java @@ -0,0 +1,71 @@ +package me.humanbeing.nolongerhuman.util.render; + +import net.minecraft.client.renderer.rendertype.RenderSetup; +import net.minecraft.client.renderer.rendertype.RenderType; + +import java.util.HashMap; +import java.util.Map; + +import static me.humanbeing.nolongerhuman.util.render.Pipelines.DEPTH_LINES_PIPELINE; +import static me.humanbeing.nolongerhuman.util.render.Pipelines.DEPTH_QUADS_PIPELINE; +import static me.humanbeing.nolongerhuman.util.render.Pipelines.GLOBAL_LINES_PIPELINE; +import static me.humanbeing.nolongerhuman.util.render.Pipelines.GLOBAL_QUADS_PIPELINE; + +public class Layers { + private static final RenderType GLOBAL_QUADS = RenderType.create( + "global_fill", + RenderSetup.builder(GLOBAL_QUADS_PIPELINE).createRenderSetup() + ); + + private static final RenderType DEPTH_QUADS = RenderType.create( + "depth_fill", + RenderSetup.builder(DEPTH_QUADS_PIPELINE).createRenderSetup() + ); + + private static final Map GLOBAL_LINES = new HashMap<>(); + private static final Map DEPTH_LINES = new HashMap<>(); + + public static RenderType getGlobalQuads() { + return GLOBAL_QUADS; + } + + public static RenderType getDepthQuads() { + return DEPTH_QUADS; + } + + public static RenderType getGlobalLines(double width) { + return GLOBAL_LINES.computeIfAbsent( + width, + key -> RenderType.create( + "global_lines_" + key, + RenderSetup.builder(GLOBAL_LINES_PIPELINE).createRenderSetup() + ) + ); + } + + public static RenderType getDepthLines(double width) { + return DEPTH_LINES.computeIfAbsent( + width, + key -> RenderType.create( + "depth_lines_" + key, + RenderSetup.builder(DEPTH_LINES_PIPELINE).createRenderSetup() + ) + ); + } + + public static RenderType quads() { + return getGlobalQuads(); + } + + public static RenderType lines() { + return getGlobalLines(1.0); + } + + public static RenderType depthQuads() { + return getDepthQuads(); + } + + public static RenderType depthLines() { + return getDepthLines(1.0); + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/Pipelines.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/Pipelines.java new file mode 100644 index 0000000..24b6220 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/Pipelines.java @@ -0,0 +1,55 @@ +package me.humanbeing.nolongerhuman.util.render; + +import com.mojang.blaze3d.pipeline.BlendFunction; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.platform.DepthTestFunction; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.resources.Identifier; + +import static net.minecraft.client.renderer.RenderPipelines.DEBUG_FILLED_SNIPPET; +import static net.minecraft.client.renderer.RenderPipelines.GLOBALS_SNIPPET; +import static net.minecraft.client.renderer.RenderPipelines.MATRICES_FOG_SNIPPET; + +class Pipelines { + static final RenderPipeline.Snippet GLOBAL_LINES_SNIPPET = RenderPipeline.builder(MATRICES_FOG_SNIPPET, GLOBALS_SNIPPET) + .withVertexShader(Identifier.fromNamespaceAndPath("nolongerhuman", "core/rendertype_lines_smooth")) + .withFragmentShader(Identifier.fromNamespaceAndPath("nolongerhuman", "core/rendertype_lines_smooth")) + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH, VertexFormat.Mode.LINES) + .withBlend(BlendFunction.TRANSLUCENT) + .withCull(false) + .buildSnippet(); + + static final RenderPipeline GLOBAL_QUADS_PIPELINE = RenderPipeline.builder(DEBUG_FILLED_SNIPPET) + .withLocation("pipeline/global_fill_pipeline") + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS) + .withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST) + .withBlend(BlendFunction.TRANSLUCENT) + .withDepthWrite(false) + .withCull(false) + .build(); + + static final RenderPipeline GLOBAL_LINES_PIPELINE = RenderPipeline.builder(GLOBAL_LINES_SNIPPET) + .withLocation("pipeline/global_lines_pipeline") + .withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST) + .withBlend(BlendFunction.TRANSLUCENT) + .withDepthWrite(false) + .withCull(false) + .build(); + + static final RenderPipeline DEPTH_QUADS_PIPELINE = RenderPipeline.builder(DEBUG_FILLED_SNIPPET) + .withLocation("pipeline/depth_fill_pipeline") + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS) + .withDepthTestFunction(DepthTestFunction.LEQUAL_DEPTH_TEST) + .withBlend(BlendFunction.TRANSLUCENT) + .withDepthWrite(false) + .withCull(false) + .build(); + + static final RenderPipeline DEPTH_LINES_PIPELINE = RenderPipeline.builder(GLOBAL_LINES_SNIPPET) + .withLocation("pipeline/depth_lines_pipeline") + .withDepthTestFunction(DepthTestFunction.LEQUAL_DEPTH_TEST) + .withBlend(BlendFunction.TRANSLUCENT) + .withDepthWrite(false) + .build(); +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/PopChamsRenderer.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/PopChamsRenderer.java new file mode 100644 index 0000000..d18a2de --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/PopChamsRenderer.java @@ -0,0 +1,578 @@ +package me.humanbeing.nolongerhuman.util.render; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.features.modules.render.PopChams; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.world.phys.Vec3; + +import java.awt.Color; + +public final class PopChamsRenderer implements Util { + private PopChamsRenderer() { + } + + public static void renderPlayer( + PoseStack stack, + PopChams.PopCham popCham, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + boolean throughWalls, + + boolean gradient, + Color gradientColorA, + Color gradientColorB, + float gradientSpeed, + float gradientScale, + float gradientStrength, + + boolean ripple, + Color rippleColorA, + Color rippleColorB, + float rippleSpeed, + float rippleScale, + float rippleStrength, + + boolean shine, + Color shineColor, + float shineSpeed, + float shineWidth, + float shineStrength + ) { + if (popCham == null) { + return; + } + + RenderStyle style = new RenderStyle( + throughWalls, + + gradient, + gradientColorA, + gradientColorB, + gradientSpeed, + gradientScale, + gradientStrength, + + ripple, + rippleColorA, + rippleColorB, + rippleSpeed, + rippleScale, + rippleStrength, + + shine, + shineColor, + shineSpeed, + shineWidth, + shineStrength + ); + + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + stack.pushPose(); + + stack.translate( + popCham.x() - camera.x(), + popCham.y() - camera.y(), + popCham.z() - camera.z() + ); + + stack.mulPose(Axis.YP.rotationDegrees(180.0F - popCham.bodyYaw())); + + if (popCham.sneaking()) { + stack.translate(0.0D, -0.08D, 0.0D); + } + + renderBody(stack, fillColor, wireColor, lineWidth, lines, fill, style); + renderHead(stack, popCham, fillColor, wireColor, lineWidth, lines, fill, style); + renderArms(stack, popCham, fillColor, wireColor, lineWidth, lines, fill, style); + renderLegs(stack, popCham, fillColor, wireColor, lineWidth, lines, fill, style); + + stack.popPose(); + } + + private static void renderBody( + PoseStack stack, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + renderCuboid( + stack, + -0.30F, + 0.75F, + -0.15F, + 0.30F, + 1.50F, + 0.15F, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + } + + private static void renderHead( + PoseStack stack, + PopChams.PopCham popCham, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + stack.pushPose(); + + stack.translate(0.0F, 1.75F, 0.0F); + stack.mulPose(Axis.YP.rotationDegrees(popCham.headYaw() - popCham.bodyYaw())); + stack.mulPose(Axis.XP.rotationDegrees(popCham.pitch())); + + renderCuboid( + stack, + -0.25F, + -0.25F, + -0.25F, + 0.25F, + 0.25F, + 0.25F, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + + stack.popPose(); + } + + private static void renderArms( + PoseStack stack, + PopChams.PopCham popCham, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + float sprintOffset = popCham.sprinting() ? 0.10F : 0.0F; + + renderCuboid( + stack, + -0.50F, + 0.78F, + -0.12F - sprintOffset, + -0.32F, + 1.45F, + 0.12F - sprintOffset, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + + renderCuboid( + stack, + 0.32F, + 0.78F, + -0.12F + sprintOffset, + 0.50F, + 1.45F, + 0.12F + sprintOffset, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + } + + private static void renderLegs( + PoseStack stack, + PopChams.PopCham popCham, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + if (popCham.swimming()) { + renderCuboid( + stack, + -0.28F, + 0.05F, + -0.45F, + -0.04F, + 0.75F, + -0.18F, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + + renderCuboid( + stack, + 0.04F, + 0.05F, + -0.45F, + 0.28F, + 0.75F, + -0.18F, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + + return; + } + + renderCuboid( + stack, + -0.28F, + 0.00F, + -0.12F, + -0.04F, + 0.75F, + 0.12F, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + + renderCuboid( + stack, + 0.04F, + 0.00F, + -0.12F, + 0.28F, + 0.75F, + 0.12F, + fillColor, + wireColor, + lineWidth, + lines, + fill, + style + ); + } + + private static void renderCuboid( + PoseStack stack, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ, + Color fillColor, + Color wireColor, + float lineWidth, + boolean lines, + boolean fill, + RenderStyle style + ) { + if (fill && fillColor.getAlpha() > 0) { + BufferBuilder quads = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + addCuboidQuads(quads, stack, minX, minY, minZ, maxX, maxY, maxZ, fillColor, style); + + if (style.throughWalls()) { + Layers.quads().draw(quads.buildOrThrow()); + } else { + Layers.depthQuads().draw(quads.buildOrThrow()); + } + } + + if (lines && wireColor.getAlpha() > 0) { + BufferBuilder lineBuffer = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + addCuboidLines(lineBuffer, stack.last(), minX, minY, minZ, maxX, maxY, maxZ, wireColor, lineWidth, style); + + if (style.throughWalls()) { + Layers.getGlobalLines(lineWidth).draw(lineBuffer.buildOrThrow()); + } else { + Layers.getDepthLines(lineWidth).draw(lineBuffer.buildOrThrow()); + } + } + } + + private static void addCuboidQuads( + BufferBuilder buffer, + PoseStack stack, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ, + Color baseColor, + RenderStyle style + ) { + PoseStack.Pose pose = stack.last(); + + addQuad(buffer, pose, baseColor, style, minX, minY, minZ, maxX, minY, minZ, maxX, minY, maxZ, minX, minY, maxZ); + addQuad(buffer, pose, baseColor, style, minX, maxY, minZ, minX, maxY, maxZ, maxX, maxY, maxZ, maxX, maxY, minZ); + + addQuad(buffer, pose, baseColor, style, minX, minY, minZ, minX, maxY, minZ, maxX, maxY, minZ, maxX, minY, minZ); + addQuad(buffer, pose, baseColor, style, maxX, minY, minZ, maxX, maxY, minZ, maxX, maxY, maxZ, maxX, minY, maxZ); + + addQuad(buffer, pose, baseColor, style, minX, minY, maxZ, maxX, minY, maxZ, maxX, maxY, maxZ, minX, maxY, maxZ); + addQuad(buffer, pose, baseColor, style, minX, minY, minZ, minX, minY, maxZ, minX, maxY, maxZ, minX, maxY, minZ); + } + + private static void addQuad( + BufferBuilder buffer, + PoseStack.Pose pose, + Color baseColor, + RenderStyle style, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2, + float x3, + float y3, + float z3, + float x4, + float y4, + float z4 + ) { + buffer.addVertex(pose, x1, y1, z1).setColor(getVertexColor(baseColor, x1, y1, z1, style)); + buffer.addVertex(pose, x2, y2, z2).setColor(getVertexColor(baseColor, x2, y2, z2, style)); + buffer.addVertex(pose, x3, y3, z3).setColor(getVertexColor(baseColor, x3, y3, z3, style)); + buffer.addVertex(pose, x4, y4, z4).setColor(getVertexColor(baseColor, x4, y4, z4, style)); + } + + private static void addCuboidLines( + BufferBuilder buffer, + PoseStack.Pose pose, + float minX, + float minY, + float minZ, + float maxX, + float maxY, + float maxZ, + Color baseColor, + float lineWidth, + RenderStyle style + ) { + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, minZ, maxX, minY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, minZ, maxX, minY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, maxZ, minX, minY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, maxZ, minX, minY, minZ); + + addLine(buffer, pose, baseColor, lineWidth, style, minX, maxY, minZ, maxX, maxY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, maxY, minZ, maxX, maxY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, maxY, maxZ, minX, maxY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, minX, maxY, maxZ, minX, maxY, minZ); + + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, minZ, minX, maxY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, minZ, maxX, maxY, minZ); + addLine(buffer, pose, baseColor, lineWidth, style, maxX, minY, maxZ, maxX, maxY, maxZ); + addLine(buffer, pose, baseColor, lineWidth, style, minX, minY, maxZ, minX, maxY, maxZ); + } + + private static void addLine( + BufferBuilder buffer, + PoseStack.Pose pose, + Color baseColor, + float lineWidth, + RenderStyle style, + float x1, + float y1, + float z1, + float x2, + float y2, + float z2 + ) { + float nx = x2 - x1; + float ny = y2 - y1; + float nz = z2 - z1; + + buffer.addVertex(pose, x1, y1, z1) + .setColor(getVertexColor(baseColor, x1, y1, z1, style)) + .setNormal(pose, nx, ny, nz) + .setLineWidth(lineWidth); + + buffer.addVertex(pose, x2, y2, z2) + .setColor(getVertexColor(baseColor, x2, y2, z2, style)) + .setNormal(pose, nx, ny, nz) + .setLineWidth(lineWidth); + } + + private static int getVertexColor(Color baseColor, float x, float y, float z, RenderStyle style) { + Color color = baseColor; + + if (style.gradient()) { + color = applyGradient(color, x, y, z, style); + } + + if (style.ripple()) { + color = applyRipple(color, x, y, z, style); + } + + if (style.shine()) { + color = applyShine(color, x, y, z, style); + } + + return color.getRGB(); + } + + private static Color applyGradient(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double phase = + ((x * 0.85D) + (y * 1.45D) + (z * 0.85D)) + * style.gradientScale() + + time * style.gradientSpeed(); + + double wave = (Math.sin(phase * Math.PI * 2.0D) + 1.0D) / 2.0D; + + Color gradientColor = mixColor( + style.gradientColorA(), + style.gradientColorB(), + wave, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + gradientColor, + clamp01(style.gradientStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyRipple(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double distance = Math.sqrt((x * x) + (z * z) + (y * y * 0.35D)); + double phase = distance * style.rippleScale() - time * style.rippleSpeed(); + + double ring = (Math.sin(phase * Math.PI * 2.0D) + 1.0D) / 2.0D; + ring = ring * ring; + + Color rippleColor = mixColor( + style.rippleColorA(), + style.rippleColorB(), + ring, + baseColor.getAlpha() + ); + + return mixColor( + baseColor, + rippleColor, + clamp01(style.rippleStrength()), + baseColor.getAlpha() + ); + } + + private static Color applyShine(Color baseColor, float x, float y, float z, RenderStyle style) { + double time = System.currentTimeMillis() / 1000.0D; + + double phase = + (x * 0.65D) + + (y * 1.15D) + - (z * 0.65D) + + time * style.shineSpeed(); + + double wrapped = phase - Math.floor(phase); + double distanceFromCenter = Math.abs(wrapped - 0.5D) * 2.0D; + + double width = Math.max(0.01D, style.shineWidth()); + double amount = 1.0D - (distanceFromCenter / width); + + if (amount <= 0.0D) { + return baseColor; + } + + amount = clamp01(amount); + amount *= clamp01(style.shineStrength()); + amount *= style.shineColor().getAlpha() / 255.0D; + + return mixColor( + baseColor, + style.shineColor(), + amount, + baseColor.getAlpha() + ); + } + + private static Color mixColor(Color first, Color second, double factor, int alpha) { + double clamped = clamp01(factor); + + int red = (int) Math.round(first.getRed() + (second.getRed() - first.getRed()) * clamped); + int green = (int) Math.round(first.getGreen() + (second.getGreen() - first.getGreen()) * clamped); + int blue = (int) Math.round(first.getBlue() + (second.getBlue() - first.getBlue()) * clamped); + + return new Color( + clampColor(red), + clampColor(green), + clampColor(blue), + clampColor(alpha) + ); + } + + private static double clamp01(double value) { + return Math.max(0.0D, Math.min(1.0D, value)); + } + + private static int clampColor(int value) { + return Math.max(0, Math.min(255, value)); + } + + private record RenderStyle( + boolean throughWalls, + + boolean gradient, + Color gradientColorA, + Color gradientColorB, + float gradientSpeed, + float gradientScale, + float gradientStrength, + + boolean ripple, + Color rippleColorA, + Color rippleColorB, + float rippleSpeed, + float rippleScale, + float rippleStrength, + + boolean shine, + Color shineColor, + float shineSpeed, + float shineWidth, + float shineStrength + ) { + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/RenderUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/RenderUtil.java new file mode 100644 index 0000000..45c861d --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/RenderUtil.java @@ -0,0 +1,368 @@ +package me.humanbeing.nolongerhuman.util.render; + +import com.mojang.blaze3d.vertex.*; +import com.mojang.math.Axis; +import me.humanbeing.nolongerhuman.util.render.state.RectRenderState; +import me.humanbeing.nolongerhuman.util.traits.Util; +import net.minecraft.client.Camera; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.core.BlockPos; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; +import org.joml.Matrix3x2f; + +import java.awt.*; + +public class RenderUtil implements Util { + public static void rect(GuiGraphics context, float x1, float y1, float x2, float y2, int color) { + int ix1 = Math.round(x1); + int iy1 = Math.round(y1); + int ix2 = Math.round(x2); + int iy2 = Math.round(y2); + + context.fill(ix1, iy1, ix2, iy2, color); + } + + public static void rect(GuiGraphics context, float x1, float y1, float x2, float y2, int color, float width) { + int w = Math.max(1, Math.round(width)); + + context.fill(Math.round(x1), Math.round(y1), Math.round(x2), Math.round(y1) + w, color); + context.fill(Math.round(x2) - w, Math.round(y1), Math.round(x2), Math.round(y2), color); + context.fill(Math.round(x1), Math.round(y2) - w, Math.round(x2), Math.round(y2), color); + context.fill(Math.round(x1), Math.round(y1), Math.round(x1) + w, Math.round(y2), color); + } + + public static void roundedRect(GuiGraphics context, float x1, float y1, float x2, float y2, float radius, int color) { + int left = Math.round(Math.min(x1, x2)); + int top = Math.round(Math.min(y1, y2)); + int right = Math.round(Math.max(x1, x2)); + int bottom = Math.round(Math.max(y1, y2)); + + int width = right - left; + int height = bottom - top; + + if (width <= 0 || height <= 0) { + return; + } + + int r = Math.round(radius); + r = Math.max(0, Math.min(r, Math.min(width / 2, height / 2))); + + if (r <= 0) { + context.fill(left, top, right, bottom, color); + return; + } + + context.fill(left + r, top, right - r, bottom, color); + context.fill(left, top + r, right, bottom - r, color); + + for (int i = 0; i < r; i++) { + double dy = r - i - 0.5D; + int dx = (int) Math.ceil(Math.sqrt(r * r - dy * dy)); + + context.fill(left + r - dx, top + i, right - r + dx, top + i + 1, color); + context.fill(left + r - dx, bottom - i - 1, right - r + dx, bottom - i, color); + } + } + + public static void roundedRect(GuiGraphics context, float x1, float y1, float x2, float y2, float radius, Color color) { + roundedRect(context, x1, y1, x2, y2, radius, color.getRGB()); + } + + public static void horizontalGradient(GuiGraphics context, float x1, float y1, float x2, float y2, Color left, Color right) { + int ix1 = Math.round(x1); + int iy1 = Math.round(y1); + int ix2 = Math.round(x2); + int iy2 = Math.round(y2); + + gradient(context, ix1, iy1, ix2, iy2, left.hashCode(), left.hashCode(), right.hashCode(), right.hashCode()); + } + + public static void verticalGradient(GuiGraphics context, float x1, float y1, float x2, float y2, Color top, Color bottom) { + int ix1 = Math.round(x1); + int iy1 = Math.round(y1); + int ix2 = Math.round(x2); + int iy2 = Math.round(y2); + + gradient(context, ix1, iy1, ix2, iy2, top.hashCode(), bottom.hashCode(), bottom.hashCode(), top.hashCode()); + } + + public static void gradient( + GuiGraphics graphics, + int x1, + int y1, + int x2, + int y2, + int topLeft, + int bottomLeft, + int bottomRight, + int topRight + ) { + graphics.guiRenderState.submitGuiElement(new RectRenderState( + RenderPipelines.GUI, + TextureSetup.noTexture(), + new Matrix3x2f(graphics.pose()), + x1, + y1, + x2, + y2, + topLeft, + bottomLeft, + bottomRight, + topRight, + graphics.scissorStack.peek() + )); + } + + public static void rect(PoseStack stack, float x1, float y1, float x2, float y2, int color) { + rectFilled(stack, x1, y1, x2, y2, color); + } + + public static void rect(PoseStack stack, float x1, float y1, float x2, float y2, int color, float width) { + drawHorizontalLine(stack, x1, x2, y1, color, width); + drawVerticalLine(stack, x2, y1, y2, color, width); + drawHorizontalLine(stack, x1, x2, y2, color, width); + drawVerticalLine(stack, x1, y1, y2, color, width); + } + + protected static void drawHorizontalLine(PoseStack matrices, float x1, float x2, float y, int color) { + if (x2 < x1) { + float i = x1; + x1 = x2; + x2 = i; + } + + rectFilled(matrices, x1, y, x2 + 1, y + 1, color); + } + + protected static void drawVerticalLine(PoseStack matrices, float x, float y1, float y2, int color) { + if (y2 < y1) { + float i = y1; + y1 = y2; + y2 = i; + } + + rectFilled(matrices, x, y1 + 1, x + 1, y2, color); + } + + protected static void drawHorizontalLine(PoseStack matrices, float x1, float x2, float y, int color, float width) { + if (x2 < x1) { + float i = x1; + x1 = x2; + x2 = i; + } + + rectFilled(matrices, x1, y, x2 + width, y + width, color); + } + + protected static void drawVerticalLine(PoseStack matrices, float x, float y1, float y2, int color, float width) { + if (y2 < y1) { + float i = y1; + y1 = y2; + y2 = i; + } + + rectFilled(matrices, x, y1 + width, x + width, y2, color); + } + + public static void rectFilled(PoseStack matrix, float x1, float y1, float x2, float y2, int color) { + float i; + + if (x1 < x2) { + i = x1; + x1 = x2; + x2 = i; + } + + if (y1 < y2) { + i = y1; + y1 = y2; + y2 = i; + } + + float f = (float) (color >> 24 & 255) / 255.0F; + float g = (float) (color >> 16 & 255) / 255.0F; + float h = (float) (color >> 8 & 255) / 255.0F; + float j = (float) (color & 255) / 255.0F; + + BufferBuilder bufferBuilder = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + bufferBuilder.addVertex(matrix.last().pose(), x1, y2, 0.0F).setColor(g, h, j, f); + bufferBuilder.addVertex(matrix.last().pose(), x2, y2, 0.0F).setColor(g, h, j, f); + bufferBuilder.addVertex(matrix.last().pose(), x2, y1, 0.0F).setColor(g, h, j, f); + bufferBuilder.addVertex(matrix.last().pose(), x1, y1, 0.0F).setColor(g, h, j, f); + + Layers.quads().draw(bufferBuilder.buildOrThrow()); + } + + public static void horizontalGradient(PoseStack matrix, float x1, float y1, float x2, float y2, Color left, Color right) { + BufferBuilder bufferBuilder = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + bufferBuilder.addVertex(matrix.last().pose(), x1, y1, 0.0F) + .setColor(left.getRed() / 255.0F, left.getGreen() / 255.0F, left.getBlue() / 255.0F, left.getAlpha() / 255.0F); + bufferBuilder.addVertex(matrix.last().pose(), x1, y2, 0.0F) + .setColor(left.getRed() / 255.0F, left.getGreen() / 255.0F, left.getBlue() / 255.0F, left.getAlpha() / 255.0F); + bufferBuilder.addVertex(matrix.last().pose(), x2, y2, 0.0F) + .setColor(right.getRed() / 255.0F, right.getGreen() / 255.0F, right.getBlue() / 255.0F, right.getAlpha() / 255.0F); + bufferBuilder.addVertex(matrix.last().pose(), x2, y1, 0.0F) + .setColor(right.getRed() / 255.0F, right.getGreen() / 255.0F, right.getBlue() / 255.0F, right.getAlpha() / 255.0F); + + Layers.quads().draw(bufferBuilder.buildOrThrow()); + } + + public static void verticalGradient(PoseStack matrix, float x1, float y1, float x2, float y2, Color top, Color bottom) { + BufferBuilder bufferBuilder = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + bufferBuilder.addVertex(matrix.last().pose(), x1, y1, 0.0F) + .setColor(top.getRed() / 255.0F, top.getGreen() / 255.0F, top.getBlue() / 255.0F, top.getAlpha() / 255.0F); + bufferBuilder.addVertex(matrix.last().pose(), x1, y2, 0.0F) + .setColor(bottom.getRed() / 255.0F, bottom.getGreen() / 255.0F, bottom.getBlue() / 255.0F, bottom.getAlpha() / 255.0F); + bufferBuilder.addVertex(matrix.last().pose(), x2, y2, 0.0F) + .setColor(bottom.getRed() / 255.0F, bottom.getGreen() / 255.0F, bottom.getBlue() / 255.0F, bottom.getAlpha() / 255.0F); + bufferBuilder.addVertex(matrix.last().pose(), x2, y1, 0.0F) + .setColor(top.getRed() / 255.0F, top.getGreen() / 255.0F, top.getBlue() / 255.0F, top.getAlpha() / 255.0F); + + Layers.quads().draw(bufferBuilder.buildOrThrow()); + } + + + public static void drawBoxFilled(PoseStack stack, AABB box, Color c) { + float minX = (float) (box.minX - mc.getEntityRenderDispatcher().camera.position().x()); + float minY = (float) (box.minY - mc.getEntityRenderDispatcher().camera.position().y()); + float minZ = (float) (box.minZ - mc.getEntityRenderDispatcher().camera.position().z()); + float maxX = (float) (box.maxX - mc.getEntityRenderDispatcher().camera.position().x()); + float maxY = (float) (box.maxY - mc.getEntityRenderDispatcher().camera.position().y()); + float maxZ = (float) (box.maxZ - mc.getEntityRenderDispatcher().camera.position().z()); + + BufferBuilder bufferBuilder = Tesselator.getInstance() + .begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); + + bufferBuilder.addVertex(stack.last().pose(), minX, minY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, minY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, minY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, minY, maxZ).setColor(c.getRGB()); + + bufferBuilder.addVertex(stack.last().pose(), minX, maxY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, maxY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, maxY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, maxY, minZ).setColor(c.getRGB()); + + bufferBuilder.addVertex(stack.last().pose(), minX, minY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, maxY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, maxY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, minY, minZ).setColor(c.getRGB()); + + bufferBuilder.addVertex(stack.last().pose(), maxX, minY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, maxY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, maxY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, minY, maxZ).setColor(c.getRGB()); + + bufferBuilder.addVertex(stack.last().pose(), minX, minY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, minY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), maxX, maxY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, maxY, maxZ).setColor(c.getRGB()); + + bufferBuilder.addVertex(stack.last().pose(), minX, minY, minZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, minY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, maxY, maxZ).setColor(c.getRGB()); + bufferBuilder.addVertex(stack.last().pose(), minX, maxY, minZ).setColor(c.getRGB()); + + Layers.quads().draw(bufferBuilder.buildOrThrow()); + } + + public static void drawBoxFilled(PoseStack stack, Vec3 vec, Color c) { + drawBoxFilled(stack, AABB.unitCubeFromLowerCorner(vec), c); + } + + public static void drawBoxFilled(PoseStack stack, BlockPos bp, Color c) { + drawBoxFilled(stack, new AABB(bp), c); + } + + public static void drawBox(PoseStack stack, AABB box, Color c, float lineWidth) { + drawBox(stack, Shapes.create(box), c, lineWidth); + } + + public static void drawBox(PoseStack stack, VoxelShape shape, Color c, float lineWidth) { + Vec3 camera = mc.getEntityRenderDispatcher().camera.position(); + + BufferBuilder bufferBuilder = Tesselator.getInstance() + .begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH); + + PoseStack.Pose pose = stack.last(); + int color = c.getRGB(); + + shape.forAllEdges((x1, y1, z1, x2, y2, z2) -> { + addLine( + bufferBuilder, + pose, + color, + lineWidth, + x1 - camera.x, + y1 - camera.y, + z1 - camera.z, + x2 - camera.x, + y2 - camera.y, + z2 - camera.z + ); + }); + + Layers.lines().draw(bufferBuilder.buildOrThrow()); + } + + private static void addLine( + BufferBuilder buf, + PoseStack.Pose pose, + int color, + float lineWidth, + double x1, + double y1, + double z1, + double x2, + double y2, + double z2 + ) { + float nx = (float) (x2 - x1); + float ny = (float) (y2 - y1); + float nz = (float) (z2 - z1); + + buf.addVertex(pose, (float) x1, (float) y1, (float) z1) + .setColor(color) + .setNormal(pose, nx, ny, nz) + .setLineWidth(lineWidth); + + buf.addVertex(pose, (float) x2, (float) y2, (float) z2) + .setColor(color) + .setNormal(pose, nx, ny, nz) + .setLineWidth(lineWidth); + } + + public static void drawBox(PoseStack stack, Vec3 vec, Color c, float lineWidth) { + drawBox(stack, AABB.unitCubeFromLowerCorner(vec), c, lineWidth); + } + + public static void drawBox(PoseStack stack, BlockPos bp, Color c, float lineWidth) { + drawBox(stack, new AABB(bp), c, lineWidth); + } + + public static PoseStack matrixFrom(Vec3 pos) { + PoseStack matrices = new PoseStack(); + Camera camera = mc.gameRenderer.getMainCamera(); + + matrices.mulPose(Axis.XP.rotationDegrees(camera.xRot())); + matrices.mulPose(Axis.YP.rotationDegrees(camera.yRot() + 180.0F)); + matrices.translate( + pos.x() - camera.position().x, + pos.y() - camera.position().y, + pos.z() - camera.position().z + ); + + return matrices; + } +} \ No newline at end of file diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/ScissorUtil.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/ScissorUtil.java new file mode 100644 index 0000000..e0930f8 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/ScissorUtil.java @@ -0,0 +1,26 @@ +package me.humanbeing.nolongerhuman.util.render; + +import net.minecraft.client.gui.GuiGraphics; + +public class ScissorUtil { + private static int X_1; + private static int Y_1; + private static int X_2; + private static int Y_2; + + public static void enable(GuiGraphics context, int x1, int y1, int x2, int y2) { + context.enableScissor(x1, y1, x2, y2); + X_1 = x1; + Y_1 = y1; + X_2 = x2; + Y_2 = y2; + } + + public static void disable(GuiGraphics context) { + context.disableScissor(); + } + + public static void enable(GuiGraphics context) { + context.enableScissor(X_1, Y_1, X_2, Y_2); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/render/state/RectRenderState.java b/src/main/java/me/humanbeing/nolongerhuman/util/render/state/RectRenderState.java new file mode 100644 index 0000000..422209f --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/render/state/RectRenderState.java @@ -0,0 +1,28 @@ +package me.humanbeing.nolongerhuman.util.render.state; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.GuiElementRenderState; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix3x2f; + +public record RectRenderState(RenderPipeline pipeline, TextureSetup textureSetup, Matrix3x2f pose, int x0, int y0, int x1, int y1, int topLeft, int bottomLeft, int bottomRight, int topRight, @Nullable ScreenRectangle scissorArea, @Nullable ScreenRectangle bounds) implements GuiElementRenderState { + public RectRenderState(RenderPipeline renderPipeline, TextureSetup textureSetup, Matrix3x2f matrix3x2f, int x0, int y0, int x1, int y1, int topLeft, int bottomLeft, int bottomRight, int topRight, @Nullable ScreenRectangle screenRectangle) { + this(renderPipeline, textureSetup, matrix3x2f, x0, y0, x1, y1, topLeft, bottomLeft, bottomRight, topRight, screenRectangle, getBounds(x0, y0, x1, y1, matrix3x2f, screenRectangle)); + } + + public void buildVertices(VertexConsumer vertexConsumer) { + vertexConsumer.addVertexWith2DPose(this.pose(), (float)this.x0(), (float)this.y0()).setColor(this.topLeft()); + vertexConsumer.addVertexWith2DPose(this.pose(), (float)this.x0(), (float)this.y1()).setColor(this.bottomLeft()); + vertexConsumer.addVertexWith2DPose(this.pose(), (float)this.x1(), (float)this.y1()).setColor(this.bottomRight()); + vertexConsumer.addVertexWith2DPose(this.pose(), (float)this.x1(), (float)this.y0()).setColor(this.topRight()); + } + + @Nullable + private static ScreenRectangle getBounds(int i, int j, int k, int l, Matrix3x2f matrix3x2f, @Nullable ScreenRectangle screenRectangle) { + ScreenRectangle screenRectangle2 = (new ScreenRectangle(i, j, k - i, l - j)).transformMaxBounds(matrix3x2f); + return screenRectangle != null ? screenRectangle.intersection(screenRectangle2) : screenRectangle2; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/traits/Jsonable.java b/src/main/java/me/humanbeing/nolongerhuman/util/traits/Jsonable.java new file mode 100644 index 0000000..cafeb4c --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/traits/Jsonable.java @@ -0,0 +1,13 @@ +package me.humanbeing.nolongerhuman.util.traits; + +import com.google.gson.JsonElement; + +public interface Jsonable { + JsonElement toJson(); + + void fromJson(JsonElement element); + + default String getFileName() { + return ""; + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/traits/Toggleable.java b/src/main/java/me/humanbeing/nolongerhuman/util/traits/Toggleable.java new file mode 100644 index 0000000..8fa7ba7 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/traits/Toggleable.java @@ -0,0 +1,18 @@ +package me.humanbeing.nolongerhuman.util.traits; + +public interface Toggleable { + boolean isToggled(); + + void enable(); + + void disable(); + + default void toggle() { + if (isToggled()) disable(); + else enable(); + } + + default void setToggled(boolean toggled) { + if(isToggled() != toggled) toggle(); + } +} diff --git a/src/main/java/me/humanbeing/nolongerhuman/util/traits/Util.java b/src/main/java/me/humanbeing/nolongerhuman/util/traits/Util.java new file mode 100644 index 0000000..9da1f73 --- /dev/null +++ b/src/main/java/me/humanbeing/nolongerhuman/util/traits/Util.java @@ -0,0 +1,9 @@ +package me.humanbeing.nolongerhuman.util.traits; + +import me.humanbeing.nolongerhuman.event.system.EventBus; +import net.minecraft.client.Minecraft; + +public interface Util { + Minecraft mc = Minecraft.getInstance(); + EventBus EVENT_BUS = new EventBus(); +} diff --git a/src/main/java/meteordevelopment/discordipc/DiscordIPC.java b/src/main/java/meteordevelopment/discordipc/DiscordIPC.java new file mode 100644 index 0000000..a334b12 --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/DiscordIPC.java @@ -0,0 +1,119 @@ +package meteordevelopment.discordipc; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import meteordevelopment.discordipc.connection.Connection; + +import java.lang.management.ManagementFactory; +import java.util.function.BiConsumer; + +public class DiscordIPC { + private static final Gson GSON = new Gson(); + + private static BiConsumer onError = DiscordIPC::defaultErrorCallback; + + private static Connection c; + private static Runnable onReady; + + private static boolean receivedDispatch; + private static JsonObject queuedActivity; + + private static IPCUser user; + + + public static void setOnError(BiConsumer onError) { + DiscordIPC.onError = onError; + } + + + public static boolean start(long appId, Runnable onReady) { + // Open connection + c = Connection.open(DiscordIPC::onPacket); + if (c == null) return false; + + DiscordIPC.onReady = onReady; + + // Handshake + JsonObject o = new JsonObject(); + o.addProperty("v", 1); + o.addProperty("client_id", Long.toString(appId)); + c.write(Opcode.Handshake, o); + + return true; + } + + + public static boolean isConnected() { + return c != null; + } + + public static IPCUser getUser() { + return user; + } + + + public static void setActivity(RichPresence presence) { + if (c == null) return; + + queuedActivity = presence.toJson(); + if (receivedDispatch) sendActivity(); + } + + public static void stop() { + if (c != null) { + c.close(); + + c = null; + onReady = null; + receivedDispatch = false; + queuedActivity = null; + user = null; + } + } + + private static void sendActivity() { + JsonObject args = new JsonObject(); + args.addProperty("pid", getPID()); + args.add("activity", queuedActivity); + + JsonObject o = new JsonObject(); + o.addProperty("cmd", "SET_ACTIVITY"); + o.add("args", args); + + c.write(Opcode.Frame, o); + queuedActivity = null; + } + + private static void onPacket(Packet packet) { + // Close + if (packet.opcode() == Opcode.Close) { + if (onError != null) onError.accept(packet.data().get("code").getAsInt(), packet.data().get("message").getAsString()); + stop(); + } + // Frame + else if (packet.opcode() == Opcode.Frame) { + // Error + if (packet.data().has("evt") && packet.data().get("evt").getAsString().equals("ERROR")) { + JsonObject d = packet.data().getAsJsonObject("data"); + if (onError != null) onError.accept(d.get("code").getAsInt(), d.get("message").getAsString()); + } + // Dispatch + else if (packet.data().has("cmd") && packet.data().get("cmd").getAsString().equals("DISPATCH")) { + receivedDispatch = true; + user = GSON.fromJson(packet.data().getAsJsonObject("data").getAsJsonObject("user"), IPCUser.class); + + if (onReady != null) onReady.run(); + if (queuedActivity != null) sendActivity(); + } + } + } + + private static int getPID() { + String pr = ManagementFactory.getRuntimeMXBean().getName(); + return Integer.parseInt(pr.substring(0, pr.indexOf('@'))); + } + + private static void defaultErrorCallback(int code, String message) { + System.err.println("Discord IPC error " + code + " with message: " + message); + } +} diff --git a/src/main/java/meteordevelopment/discordipc/IPCUser.java b/src/main/java/meteordevelopment/discordipc/IPCUser.java new file mode 100644 index 0000000..51ba4e7 --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/IPCUser.java @@ -0,0 +1,11 @@ +package meteordevelopment.discordipc; + +public class IPCUser { + public String id; + public String username; + public String discriminator; + public String avatar; + public boolean bot; + public String flags; + public int premium_type; +} diff --git a/src/main/java/meteordevelopment/discordipc/Opcode.java b/src/main/java/meteordevelopment/discordipc/Opcode.java new file mode 100644 index 0000000..146c465 --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/Opcode.java @@ -0,0 +1,15 @@ +package meteordevelopment.discordipc; + +public enum Opcode { + Handshake, + Frame, + Close, + Ping, + Pong; + + private static final Opcode[] VALUES = values(); + + public static Opcode valueOf(int i) { + return VALUES[i]; + } +} diff --git a/src/main/java/meteordevelopment/discordipc/Packet.java b/src/main/java/meteordevelopment/discordipc/Packet.java new file mode 100644 index 0000000..344a030 --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/Packet.java @@ -0,0 +1,6 @@ +package meteordevelopment.discordipc; + +import com.google.gson.JsonObject; + +public record Packet(Opcode opcode, JsonObject data) { +} diff --git a/src/main/java/meteordevelopment/discordipc/RichPresence.java b/src/main/java/meteordevelopment/discordipc/RichPresence.java new file mode 100644 index 0000000..b026db8 --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/RichPresence.java @@ -0,0 +1,83 @@ +package meteordevelopment.discordipc; + +import com.google.gson.JsonObject; + +public class RichPresence { + private String details; + private String state; + + private Assets assets; + private Timestamps timestamps; + + public void setDetails(String details) { + this.details = details; + } + + public void setState(String state) { + this.state = state; + } + + public void setLargeImage(String key, String text) { + if (assets == null) assets = new Assets(); + assets.large_image = key; + assets.large_text = text; + } + + public void setSmallImage(String key, String text) { + if (assets == null) assets = new Assets(); + assets.small_image = key; + assets.small_text = text; + } + + public void setStart(long time) { + if (timestamps == null) timestamps = new Timestamps(); + timestamps.start = time; + } + + public void setEnd(long time) { + if (timestamps == null) timestamps = new Timestamps(); + timestamps.end = time; + } + + public JsonObject toJson() { + // Main + JsonObject o = new JsonObject(); + + if (details != null) o.addProperty("details", details); + if (state != null) o.addProperty("state", state); + + // Assets + if (assets != null) { + JsonObject a = new JsonObject(); + + if (assets.large_image != null) a.addProperty("large_image", assets.large_image); + if (assets.large_text != null) a.addProperty("large_text", assets.large_text); + if (assets.small_image != null) a.addProperty("small_image", assets.small_image); + if (assets.small_text != null) a.addProperty("small_text", assets.small_text); + + o.add("assets", a); + } + + // Timestamps + if (timestamps != null) { + JsonObject t = new JsonObject(); + + if (timestamps.start != null) t.addProperty("start", timestamps.start); + if (timestamps.end != null) t.addProperty("end", timestamps.end); + + o.add("timestamps", t); + } + + return o; + } + + public static class Assets { + public String large_image, large_text; + public String small_image, small_text; + } + + public static class Timestamps { + public Long start; + public Long end; + } +} diff --git a/src/main/java/meteordevelopment/discordipc/connection/Connection.java b/src/main/java/meteordevelopment/discordipc/connection/Connection.java new file mode 100644 index 0000000..7f011b5 --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/connection/Connection.java @@ -0,0 +1,64 @@ +package meteordevelopment.discordipc.connection; + +import com.google.gson.JsonObject; +import meteordevelopment.discordipc.Opcode; +import meteordevelopment.discordipc.Packet; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.UUID; +import java.util.function.Consumer; + +public abstract class Connection { + private final static String[] UNIX_TEMP_PATHS = { "XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP" }; + + public static Connection open(Consumer callback) { + String os = System.getProperty("os.name").toLowerCase(); + + // Windows + if (os.contains("win")) { + for (int i = 0; i < 10; i++) { + try { + return new WinConnection("\\\\.\\pipe\\discord-ipc-" + i, callback); + } catch (IOException ignored) {} + } + } + // Unix + else { + String name = null; + + for (String tempPath : UNIX_TEMP_PATHS) { + name = System.getenv(tempPath); + if (name != null) break; + } + + if (name == null) name = "/tmp"; + name += "/discord-ipc-"; + + for (int i = 0; i < 10; i++) { + try { + return new UnixConnection(name + i, callback); + } catch (IOException ignored) {} + } + } + + return null; + } + + public void write(Opcode opcode, JsonObject o) { + o.addProperty("nonce", UUID.randomUUID().toString()); + + byte[] d = o.toString().getBytes(); + ByteBuffer packet = ByteBuffer.allocate(d.length + 8); + packet.putInt(Integer.reverseBytes(opcode.ordinal())); + packet.putInt(Integer.reverseBytes(d.length)); + packet.put(d); + + packet.rewind(); + write(packet); + } + + protected abstract void write(ByteBuffer buffer); + + public abstract void close(); +} diff --git a/src/main/java/meteordevelopment/discordipc/connection/UnixConnection.java b/src/main/java/meteordevelopment/discordipc/connection/UnixConnection.java new file mode 100644 index 0000000..3722b3a --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/connection/UnixConnection.java @@ -0,0 +1,104 @@ +package meteordevelopment.discordipc.connection; + +import com.google.gson.JsonParser; +import meteordevelopment.discordipc.Opcode; +import meteordevelopment.discordipc.Packet; + +import java.io.IOException; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.nio.charset.Charset; +import java.util.function.Consumer; + +public class UnixConnection extends Connection { + private final Selector s; + private final SocketChannel sc; + private final Consumer callback; + + public UnixConnection(String name, Consumer callback) throws IOException { + this.s = Selector.open(); + this.sc = SocketChannel.open(UnixDomainSocketAddress.of(name)); + this.callback = callback; + + sc.configureBlocking(false); + sc.register(s, SelectionKey.OP_READ); + + Thread thread = new Thread(this::run); + thread.setName("Discord IPC - Read thread"); + thread.start(); + } + + private void run() { + State state = State.Opcode; + + ByteBuffer intB = ByteBuffer.allocate(4); + ByteBuffer dataB = null; + + Opcode opcode = null; + + try { + while (true) { + s.select(); + + switch (state) { + case Opcode -> { + sc.read(intB); + if (intB.hasRemaining()) break; + + opcode = Opcode.valueOf(Integer.reverseBytes(intB.getInt(0))); + state = State.Length; + + intB.rewind(); + } + case Length -> { + sc.read(intB); + if (intB.hasRemaining()) break; + + dataB = ByteBuffer.allocate(Integer.reverseBytes(intB.getInt(0))); + state = State.Data; + + intB.rewind(); + } + case Data -> { + sc.read(dataB); + if (dataB.hasRemaining()) break; + + String data = Charset.defaultCharset().decode(dataB.rewind()).toString(); + callback.accept(new Packet(opcode, JsonParser.parseString(data).getAsJsonObject())); + + dataB = null; + state = State.Opcode; + } + } + } + } catch (Exception ignored) {} + } + + @Override + protected void write(ByteBuffer buffer) { + try { + sc.write(buffer); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void close() { + try { + s.close(); + sc.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private enum State { + Opcode, + Length, + Data + } +} diff --git a/src/main/java/meteordevelopment/discordipc/connection/WinConnection.java b/src/main/java/meteordevelopment/discordipc/connection/WinConnection.java new file mode 100644 index 0000000..f3fe49a --- /dev/null +++ b/src/main/java/meteordevelopment/discordipc/connection/WinConnection.java @@ -0,0 +1,82 @@ +package meteordevelopment.discordipc.connection; + +import com.google.gson.JsonParser; +import meteordevelopment.discordipc.Opcode; +import meteordevelopment.discordipc.Packet; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.function.Consumer; + +public class WinConnection extends Connection { + private final RandomAccessFile raf; + private final Consumer callback; + + WinConnection(String name, Consumer callback) throws IOException { + this.raf = new RandomAccessFile(name, "rw"); + this.callback = callback; + + Thread thread = new Thread(this::run); + thread.setName("Discord IPC - Read thread"); + thread.start(); + } + + @Override + protected void write(ByteBuffer buffer) { + try { + raf.write(buffer.array()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void run() { + ByteBuffer intB = ByteBuffer.allocate(4); + + try { + while (true) { + // Opcode + readFully(intB); + Opcode opcode = Opcode.valueOf(Integer.reverseBytes(intB.getInt(0))); + + // Length + readFully(intB); + int length = Integer.reverseBytes(intB.getInt(0)); + + // Data + ByteBuffer dataB = ByteBuffer.allocate(length); + readFully(dataB); + String data = Charset.defaultCharset().decode(dataB.rewind()).toString(); + + // Call callback + callback.accept(new Packet(opcode, JsonParser.parseString(data).getAsJsonObject())); + } + } catch (Exception ignored) {} + } + + private void readFully(ByteBuffer buffer) throws IOException { + buffer.rewind(); + + while (raf.length() < buffer.remaining()) { + Thread.onSpinWait(); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + while (buffer.hasRemaining()) raf.getChannel().read(buffer); + } + + @Override + public void close() { + try { + raf.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/resources/assets/nolongerhuman/shaders/core/rendertype_lines_smooth.fsh b/src/main/resources/assets/nolongerhuman/shaders/core/rendertype_lines_smooth.fsh new file mode 100644 index 0000000..99c5eed --- /dev/null +++ b/src/main/resources/assets/nolongerhuman/shaders/core/rendertype_lines_smooth.fsh @@ -0,0 +1,20 @@ +#version 330 + +#moj_import +#moj_import + +in float sphericalVertexDistance; +in float cylindricalVertexDistance; +in vec4 vertexColor; +in float lineEdge; + +out vec4 fragColor; + +void main() { + vec4 color = vertexColor * ColorModulator; + color.a *= exp(-4.0 * lineEdge * lineEdge); + + if (color.a < 0.001) discard; + + fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor); +} \ No newline at end of file diff --git a/src/main/resources/assets/nolongerhuman/shaders/core/rendertype_lines_smooth.vsh b/src/main/resources/assets/nolongerhuman/shaders/core/rendertype_lines_smooth.vsh new file mode 100644 index 0000000..72918a8 --- /dev/null +++ b/src/main/resources/assets/nolongerhuman/shaders/core/rendertype_lines_smooth.vsh @@ -0,0 +1,51 @@ +#version 330 + +#moj_import +#moj_import +#moj_import +#moj_import + +in vec3 Position; +in vec4 Color; +in vec3 Normal; +in float LineWidth; + +out float sphericalVertexDistance; +out float cylindricalVertexDistance; +out vec4 vertexColor; +out float lineEdge; + +const float VIEW_SHRINK = 1.0 - (1.0 / 256.0); +const mat4 VIEW_SCALE = mat4( + VIEW_SHRINK, 0.0, 0.0, 0.0, + 0.0, VIEW_SHRINK, 0.0, 0.0, + 0.0, 0.0, VIEW_SHRINK, 0.0, + 0.0, 0.0, 0.0, 1.0 +); + +void main() { + vec4 linePosStart = ProjMat * VIEW_SCALE * ModelViewMat * vec4(Position, 1.0); + vec4 linePosEnd = ProjMat * VIEW_SCALE * ModelViewMat * vec4(Position + Normal, 1.0); + + vec3 ndc1 = linePosStart.xyz / linePosStart.w; + vec3 ndc2 = linePosEnd.xyz / linePosEnd.w; + + vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * ScreenSize); + vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * LineWidth * 2 / ScreenSize; + + if (lineOffset.x < 0.0) { + lineOffset *= -1.0; + } + + if (gl_VertexID % 2 == 0) { + gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w); + lineEdge = 1.0; + } else { + gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w); + lineEdge = -1.0; + } + + sphericalVertexDistance = fog_spherical_distance(Position); + cylindricalVertexDistance = fog_cylindrical_distance(Position); + vertexColor = Color; +} \ No newline at end of file diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..4389604 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,29 @@ +{ + "schemaVersion": 1, + "id": "nolongerhuman", + "version": "${version}", + "name": "nolongerhuman", + "description": "nolongerhuman client", + "authors": [ + "humanbeing" + ], + "license": "MIT", + "environment": "client", + "accessWidener": "nolongerhuman.accesswidener", + "entrypoints": { + "client": [ + "me.humanbeing.nolongerhuman.nolongerhuman" + ], + "main": [ + "me.humanbeing.nolongerhuman.nolongerhuman" + ] + }, + "mixins": [ + "humanbeing.mixins.json" + ], + "depends": { + "fabricloader": ">=${loader_version}", + "fabric": "*", + "minecraft": "${minecraft_version}" + } +} diff --git a/src/main/resources/humanbeing.mixins.json b/src/main/resources/humanbeing.mixins.json new file mode 100644 index 0000000..0dcf852 --- /dev/null +++ b/src/main/resources/humanbeing.mixins.json @@ -0,0 +1,66 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "me.humanbeing.nolongerhuman.mixin", + "compatibilityLevel": "JAVA_21", + "mixins": [ + "network.MixinConnection" + ], + "client": [ + "entity.MixinClientPlayerEntity", + "input.MixinKeyboardHandler", + "input.MixinMouseHandler", + "network.MixinClientPacketListener", + "render.MixinChatComponent", + "render.MixinLevelRenderer", + "render.MixinDeltaTrackerTimer", + "render.gui.MixinCommandSuggestions", + "render.gui.MixinGui", + "ChinaGUINoBlurMixin", + "render.MixinParticleEngine", + "render.gui.MixinNoScreenBlur", + "entity.MixinEntity", + "render.MixinParticleEngine", + "render.MixinGameRenderer", + "render.MixinScreenEffectRenderer", + "render.MixinFogRenderer", + "render.MixinLivingEntityRenderer", + "render.MixinParticleEngine", + "render.MixinGameRenderer", + "render.gui.MixinGui", + "render.MixinFogRenderer", + "effect.MixinMobEffectInstance", + "render.gui.MixinGui", + "render.MixinFogRenderer", + "entity.MixinLivingEntityNoRenderArmor", + "player.MixinMultiPlayerGameMode", + "accessor.IMultiPlayerGameMode", + "player.MixinNoInteractPlayer", + "player.MixinNoInteractGameMode", + "render.MixinGameRendererNoEntityTrace", + "entity.MixinLivingEntity", + "entity.MixinEntity", + "render.MixinBossHealthOverlay", + "render.MixinScreenEffectRenderer", + "render.MixinEntity", + "render.MixinLevelRenderer", + "render.MixinWorldBorderRenderer", + "render.MixinFogRenderer", + "render.MixinGameRendererViewModel", + "render.MixinItemInHandRendererViewModel", + "render.MixinNoEatingAnimation", + "render.MixinHandAnimations", + "entity.MixinEntityNoRenderCrystals", + "render.MixinSkyRenderer", + "render.MixinEntityRenderer", + "render.MixinCamera", + "input.MixinMouseHandler", + "accessor.MouseHandlerAccessor", + "render.gui.GuiGraphicsMixin", + "render.FontMixin", + "render.ChatComponentMixin" + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/src/main/resources/nolongerhuman.accesswidener b/src/main/resources/nolongerhuman.accesswidener new file mode 100644 index 0000000..a60449a --- /dev/null +++ b/src/main/resources/nolongerhuman.accesswidener @@ -0,0 +1,8 @@ +accessWidener v2 named + +accessible field net/minecraft/client/Minecraft rightClickDelay I +accessible field net/minecraft/network/protocol/game/ServerboundInteractPacket entityId I +accessible method net/minecraft/network/protocol/game/ServerboundInteractPacket$Action getType ()Lnet/minecraft/network/protocol/game/ServerboundInteractPacket$ActionType; +accessible class net/minecraft/network/protocol/game/ServerboundInteractPacket$ActionType +accessible field net/minecraft/network/protocol/game/ServerboundInteractPacket action Lnet/minecraft/network/protocol/game/ServerboundInteractPacket$Action; +accessible method net/minecraft/client/multiplayer/MultiPlayerGameMode ensureHasSentCarriedItem ()V \ No newline at end of file