diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e59ca03 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/gradlew text eol=lf +*.bat text eol=crlf diff --git a/.gitignore b/.gitignore index edeba0a..8ba5637 100644 --- a/.gitignore +++ b/.gitignore @@ -1,49 +1,37 @@ -# ---> Java -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) +out/ +bin/ +run/ +build/ +.idea/ +.gradle/ +.vscode/ .mtj.tmp/ +.settings/ -# Package Files # +*.iml +*.ipr +*.iws +*.jfr +*.log *.jar *.war *.nar *.ear *.zip -*.tar.gz *.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +*.ctxt +*.hprof +*.class +*.launch +.project +*.tar.gz +.classpath +*.DS_Store hs_err_pid* replay_pid* - -# ---> Gradle -.gradle -**/build/ -!src/**/build/ - -# Ignore Gradle GUI config +hs_err_*.log +replay_*.log gradle-app.setting - -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) !gradle-wrapper.jar - -# Avoid ignore Gradle wrappper properties -!gradle-wrapper.properties - -# Cache of project .gradletasknamecache - -# Eclipse Gradle plugin generated files -# Eclipse Core -.project -# JDT-specific (Eclipse Java Development Tools) -.classpath - +!gradle-wrapper.properties diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..769b326 --- /dev/null +++ b/build.gradle @@ -0,0 +1,88 @@ +plugins { + id 'fabric-loom' version "${loom_version}" + id 'maven-publish' +} + +version = project.mod_version +group = project.maven_group + +base { + archivesName = project.archives_base_name +} + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. +} + +loom { + splitEnvironmentSourceSets() + + mods { + "homestead-relay" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } + +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": inputs.properties.version + } +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 17 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +jar { + inputs.property "archivesName", project.base.archivesName + + from("LICENSE") { + rename { "${it}_${inputs.properties.archivesName}"} + } +} + +// configure the maven publication +publishing { + publications { + create("mavenJava", MavenPublication) { + artifactId = project.archives_base_name + from components.java + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6a96bb7 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,21 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G +org.gradle.parallel=true + +# IntelliJ IDEA is not yet fully compatible with configuration cache, see: https://github.com/FabricMC/fabric-loom/issues/1349 +org.gradle.configuration-cache=false + +# Fabric Properties +# check these on https://fabricmc.net/develop +minecraft_version=1.20.1 +yarn_mappings=1.20.1+build.10 +loader_version=0.17.2 +loom_version=1.13-SNAPSHOT + +# Mod Properties +mod_version=1.0.8 +maven_group=com.overlord.qualityoflife +archives_base_name=quality-of-life + +# Dependencies +fabric_version=0.92.6+1.20.1 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..8bdaf60 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..2e11132 --- /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.1.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..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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 + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + 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 optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..75c4d72 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} \ No newline at end of file diff --git a/src/client/java/com/overlord/qualityoflife/QualityOfLifeClient.java b/src/client/java/com/overlord/qualityoflife/QualityOfLifeClient.java new file mode 100644 index 0000000..69213fe --- /dev/null +++ b/src/client/java/com/overlord/qualityoflife/QualityOfLifeClient.java @@ -0,0 +1,18 @@ +package com.overlord.qualityoflife; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import net.fabricmc.api.ClientModInitializer; + +public class QualityOfLifeClient implements ClientModInitializer +{ + public static final String MOD = "HomesteadRelay"; + public static final String MOD_ID = "homestead-relay"; + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + + @Override + public void onInitializeClient() + { + LOGGER.info("[{}] Initializing (client).", MOD); + } +} diff --git a/src/client/resources/quality-of-life.client.mixins.json b/src/client/resources/quality-of-life.client.mixins.json new file mode 100644 index 0000000..3131748 --- /dev/null +++ b/src/client/resources/quality-of-life.client.mixins.json @@ -0,0 +1,11 @@ +{ + "required": true, + "package": "com.overlord.qualityoflife.mixin.client", + "compatibilityLevel": "JAVA_17", + "client": [ + + ], + "injectors": { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/src/main/java/com/overlord/qualityoflife/QualityOfLife.java b/src/main/java/com/overlord/qualityoflife/QualityOfLife.java new file mode 100644 index 0000000..0ae6673 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/QualityOfLife.java @@ -0,0 +1,35 @@ +package com.overlord.qualityoflife; + +import com.google.gson.Gson; +import org.slf4j.LoggerFactory; +import com.google.gson.GsonBuilder; +import net.fabricmc.api.ModInitializer; +import com.overlord.qualityoflife.classes.controller.*; +import com.overlord.qualityoflife.classes.controller.util.ModLogger; + +/** + * Mod Initializer for QoL Mod. + */ +public class QualityOfLife implements ModInitializer +{ + public static final String MOD = "HomesteadRelay"; + public static final String MOD_ID = "homestead-relay"; + public static final ModLogger LOGGER = new ModLogger(LoggerFactory.getLogger(MOD_ID)); + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + @Override + public void onInitialize() + { + LOGGER.setPrefix(MOD); + + LOGGER.info("Initializing (server)."); + + PurgeController.register(); // Clean-up for ServerCore mishaps + AfflictionController.register(); // Nerve Agent & Cure Handling + PingCommandController.register(); // ping-Command + IgnoreCommandController.register(); // ignore-Command + AutomaticUpdateController.register(); // Automatic updates for the mod + + LOGGER.info("Finished initializing (server)."); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/affliction/AfflictionManager.java b/src/main/java/com/overlord/qualityoflife/classes/affliction/AfflictionManager.java new file mode 100644 index 0000000..fa3af34 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/affliction/AfflictionManager.java @@ -0,0 +1,150 @@ +package com.overlord.qualityoflife.classes.affliction; + +import java.util.*; +import java.nio.file.*; +import java.io.IOException; +import com.google.gson.Gson; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.random.Random; +import java.util.concurrent.ConcurrentHashMap; +import com.overlord.qualityoflife.QualityOfLife; +import net.minecraft.entity.effect.StatusEffects; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.entity.effect.StatusEffectInstance; +import com.overlord.qualityoflife.classes.controller.ConfigController; + +public class AfflictionManager +{ + private static final AfflictionManager INSTANCE = new AfflictionManager(); + public static AfflictionManager instance() { return INSTANCE; } + + private final Map map = new ConcurrentHashMap<>(); + private final Gson gson = QualityOfLife.GSON; + + private static final long TICKS_PER_DAY = 24000L; + private static final long TOTAL_TICKS = TICKS_PER_DAY * 50L; // 50 MC days -> 1_200_000 ticks + + private long saveTickCounter = 0L; + + public boolean isAfflicted(UUID uuid) { + return map.containsKey(uuid); + } + + public void applyAffliction(UUID uuid) + { + if (isAfflicted(uuid)) return; + + PlayerAffliction pa = new PlayerAffliction(uuid); + map.put(uuid, pa); + saveFor(pa); + } + + public void removeAffliction(UUID uuid) + { + PlayerAffliction pa = map.remove(uuid); + if (pa == null) return; + + Path p = ConfigController.AFFLICTIONS_DIR.resolve(uuid.toString() + ".json"); + + try { + ConfigController.deleteFile(p); + } catch (IOException ignored) {} + } + + public Optional getAffliction(UUID uuid) { + return Optional.ofNullable(map.get(uuid)); + } + + public void loadAll() + { + try + { + ConfigController.forEachJsonFile(ConfigController.AFFLICTIONS_DIR, path -> + { + String json = ConfigController.readFile(path); + PlayerAffliction pa = gson.fromJson(json, PlayerAffliction.class); + if (pa != null) map.put(pa.getUuid(), pa); + }); + } + catch (IOException e) { + QualityOfLife.LOGGER.error("Failed to load afflictions", e); + } + } + + public void saveAll() + { + for (PlayerAffliction pa : map.values()) + saveFor(pa); + } + + private void saveFor(PlayerAffliction pa) + { + Path p = ConfigController.AFFLICTIONS_DIR.resolve(pa.uuid + ".json"); + + try + { + ConfigController.writeFile(p, gson.toJson(pa)); + } + catch (IOException e) { + QualityOfLife.LOGGER.error("Failed to save affliction for {}", pa.uuid, e); + } + } + + /** + * Call from server tick (main thread). Only counts while player is online. + */ + public void tick(MinecraftServer server) + { + List players = server.getPlayerManager().getPlayerList(); + + for (ServerPlayerEntity player : players) + { + UUID uuid = player.getUuid(); + PlayerAffliction pa = map.get(uuid); + if (pa == null) continue; + + pa.ticksPlayed++; + + maybeTriggerTemporaryEffect(player, pa); + + if (pa.ticksPlayed >= TOTAL_TICKS) { + player.kill(); + removeAffliction(uuid); + } + } + + saveTickCounter++; + if (saveTickCounter >= 600) + { + saveTickCounter = 0; + saveAll(); + } + } + + private void maybeTriggerTemporaryEffect(ServerPlayerEntity player, PlayerAffliction pa) + { + // progress fraction 0..1 + double progress = Math.min(1.0, (double)pa.ticksPlayed / (double)TOTAL_TICKS); + + // desired expected events per day: linear from 1/3 at day 1 to 5 at day 49/50 + double eventsPerDayAtStart = 1.0 / 3.0; + double eventsPerDayAtEnd = 7.0; + + double expectedEventsPerDay = eventsPerDayAtStart * (1.0 - progress) + eventsPerDayAtEnd * progress; + double perTickChance = expectedEventsPerDay / (double)TICKS_PER_DAY; + + Random rng = player.getRandom(); + if (rng.nextDouble() < perTickChance) + { + boolean chooseNausea = rng.nextDouble() < 0.5; + int durationTicks = 100 + rng.nextInt(100); // 5-10 seconds roughly + + player.addStatusEffect( + new StatusEffectInstance( + chooseNausea ? StatusEffects.NAUSEA : StatusEffects.DARKNESS, durationTicks, 0, + false, false, false + ) + ); + } + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/affliction/PlayerAffliction.java b/src/main/java/com/overlord/qualityoflife/classes/affliction/PlayerAffliction.java new file mode 100644 index 0000000..0b71925 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/affliction/PlayerAffliction.java @@ -0,0 +1,20 @@ +package com.overlord.qualityoflife.classes.affliction; + +import java.util.UUID; + +public class PlayerAffliction +{ + public String uuid; + public long ticksPlayed; + + public PlayerAffliction() {} + + public PlayerAffliction(UUID uuid) { + this.uuid = uuid.toString(); + this.ticksPlayed = 0L; + } + + public UUID getUuid() { + return UUID.fromString(uuid); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/AfflictionController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/AfflictionController.java new file mode 100644 index 0000000..a14a4f7 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/AfflictionController.java @@ -0,0 +1,20 @@ +package com.overlord.qualityoflife.classes.controller; + +import com.overlord.qualityoflife.classes.registry.ModEffects; +import com.overlord.qualityoflife.classes.registry.ModPotions; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; +import com.overlord.qualityoflife.classes.affliction.AfflictionManager; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; + +public class AfflictionController +{ + public static void register() + { + ModEffects.register(); + ModPotions.register(); + + ServerLifecycleEvents.SERVER_STARTED.register(server -> AfflictionManager.instance().loadAll()); + ServerLifecycleEvents.SERVER_STOPPING.register(server -> AfflictionManager.instance().saveAll()); + ServerTickEvents.END_SERVER_TICK.register(server -> AfflictionManager.instance().tick(server)); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/AutomaticUpdateController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/AutomaticUpdateController.java new file mode 100644 index 0000000..8eedfec --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/AutomaticUpdateController.java @@ -0,0 +1,174 @@ +package com.overlord.qualityoflife.classes.controller; + +import java.nio.file.Path; +import java.util.Optional; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.channels.FileChannel; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.server.MinecraftServer; +import java.util.concurrent.CompletableFuture; +import com.overlord.qualityoflife.QualityOfLife; +import com.google.gson.annotations.SerializedName; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import com.overlord.qualityoflife.classes.controller.util.extension.INetworkUtility; + +@SuppressWarnings("SameParameterValue") +public class AutomaticUpdateController extends INetworkUtility +{ + private static final String api = "https://cdn.security-command.org/homestead"; + private static final String info = api + "/latest.json"; + + private static Stats latest = null; + private static boolean update = false; + + private record Stats( + @SerializedName("version") String version, + @SerializedName("file") String filename, + @SerializedName("sha256") String checksum + ) + { + public String location() { + return api + "/" + filename; + } + } + + public static void register() + { + ServerLifecycleEvents.SERVER_STARTED.register(AutomaticUpdateController::checkForUpdate); + ServerLifecycleEvents.SERVER_STOPPING.register(AutomaticUpdateController::updateFile); + } + + // update (check, download, verify) + + private static void checkForUpdate(MinecraftServer server) + { + CompletableFuture.runAsync(() -> + { + try + { + String json = fetch(info, 5_000, 15_000); + if (json == null || json.isBlank()) + throw new RuntimeException("No metadata found."); + + Stats meta = QualityOfLife.GSON.fromJson(json, Stats.class); + if (meta == null || meta.version == null) + throw new RuntimeException("Invalid metadata."); + + latest = meta; + + if (!isNewerVersion(meta.version(), getCurrentVersion())) + { + QualityOfLife.LOGGER.info("Currently using the latest version of the mod."); + return; + } + + Path tmp = downloadFile( + meta.location(), + ConfigController.UPDATES_DIR.resolve(meta.filename() + ".tmp") + ); + + if (!verifySha256(tmp, meta.checksum())) + { + Files.deleteIfExists(tmp); + throw new RuntimeException("Invalid SHA-256 checksum."); + } + + Path staged = ConfigController.UPDATES_DIR.resolve(meta.filename()); + Files.move(tmp, staged, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + + update = true; + + QualityOfLife.LOGGER.warn("Successfully fetched new mod version from api, will be applied on next restart."); + } + catch (Exception e) + { + QualityOfLife.LOGGER.error("Error while checking for updates! '{}'", e.getMessage(), e); + } + }); + } + + // move/replace + + private static void updateFile(MinecraftServer server) + { + try + { + if (latest == null || !update) return; + + Path orig = getCurrentModFile(QualityOfLife.MOD_ID); + Path dest = ConfigController.MODS_DIR.resolve(latest.filename()); + Path file = ConfigController.UPDATES_DIR.resolve(latest.filename()); + + Files.move(file, dest, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + + if (orig != null) + Files.deleteIfExists(orig); + + try (FileChannel chan = FileChannel.open(ConfigController.MODS_DIR, StandardOpenOption.READ)) + { + // flush changes to the disk + chan.force(true); + } + catch (Throwable ignored) {} + + latest = null; + + Files.deleteIfExists(file); + } + catch (Exception e) + { + QualityOfLife.LOGGER.error("Error while updating file! '{}'", e.getMessage(), e); + } + } + + // utility + + private static String getCurrentVersion() + { + Optional mc = FabricLoader.getInstance().getModContainer(QualityOfLife.MOD_ID); + + return mc.isPresent() + ? mc.get().getMetadata().getVersion().getFriendlyString() + : "0.0.0"; + } + + private static Path getCurrentModFile(String modId) throws IOException + { + try (var stream = Files.newDirectoryStream(ConfigController.MODS_DIR, modId + "-*.jar")) + { + for (Path file : stream) + return file; + } + + return null; + } + + private static boolean isNewerVersion(String a, String b) + { + if (a == null) return false; + if (b == null || b.isEmpty()) return true; + + String[] A = a.split("\\."); + String[] B = b.split("\\."); + + int n = Math.max(A.length, B.length); + for (int i = 0; i < n; i++) + { + int ai = i < A.length ? parseIntSafe(A[i]) : 0; + int bi = i < B.length ? parseIntSafe(B[i]) : 0; + + if (ai > bi) return true; + if (ai < bi) return false; + } + + return false; + } + + private static int parseIntSafe(String s) { + try { return Integer.parseInt(s.replaceAll("[^0-9]", "")); } catch (Exception e) { return 0; } + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/ConfigController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/ConfigController.java new file mode 100644 index 0000000..dd189df --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/ConfigController.java @@ -0,0 +1,84 @@ +package com.overlord.qualityoflife.classes.controller; + +import java.nio.file.Path; +import java.io.IOException; +import java.nio.file.Files; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.nio.file.StandardOpenOption; +import net.fabricmc.loader.api.FabricLoader; +import com.overlord.qualityoflife.QualityOfLife; + +public class ConfigController +{ + public static final Path MODS_DIR = FabricLoader.getInstance().getGameDir().resolve("mods"); + public static final Path CONFIG_DIR = FabricLoader.getInstance().getConfigDir().resolve(QualityOfLife.MOD_ID); + public static final Path AFFLICTIONS_DIR = CONFIG_DIR.resolve("afflictions"); + public static final Path UPDATES_DIR = CONFIG_DIR.resolve("updates"); + public static final Path IGNORES_DIR = CONFIG_DIR.resolve("ignores"); + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + static + { + try + { + Files.createDirectories(CONFIG_DIR); + Files.createDirectories(AFFLICTIONS_DIR); + Files.createDirectories(UPDATES_DIR); + Files.createDirectories(IGNORES_DIR); + } + catch (IOException e) + { + throw new RuntimeException("Failed to create mod directories.", e); + } + } + + /** + * Read a JSON file from the mod directory + */ + public static String readFile(Path filePath) throws IOException { + return Files.readString(filePath); + } + + /** + * Write a JSON file to the mod directory + */ + public static void writeFile(Path filePath, String content) throws IOException { + Files.writeString(filePath, content, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + } + + /** + * Delete a file from the mod directory + */ + public static void deleteFile(Path filePath) throws IOException { + Files.deleteIfExists(filePath); + } + + /** + * List all JSON files in a directory + */ + public static void forEachJsonFile(Path directory, JsonFileConsumer consumer) throws IOException + { + try (var ds = Files.newDirectoryStream(directory, "*.json")) + { + for (Path p : ds) + { + try + { + consumer.accept(p); + } + catch (Throwable t) + { + QualityOfLife.LOGGER.error("Error processing file {}", p, t); + } + } + } + } + + @FunctionalInterface + public interface JsonFileConsumer + { + void accept(Path path) throws IOException; + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/IgnoreCommandController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/IgnoreCommandController.java new file mode 100644 index 0000000..e341ca8 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/IgnoreCommandController.java @@ -0,0 +1,293 @@ +package com.overlord.qualityoflife.classes.controller; + +import java.util.*; +import java.nio.file.Path; +import java.io.IOException; + +import com.overlord.qualityoflife.classes.controller.util.CommandExceptionFactory; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.minecraft.text.Text; +import com.mojang.brigadier.Command; +import java.util.concurrent.ConcurrentHashMap; +import com.overlord.qualityoflife.QualityOfLife; +import com.mojang.brigadier.context.CommandContext; +import net.minecraft.server.command.CommandManager; +import com.mojang.brigadier.arguments.BoolArgumentType; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.command.argument.EntityArgumentType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.overlord.qualityoflife.classes.controller.util.Player; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import com.overlord.qualityoflife.classes.controller.util.extension.IChatCommandController; + +public class IgnoreCommandController implements IChatCommandController +{ + public static class IgnoreData + { + public boolean globally = false; + public Set mutedBy = ConcurrentHashMap.newKeySet(); + } + + private static final Map ignoreMap = new ConcurrentHashMap<>(); + + public static void register() + { + ServerLifecycleEvents.SERVER_STARTED.register(server -> IgnoreCommandController.loadAll()); + ServerLifecycleEvents.SERVER_STOPPING.register(server -> IgnoreCommandController.saveAll()); + + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> + { + dispatcher.register(CommandManager.literal("ignore") + .then(CommandManager.argument("player", EntityArgumentType.player()) + .executes(IgnoreCommandController::executeIgnore) + .then(CommandManager.argument("global", BoolArgumentType.bool()) + .requires(source -> source.hasPermissionLevel(Player.PERMISSION_LEVEL_OP)) + .executes(IgnoreCommandController::executeIgnoreGlobal))) + .then(CommandManager.literal("list") + .executes(IgnoreCommandController::executeList)) + ); + + dispatcher.register(CommandManager.literal("unignore") + .then(CommandManager.argument("player", EntityArgumentType.player()) + .executes(IgnoreCommandController::executeUnignore) + .then(CommandManager.argument("global", BoolArgumentType.bool()) + .requires(source -> source.hasPermissionLevel(Player.PERMISSION_LEVEL_OP)) + .executes(IgnoreCommandController::executeUnignoreGlobal))) + ); + }); + } + + private static int executeIgnore(CommandContext context) throws CommandSyntaxException + { + ServerCommandSource source = context.getSource(); + ServerPlayerEntity executor = source.getPlayerOrThrow(); + ServerPlayerEntity target = EntityArgumentType.getPlayer(context, "player"); + + if (executor.getUuid().equals(target.getUuid())) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.INVALID_ARGUMENT, + "You cannot ignore yourself!" + ); + } + + UUID targetUuid = target.getUuid(); + IgnoreData data = ignoreMap.computeIfAbsent(targetUuid, k -> new IgnoreData()); + + if (data.mutedBy.contains(executor.getUuid())) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.WARNING, + "You're already ignoring '" + target.getName().getString() + "'." + ); + } + + data.mutedBy.add(executor.getUuid()); + save(targetUuid); + + source.sendFeedback(() -> Text.literal("Now ignoring '" + target.getName().getString() + "'."), false); + + return Command.SINGLE_SUCCESS; + } + + private static int executeIgnoreGlobal(CommandContext context) throws CommandSyntaxException + { + ServerCommandSource source = context.getSource(); + ServerPlayerEntity target = EntityArgumentType.getPlayer(context, "player"); + boolean global = BoolArgumentType.getBool(context, "global"); + + if (global) + { + UUID targetUuid = target.getUuid(); + IgnoreData data = ignoreMap.computeIfAbsent(targetUuid, k -> new IgnoreData()); + + if (data.globally) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.WARNING, + "'" + target.getName().getString() + "' is already being ignored globally." + ); + } + + data.globally = true; + save(targetUuid); + + source.sendFeedback(() -> Text.literal("'" + target.getName().getString() + "' is now globally ignored."), true); + return Command.SINGLE_SUCCESS; + } + + return executeIgnore(context); + } + + private static int executeUnignore(CommandContext context) throws CommandSyntaxException + { + ServerCommandSource source = context.getSource(); + ServerPlayerEntity executor = source.getPlayerOrThrow(); + ServerPlayerEntity target = EntityArgumentType.getPlayer(context, "player"); + + UUID targetUuid = target.getUuid(); + IgnoreData data = ignoreMap.get(targetUuid); + + if (executor.getUuid().equals(target.getUuid())) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.INVALID_ARGUMENT, + "You cannot unignore yourself!" + ); + } + + if (data == null || !data.mutedBy.contains(executor.getUuid())) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.WARNING, + "You're currently not ignoring '" + target.getName().getString() + "'." + ); + } + + data.mutedBy.remove(executor.getUuid()); + save(targetUuid); + + source.sendFeedback(() -> Text.literal("No longer ignoring '" + target + "'."), false); + + return Command.SINGLE_SUCCESS; + } + + private static int executeUnignoreGlobal(CommandContext context) throws CommandSyntaxException + { + ServerCommandSource source = context.getSource(); + ServerPlayerEntity target = EntityArgumentType.getPlayer(context, "player"); + boolean global = BoolArgumentType.getBool(context, "global"); + + UUID targetUuid = target.getUuid(); + IgnoreData data = ignoreMap.get(targetUuid); + + if (data == null) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.WARNING, + "'" + target.getName().getString() + "' is currently not ignored." + ); + } + + if (global) + { + if (!data.globally) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.WARNING, + "'" + target.getName().getString() + "' is currently not globally ignored." + ); + } + + data.globally = false; + source.sendFeedback(() -> Text.literal("'" + target.getName().getString() + "' is no longer globally ignored."), true); + } + else + { + return executeUnignore(context); + } + + save(targetUuid); + + return Command.SINGLE_SUCCESS; + } + + private static int executeList(CommandContext context) throws CommandSyntaxException + { + ServerCommandSource source = context.getSource(); + ServerPlayerEntity executor = source.getPlayerOrThrow(); + + List ignoringList = new ArrayList<>(); + + for (Map.Entry entry : ignoreMap.entrySet()) + { + if (entry.getValue().mutedBy.contains(executor.getUuid())) + ignoringList.add(entry.getKey()); + } + + if (ignoringList.isEmpty()) + { + throw CommandExceptionFactory.create( + CommandExceptionFactory.ExceptionType.WARNING, + "You're currently not ignoring anyone." + ); + } + + StringBuilder list = new StringBuilder("Ignoring: "); + for (UUID uuid : ignoringList) + list.append(uuid).append(", "); + String result = list.substring(0, list.length() - 2); + + source.sendFeedback(() -> Text.literal(result), false); + + return Command.SINGLE_SUCCESS; + } + + /** + * Check if a message from sender should be visible to receiver + * Returns true if the message should be blocked + */ + public static boolean shouldBlockMessage(UUID sender, UUID receiver) + { + IgnoreData data = ignoreMap.get(sender); + + if (data == null) return false; + if (data.globally) return true; + + return data.mutedBy.contains(receiver); + } + + public static void loadAll() + { + try + { + ConfigController.forEachJsonFile(ConfigController.IGNORES_DIR, path -> + { + String json = ConfigController.readFile(path); + IgnoreData data = QualityOfLife.GSON.fromJson(json, IgnoreData.class); + + UUID playerUuid = UUID.fromString(path.getFileName().toString().replace(".json", "")); + + if (data != null) + ignoreMap.put(playerUuid, data); + }); + } + catch (IOException e) + { + QualityOfLife.LOGGER.error("Failed to load ignore data", e); + } + } + + public static void saveAll() { + for (UUID uuid : ignoreMap.keySet()) + save(uuid); + } + + private static void save(UUID playerUuid) + { + IgnoreData data = ignoreMap.get(playerUuid); + + if (data == null || (data.mutedBy.isEmpty() && !data.globally)) + { + try + { + ConfigController.deleteFile(ConfigController.IGNORES_DIR.resolve(playerUuid + ".json")); + } + catch (IOException ignored) {} + + return; + } + + Path p = ConfigController.IGNORES_DIR.resolve(playerUuid + ".json"); + + try + { + ConfigController.writeFile(p, QualityOfLife.GSON.toJson(data)); + } + catch (IOException e) + { + QualityOfLife.LOGGER.error("Failed to save ignore data for {}", playerUuid, e); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/PingCommandController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/PingCommandController.java new file mode 100644 index 0000000..5bec823 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/PingCommandController.java @@ -0,0 +1,94 @@ +package com.overlord.qualityoflife.classes.controller; + +import java.util.Collection; +import net.minecraft.text.Text; +import com.mojang.brigadier.Command; +import net.minecraft.text.MutableText; +import net.minecraft.server.command.CommandManager; +import com.mojang.brigadier.context.CommandContext; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.command.argument.EntityArgumentType; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.overlord.qualityoflife.classes.controller.util.Color; +import com.overlord.qualityoflife.classes.controller.util.Player; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; +import com.overlord.qualityoflife.classes.controller.util.CommandExceptionFactory; +import com.overlord.qualityoflife.classes.controller.util.extension.IChatCommandController; + +public class PingCommandController implements IChatCommandController +{ + public static void register() + { + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> + { + dispatcher.register(CommandManager.literal("ping") + .executes(PingCommandController::execute) + .then(CommandManager.argument("target", EntityArgumentType.players()) + .requires(source -> source.hasPermissionLevel(Player.PERMISSION_LEVEL_OP)) // Op-only check + .executes(PingCommandController::executeWithTargets)) + ); + }); + } + + private static int execute(CommandContext context) throws CommandSyntaxException + { + ServerCommandSource source = context.getSource(); + + if (source.getPlayer() != null) + { + ServerPlayerEntity player = source.getPlayer(); + + player.sendMessage(getFormattedPingText(Player.of(player))); + } + else throw CommandExceptionFactory.create("This command has to be run by a player."); + + return Command.SINGLE_SUCCESS; + } + + public static int executeWithTargets(CommandContext context) throws CommandSyntaxException + { + Collection players = EntityArgumentType.getPlayers(context, "target"); + ServerCommandSource source = context.getSource(); + + MutableText response = Text.empty(); + + int i = 0; + int size = players.size(); + + for (ServerPlayerEntity serverPlayer : players) + { + boolean newline = players.size() > 1 && !(i == size-1); + + response.append(getFormattedPingText( + Player.of(serverPlayer), newline + )); + + i++; + } + + source.sendFeedback(() -> response, false); + + return Command.SINGLE_SUCCESS; + } + + private static Text getFormattedPingText(Player player) + { + return getFormattedPingText(player, false); + } + + private static Text getFormattedPingText(Player player, boolean appendNewline) + { + int ping = player.getPing(); + + Text pingValue = Text.literal(String.valueOf(ping)) + .styled(style -> style.withColor(Color.fromPing(ping))); + + return Text.literal("") + .append(player.display) + .append(": ") + .append(pingValue) + .append("ms") + .append(appendNewline ? "\n" : ""); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/PurgeController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/PurgeController.java new file mode 100644 index 0000000..e852aeb --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/PurgeController.java @@ -0,0 +1,71 @@ +package com.overlord.qualityoflife.classes.controller; + +import java.util.Queue; +import java.util.LinkedList; +import net.minecraft.entity.Entity; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.world.ServerWorld; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerEntityEvents; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; + +public class PurgeController +{ + private static final int BATCH_SIZE = 20; + private static boolean purgeRegistered = true; + private static final Queue queue = new LinkedList<>(); + + public static void register() + { + ServerLifecycleEvents.SERVER_STARTED.register(PurgeController::iterateEntities); + ServerTickEvents.END_SERVER_TICK.register(PurgeController::iterateQueue); + ServerEntityEvents.ENTITY_LOAD.register(PurgeController::discardEntity); + } + + private static boolean validEntity(ServerWorld world, Entity entity) + { + NbtCompound nbt = new NbtCompound(); + entity.writeNbt(nbt); + + return (!world.isClient && nbt.getBoolean("NoAI")); + } + + private static void iterateEntities(MinecraftServer server) + { + for (ServerWorld world : server.getWorlds()) + world.iterateEntities().forEach(entity -> queueEntity(world, entity)); + } + + private static void iterateQueue(MinecraftServer server) + { + if (!purgeRegistered) return; + + if (queue.isEmpty()) + { + purgeRegistered = false; + return; + } + + int count = 0; + while (count < BATCH_SIZE && !queue.isEmpty()) + { + Entity entity = queue.poll(); + + if (entity != null && entity.isAlive()) + entity.remove(Entity.RemovalReason.DISCARDED); + + count++; + } + } + + private static void queueEntity(ServerWorld world, Entity entity) { + if (validEntity(world, entity)) + queue.add(entity); + } + + private static void discardEntity(Entity entity, ServerWorld world) { + if (validEntity(world, entity)) + entity.remove(Entity.RemovalReason.DISCARDED); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/Color.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/Color.java new file mode 100644 index 0000000..b00332d --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/Color.java @@ -0,0 +1,19 @@ +package com.overlord.qualityoflife.classes.controller.util; + +import com.overlord.qualityoflife.classes.controller.util.extension.ColorGradient; + +public class Color +{ + private static final int MAX_PING = 1000; + private static final int[] COLORS_CACHE_PING = new int[MAX_PING + 1]; + private static final ColorGradient PING_GRADIENT = new ColorGradient(120f, 0f); + + public static int fromPing(int ping) + { + ping = Math.max(0, Math.min(ping, MAX_PING)); + + if (COLORS_CACHE_PING[ping] != 0) return COLORS_CACHE_PING[ping]; + + return COLORS_CACHE_PING[ping] = (PING_GRADIENT.getColor(ping / (float) MAX_PING)).toRgbInt(); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/CommandExceptionFactory.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/CommandExceptionFactory.java new file mode 100644 index 0000000..360ee99 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/CommandExceptionFactory.java @@ -0,0 +1,55 @@ +package com.overlord.qualityoflife.classes.controller.util; + +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; + +public class CommandExceptionFactory +{ + private CommandExceptionFactory() {} + + public enum ExceptionType { + WARNING, + GENERIC, + INVALID_ARGUMENT, + UNKNOWN_PLAYER, + NO_PERMISSION + } + + /** + * Create a plain exception with the given message. + * @param message the literal message shown to the player + */ + public static CommandSyntaxException create(String message) { + return new SimpleCommandExceptionType( + Text.literal(message).styled(style -> style.withColor(Formatting.RED)) + ).create(); + } + + /** + * Create a typed exception that may prepend or style the text differently. + * @param type the category of error + * @param message the literal message shown to the player + */ + public static CommandSyntaxException create(ExceptionType type, String message) + { + Text text = switch (type) + { + case WARNING -> + Text.literal(message).formatted(Formatting.YELLOW); + case GENERIC -> + Text.literal(message).formatted(Formatting.RED); + case INVALID_ARGUMENT -> + Text.literal("Invalid argument: ").formatted(Formatting.YELLOW) + .append(Text.literal(message).formatted(Formatting.RED)); + case UNKNOWN_PLAYER -> + Text.literal("Unknown player: ").formatted(Formatting.YELLOW) + .append(Text.literal(message).formatted(Formatting.RED)); + case NO_PERMISSION -> + Text.literal("Insufficient permission.").formatted(Formatting.RED); + }; + + return new SimpleCommandExceptionType(text).create(); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/Dimension.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/Dimension.java new file mode 100644 index 0000000..66515b9 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/Dimension.java @@ -0,0 +1,57 @@ +package com.overlord.qualityoflife.classes.controller.util; + +import net.minecraft.world.World; +import net.minecraft.util.Identifier; +import net.minecraft.util.Formatting; +import net.minecraft.registry.RegistryKey; + +public class Dimension +{ + public enum Type + { + IDENTIFIER, + READABLE + } + + public static String getNormalizedName(RegistryKey dimension) + { + return getNormalizedName(dimension, Type.READABLE); + } + + public static String getNormalizedName(RegistryKey dimension, Type type) + { + Identifier id = dimension.getValue(); + + String namespace = id.getNamespace(); + String path = id.getPath(); + + if (!"minecraft".equals(namespace) || type.equals(Type.IDENTIFIER)) + return (namespace + ":" + path); + + return switch (path) + { + case "overworld" -> "Overworld"; + case "the_nether" -> "Nether"; + case "the_end" -> "End"; + default -> "Unknown (" + id + ")"; + }; + } + + public static Formatting getColorByDimension(String dimension) + { + String key = dimension.contains(":") ? dimension.split(":", 2)[1] : dimension; + + return switch (key) + { + case "overworld" -> Formatting.GREEN; + case "the_nether" -> Formatting.DARK_RED; + case "the_end" -> Formatting.LIGHT_PURPLE; + default -> Formatting.BLACK; + }; + } + + public static Formatting getColorByDimension(RegistryKey dimension) + { + return getColorByDimension(dimension.getValue().getPath()); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/ModLogger.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/ModLogger.java new file mode 100644 index 0000000..1293f5b --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/ModLogger.java @@ -0,0 +1,329 @@ +package com.overlord.qualityoflife.classes.controller.util; + +import org.slf4j.Logger; + +/** + * Wraps a Logger to automatically prefix all messages with a mod identifier + */ +public class ModLogger implements Logger +{ + private final Logger delegate; + private String globalPrefix = ""; + + public ModLogger(Logger logger) { + this.delegate = logger; + } + + public void setPrefix(String prefix) { + this.globalPrefix = prefix == null || prefix.isEmpty() ? "" : "[" + prefix + "] "; + } + + private String addPrefix(String msg) { + return globalPrefix + msg; + } + + @Override + public String getName() { + return delegate.getName(); + } + + @Override + public boolean isTraceEnabled() { + return delegate.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + delegate.trace(addPrefix(msg)); + } + + @Override + public void trace(String format, Object arg) { + delegate.trace(addPrefix(format), arg); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + delegate.trace(addPrefix(format), arg1, arg2); + } + + @Override + public void trace(String format, Object... arguments) { + delegate.trace(addPrefix(format), arguments); + } + + @Override + public void trace(String msg, Throwable t) { + delegate.trace(addPrefix(msg), t); + } + + @Override + public boolean isTraceEnabled(org.slf4j.Marker marker) { + return delegate.isTraceEnabled(marker); + } + + @Override + public void trace(org.slf4j.Marker marker, String msg) { + delegate.trace(marker, addPrefix(msg)); + } + + @Override + public void trace(org.slf4j.Marker marker, String format, Object arg) { + delegate.trace(marker, addPrefix(format), arg); + } + + @Override + public void trace(org.slf4j.Marker marker, String format, Object arg1, Object arg2) { + delegate.trace(marker, addPrefix(format), arg1, arg2); + } + + @Override + public void trace(org.slf4j.Marker marker, String format, Object... argArray) { + delegate.trace(marker, addPrefix(format), argArray); + } + + @Override + public void trace(org.slf4j.Marker marker, String msg, Throwable t) { + delegate.trace(marker, addPrefix(msg), t); + } + + @Override + public boolean isDebugEnabled() { + return delegate.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + delegate.debug(addPrefix(msg)); + } + + @Override + public void debug(String format, Object arg) { + delegate.debug(addPrefix(format), arg); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + delegate.debug(addPrefix(format), arg1, arg2); + } + + @Override + public void debug(String format, Object... arguments) { + delegate.debug(addPrefix(format), arguments); + } + + @Override + public void debug(String msg, Throwable t) { + delegate.debug(addPrefix(msg), t); + } + + @Override + public boolean isDebugEnabled(org.slf4j.Marker marker) { + return delegate.isDebugEnabled(marker); + } + + @Override + public void debug(org.slf4j.Marker marker, String msg) { + delegate.debug(marker, addPrefix(msg)); + } + + @Override + public void debug(org.slf4j.Marker marker, String format, Object arg) { + delegate.debug(marker, addPrefix(format), arg); + } + + @Override + public void debug(org.slf4j.Marker marker, String format, Object arg1, Object arg2) { + delegate.debug(marker, addPrefix(format), arg1, arg2); + } + + @Override + public void debug(org.slf4j.Marker marker, String format, Object... argArray) { + delegate.debug(marker, addPrefix(format), argArray); + } + + @Override + public void debug(org.slf4j.Marker marker, String msg, Throwable t) { + delegate.debug(marker, addPrefix(msg), t); + } + + @Override + public boolean isInfoEnabled() { + return delegate.isInfoEnabled(); + } + + @Override + public void info(String msg) { + delegate.info(addPrefix(msg)); + } + + @Override + public void info(String format, Object arg) { + delegate.info(addPrefix(format), arg); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + delegate.info(addPrefix(format), arg1, arg2); + } + + @Override + public void info(String format, Object... arguments) { + delegate.info(addPrefix(format), arguments); + } + + @Override + public void info(String msg, Throwable t) { + delegate.info(addPrefix(msg), t); + } + + @Override + public boolean isInfoEnabled(org.slf4j.Marker marker) { + return delegate.isInfoEnabled(marker); + } + + @Override + public void info(org.slf4j.Marker marker, String msg) { + delegate.info(marker, addPrefix(msg)); + } + + @Override + public void info(org.slf4j.Marker marker, String format, Object arg) { + delegate.info(marker, addPrefix(format), arg); + } + + @Override + public void info(org.slf4j.Marker marker, String format, Object arg1, Object arg2) { + delegate.info(marker, addPrefix(format), arg1, arg2); + } + + @Override + public void info(org.slf4j.Marker marker, String format, Object... argArray) { + delegate.info(marker, addPrefix(format), argArray); + } + + @Override + public void info(org.slf4j.Marker marker, String msg, Throwable t) { + delegate.info(marker, addPrefix(msg), t); + } + + @Override + public boolean isWarnEnabled() { + return delegate.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + delegate.warn(addPrefix(msg)); + } + + @Override + public void warn(String format, Object arg) { + delegate.warn(addPrefix(format), arg); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + delegate.warn(addPrefix(format), arg1, arg2); + } + + @Override + public void warn(String format, Object... arguments) { + delegate.warn(addPrefix(format), arguments); + } + + @Override + public void warn(String msg, Throwable t) { + delegate.warn(addPrefix(msg), t); + } + + @Override + public boolean isWarnEnabled(org.slf4j.Marker marker) { + return delegate.isWarnEnabled(marker); + } + + @Override + public void warn(org.slf4j.Marker marker, String msg) { + delegate.warn(marker, addPrefix(msg)); + } + + @Override + public void warn(org.slf4j.Marker marker, String format, Object arg) { + delegate.warn(marker, addPrefix(format), arg); + } + + @Override + public void warn(org.slf4j.Marker marker, String format, Object arg1, Object arg2) { + delegate.warn(marker, addPrefix(format), arg1, arg2); + } + + @Override + public void warn(org.slf4j.Marker marker, String format, Object... argArray) { + delegate.warn(marker, addPrefix(format), argArray); + } + + @Override + public void warn(org.slf4j.Marker marker, String msg, Throwable t) { + delegate.warn(marker, addPrefix(msg), t); + } + + @Override + public boolean isErrorEnabled() { + return delegate.isErrorEnabled(); + } + + @Override + public void error(String msg) { + delegate.error(addPrefix(msg)); + } + + @Override + public void error(String format, Object arg) { + delegate.error(addPrefix(format), arg); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + delegate.error(addPrefix(format), arg1, arg2); + } + + @Override + public void error(String format, Object... arguments) { + delegate.error(addPrefix(format), arguments); + } + + @Override + public void error(String msg, Throwable t) { + delegate.error(addPrefix(msg), t); + } + + @Override + public boolean isErrorEnabled(org.slf4j.Marker marker) { + return delegate.isErrorEnabled(marker); + } + + @Override + public void error(org.slf4j.Marker marker, String msg) { + delegate.error(marker, addPrefix(msg)); + } + + @Override + public void error(org.slf4j.Marker marker, String format, Object arg) { + delegate.error(marker, addPrefix(format), arg); + } + + @Override + public void error(org.slf4j.Marker marker, String format, Object arg1, Object arg2) { + delegate.error(marker, addPrefix(format), arg1, arg2); + } + + @Override + public void error(org.slf4j.Marker marker, String format, Object... argArray) { + delegate.error(marker, addPrefix(format), argArray); + } + + @Override + public void error(org.slf4j.Marker marker, String msg, Throwable t) { + delegate.error(marker, addPrefix(msg), t); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/Player.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/Player.java new file mode 100644 index 0000000..26f9800 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/Player.java @@ -0,0 +1,58 @@ +package com.overlord.qualityoflife.classes.controller.util; + +import java.util.UUID; +import net.minecraft.text.Text; +import net.minecraft.server.network.ServerPlayerEntity; + +public class Player +{ + public String name = null; + public Text display = null; + public UUID identifier = null; + + private final ServerPlayerEntity player; + + public static final int PERMISSION_LEVEL_OP = 2; + + public Player(ServerPlayerEntity _player) + { + this.player = _player; + this.name = player.getName().getString(); + this.display = player.getDisplayName() != null ? player.getDisplayName() : Text.of(this.name); + this.identifier = player.getUuid(); + } + + public static Player of(ServerPlayerEntity _player) { + return new Player(_player); + } + + public String getPosition() { + var pos = player.getPos(); + return String.format("%.2f %.2f %.2f", pos.x, pos.y, pos.z); + } + + public String getPosition(String format) { + var pos = player.getPos(); + return String.format(format, pos.x, pos.y, pos.z); + } + + public String getDimension() { + return Dimension.getNormalizedName(player.getWorld().getRegistryKey()); + } + + public String getDimension(Dimension.Type type) { + return Dimension.getNormalizedName(player.getWorld().getRegistryKey(), type); + } + + public void sendMessage(Text message) { + player.sendMessage(message, false); + } + + public void sendMessage(Text message, boolean overlay) { + player.sendMessage(message, overlay); + } + + public int getPing() { + return player.pingMilliseconds; + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/StackTraceUtility.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/StackTraceUtility.java new file mode 100644 index 0000000..07911ff --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/StackTraceUtility.java @@ -0,0 +1,87 @@ +package com.overlord.qualityoflife.classes.controller.util; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.transformer.ClassInfo; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * Based on MixinTrace + */ +public class StackTraceUtility +{ + public static void printTrace(StackTraceElement[] stackTrace, StringBuilder crashReportBuilder) + { + if (stackTrace != null && stackTrace.length > 0) + { + crashReportBuilder.append("\nMixins in Stacktrace:"); + + try + { + List classNames = new ArrayList<>(); + for (StackTraceElement el : stackTrace) + { + if (!classNames.contains(el.getClassName())) + classNames.add(el.getClassName()); + } + + boolean found = false; + for (String className : classNames) + { + ClassInfo classInfo = ClassInfo.fromCache(className); + + if (classInfo != null) + { + Object mixinInfoSetObject; + + try + { + //noinspection JavaReflectionMemberAccess + Method getMixins = ClassInfo.class.getDeclaredMethod("getMixins"); + + getMixins.setAccessible(true); + mixinInfoSetObject = getMixins.invoke(classInfo); + } + catch (Exception e) + { + var mixinsField = ClassInfo.class.getDeclaredField("mixins"); + + mixinsField.setAccessible(true); + mixinInfoSetObject = mixinsField.get(classInfo); + } + + @SuppressWarnings("unchecked") Set mixinInfoSet = (Set) mixinInfoSetObject; + + if (!mixinInfoSet.isEmpty()) + { + crashReportBuilder.append("\n\t"); + crashReportBuilder.append(className); + crashReportBuilder.append(":"); + + for (IMixinInfo info : mixinInfoSet) + { + crashReportBuilder.append("\n\t\t"); + crashReportBuilder.append(info.getClassName()); + crashReportBuilder.append(" ("); + crashReportBuilder.append(info.getConfig().getName()); + crashReportBuilder.append(")"); + } + + found = true; + } + } + } + + if (!found) + crashReportBuilder.append(" None found"); + } + catch (Exception e) + { + crashReportBuilder.append(" Failed to find Mixin metadata: ").append(e); + } + } + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/ColorGradient.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/ColorGradient.java new file mode 100644 index 0000000..5962337 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/ColorGradient.java @@ -0,0 +1,80 @@ +package com.overlord.qualityoflife.classes.controller.util.extension; + +public record ColorGradient(float startHue, float endHue, float saturation, float value) +{ + public ColorGradient(float startHue, float endHue) + { + this(startHue, endHue, 1.0f, 1.0f); + } + + public ColorGradient { + startHue = normalizeHue(startHue); + endHue = normalizeHue(endHue); + saturation = clamp(saturation); + value = clamp(value); + } + + public RgbColor getColor(float ratio) + { + ratio = clamp(ratio); + + float delta = normalizeDelta(endHue - startHue); + float hue = normalizeHue((startHue + delta * ratio)); // Interpolate along shortest arc + + return hsvToRgb(hue, saturation, value); + } + + private static float normalizeHue(float hue) + { + hue %= 360; + + return hue < 0 ? hue + 360 : hue; + } + + private static float normalizeDelta(float delta) + { + // Normalize delta to [-180, 180] range for shortest direction + return delta > 180 + ? delta - 360 + : delta < -180 + ? delta + 360 + : delta; + } + + private static float clamp(float v) { + return Math.max(0f, Math.min(1f, v)); + } + + private static RgbColor hsvToRgb(float h, float s, float v) + { + float c = v * s; + float x = c * (1 - Math.abs((h / 60) % 2 - 1)); + float m = v - c; + + float rPrime = 0, gPrime = 0, bPrime = 0; + + if (h < 60) { rPrime = c; gPrime = x; } + else if (h < 120) { rPrime = x; gPrime = c; } + else if (h < 180) { gPrime = c; bPrime = x; } + else if (h < 240) { gPrime = x; bPrime = c; } + else if (h < 300) { rPrime = x; bPrime = c; } + else { rPrime = c; bPrime = x; } + + int r = Math.round((rPrime + m) * 255); + int g = Math.round((gPrime + m) * 255); + int b = Math.round((bPrime + m) * 255); + + return new RgbColor(r, g, b); + } + + public record RgbColor(int red, int green, int blue) + { + public int toRgbInt() { + return (this.red() << 16) | (this.green() << 8) | this.blue(); + } + + public String toHex() { + return String.format("#%02X%02X%02X", this.red(), this.green(), this.blue()); + } + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/IChatCommandController.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/IChatCommandController.java new file mode 100644 index 0000000..b905564 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/IChatCommandController.java @@ -0,0 +1,17 @@ +package com.overlord.qualityoflife.classes.controller.util.extension; + +import com.mojang.brigadier.Command; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.server.command.ServerCommandSource; +import org.slf4j.Logger; +import com.overlord.qualityoflife.QualityOfLife; + +public interface IChatCommandController +{ + String MOD_ID = QualityOfLife.MOD_ID; + Logger LOGGER = QualityOfLife.LOGGER; + + static void register() {} + private static int execute(CommandContext context) throws CommandSyntaxException { return Command.SINGLE_SUCCESS; } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/INetworkUtility.java b/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/INetworkUtility.java new file mode 100644 index 0000000..ff6c91f --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/controller/util/extension/INetworkUtility.java @@ -0,0 +1,125 @@ +package com.overlord.qualityoflife.classes.controller.util.extension; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.nio.file.Path; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.net.HttpURLConnection; +import java.security.MessageDigest; +import java.io.ByteArrayOutputStream; +import java.nio.file.StandardCopyOption; +import java.nio.charset.StandardCharsets; + +@SuppressWarnings("SameParameterValue") +public abstract class INetworkUtility +{ + protected static final String USER_AGENT = "QoL-AutoUpdater/1.0"; + protected static final String ALGORITHM = "SHA-256"; + protected static final int BUFFER_SIZE = 65536; // 64 KB + + private static HttpURLConnection getConnection(String url) throws IOException { + return getConnection(url, "GET", 5_000, 15_000, null); + } + + private static HttpURLConnection getConnection(String url, int connTimeoutMs, int readTimeoutMs) throws IOException { + return getConnection(url, "GET", connTimeoutMs, readTimeoutMs, null); + } + + private static HttpURLConnection getConnection(String url, int connTimeoutMs, int readTimeoutMs, Map properties) throws IOException { + return getConnection(url, "GET", connTimeoutMs, readTimeoutMs, properties); + } + + private static HttpURLConnection getConnection(String url, String method, int connTimeoutMs, int readTimeoutMs, Map properties) throws IOException + { + HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(); + + connection.setRequestProperty("User-Agent", USER_AGENT); + connection.setInstanceFollowRedirects(true); + connection.setConnectTimeout(connTimeoutMs); + connection.setReadTimeout(readTimeoutMs); + connection.setRequestMethod(method); + + if (properties != null) + { + for (Map.Entry e : properties.entrySet()) + { + if (e.getKey() == null || e.getValue() == null) continue; + + connection.setRequestProperty(e.getKey(), e.getValue()); + } + } + + return connection; + } + + protected static String fetch(String url, int connTimeoutMs, int readTimeoutMs) throws IOException + { + HttpURLConnection conn = getConnection(url, "GET", connTimeoutMs, readTimeoutMs, null); + + int code = conn.getResponseCode(); + + if (code / 100 != 2) + throw new IOException("HTTP " + code + " from " + url); + + try (InputStream in = conn.getInputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream()) + { + int r; + byte[] buf = new byte[BUFFER_SIZE]; + + while ((r = in.read(buf)) != -1) + bout.write(buf, 0, r); + + return bout.toString(StandardCharsets.UTF_8); + } + } + + protected static Path downloadFile(String url, Path out) throws IOException + { + Map properties = new HashMap<>(); + properties.put("Accept", "application/octet-stream, */*"); + properties.put("Connection", "keep-alive"); + + HttpURLConnection conn = getConnection(url, "GET", 5_000, 15_000, properties); + + int code = conn.getResponseCode(); + + if (code / 100 != 2) + throw new IOException("HTTP " + code + " from " + url); + + try (InputStream in = conn.getInputStream()) + { + Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING); + } + finally + { + conn.disconnect(); + } + + return out; + } + + protected static boolean verifySha256(Path file, String expectedHex) throws Exception + { + MessageDigest md = MessageDigest.getInstance(ALGORITHM); + + try (InputStream is = Files.newInputStream(file)) + { + int r; + byte[] buf = new byte[BUFFER_SIZE]; + + while ((r = is.read(buf)) != -1) + md.update(buf, 0, r); + } + + byte[] digest = md.digest(); + StringBuilder sb = new StringBuilder(); + + for (byte b : digest) + sb.append(String.format("%02x", b)); + + return sb.toString().equalsIgnoreCase(expectedHex); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/registry/ModEffects.java b/src/main/java/com/overlord/qualityoflife/classes/registry/ModEffects.java new file mode 100644 index 0000000..8e02874 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/registry/ModEffects.java @@ -0,0 +1,55 @@ +package com.overlord.qualityoflife.classes.registry; + +import net.minecraft.util.Identifier; +import net.minecraft.registry.Registry; +import net.minecraft.registry.Registries; +import com.overlord.qualityoflife.QualityOfLife; +import net.minecraft.entity.effect.StatusEffect; +import net.minecraft.entity.effect.StatusEffectCategory; + +/** + * A tiny invisible marker effect. It does nothing, is registered only so the potion can contain + * something and have a color. The affliction gameplay is handled in AfflictionManager (server JSON). + */ +public class ModEffects +{ + public static StatusEffect BLACK_POISON_MARKER; + public static StatusEffect CURE_BLACK_POISON_MARKER; + + public static final Identifier BLACK_POISON_MARKER_ID = new Identifier(QualityOfLife.MOD_ID, "black_poison_marker"); + public static final Identifier CURE_BLACK_POISON_MARKER_ID = new Identifier(QualityOfLife.MOD_ID, "cure_black_poison_marker"); + + public static void register() + { + BLACK_POISON_MARKER = new SimpleStatusEffect(StatusEffectCategory.HARMFUL, 0x000000); // black + CURE_BLACK_POISON_MARKER = new SimpleStatusEffect(StatusEffectCategory.BENEFICIAL, 0xffffff); // white + + Registry.register(Registries.STATUS_EFFECT, BLACK_POISON_MARKER_ID, BLACK_POISON_MARKER); + Registry.register(Registries.STATUS_EFFECT, CURE_BLACK_POISON_MARKER_ID, CURE_BLACK_POISON_MARKER); + } + + /** + * Simple StatusEffect subclass to work around protected constructor + */ + private static class SimpleStatusEffect extends StatusEffect + { + public SimpleStatusEffect(StatusEffectCategory category, int color) { + super(category, color); + } + + @Override + public boolean isBeneficial() { + return false; + } + + @Override + public boolean isInstant() { + return false; + } + + @Override + public boolean canApplyUpdateEffect(int duration, int amplifier) { + return false; + } + } +} diff --git a/src/main/java/com/overlord/qualityoflife/classes/registry/ModPotions.java b/src/main/java/com/overlord/qualityoflife/classes/registry/ModPotions.java new file mode 100644 index 0000000..7858fe5 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/classes/registry/ModPotions.java @@ -0,0 +1,47 @@ +package com.overlord.qualityoflife.classes.registry; + +import net.minecraft.item.Items; +import net.minecraft.potion.Potion; +import net.minecraft.potion.Potions; +import net.minecraft.util.Identifier; +import net.minecraft.registry.Registry; +import net.minecraft.registry.Registries; +import com.overlord.qualityoflife.QualityOfLife; +import net.minecraft.recipe.BrewingRecipeRegistry; +import net.minecraft.entity.effect.StatusEffectInstance; + +public class ModPotions +{ + public static Potion BLACK_POISON; + public static Potion CURE_POTION; + + public static final Identifier BLACK_POISON_ID = new Identifier(QualityOfLife.MOD_ID, "black_poison"); + public static final Identifier CURE_POTION_ID = new Identifier(QualityOfLife.MOD_ID, "black_poison_cure"); + + public static void register() + { + StatusEffectInstance markerInstance = new StatusEffectInstance( + ModEffects.BLACK_POISON_MARKER, 1, 0, + false, false, false + ); + + StatusEffectInstance cureInstance = new StatusEffectInstance( + ModEffects.CURE_BLACK_POISON_MARKER, 1, 0, + false, false, false + ); + + BLACK_POISON = new Potion(markerInstance); + CURE_POTION = new Potion(cureInstance); + + Registry.register(Registries.POTION, BLACK_POISON_ID, BLACK_POISON); + Registry.register(Registries.POTION, CURE_POTION_ID, CURE_POTION); + + registerBrewing(); + } + + private static void registerBrewing() + { + BrewingRecipeRegistry.registerPotionRecipe(Potions.AWKWARD, Items.POISONOUS_POTATO, BLACK_POISON); + BrewingRecipeRegistry.registerPotionRecipe(Potions.AWKWARD, Items.ENCHANTED_GOLDEN_APPLE, CURE_POTION); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/mixin/affliction/PlayerDeathMixin.java b/src/main/java/com/overlord/qualityoflife/mixin/affliction/PlayerDeathMixin.java new file mode 100644 index 0000000..fe01756 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/mixin/affliction/PlayerDeathMixin.java @@ -0,0 +1,43 @@ +package com.overlord.qualityoflife.mixin.affliction; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +import net.minecraft.text.Text; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +import com.overlord.qualityoflife.classes.affliction.AfflictionManager; + +/** + * Intercepts player death to broadcast custom death message for afflicted players + */ +@Mixin(ServerPlayerEntity.class) +public class PlayerDeathMixin +{ + /** + * Redirect the call to PlayerManager.broadcast(Text, boolean) made from ServerPlayerEntity.onDeath + * Yarn/official mappings for 1.20.1: "Lnet/minecraft/server/PlayerManager;broadcast(Lnet/minecraft/text/Text;Z)V" + */ + @Redirect( + method = "onDeath", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/server/PlayerManager;broadcast(Lnet/minecraft/text/Text;Z)V" + ) + ) + private void redirectBroadcastOnDeath(PlayerManager manager, Text originalMessage, boolean actionBar) + { + ServerPlayerEntity player = (ServerPlayerEntity)(Object)this; + + if (AfflictionManager.instance().isAfflicted(player.getUuid())) + { + String deathMessage = player.getEntityName() + " died due to organ failure."; + manager.broadcast(Text.literal(deathMessage), false); + return; + } + + // Not afflicted: preserve vanilla behaviour + manager.broadcast(originalMessage, actionBar); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/mixin/affliction/PotionFinishMixin.java b/src/main/java/com/overlord/qualityoflife/mixin/affliction/PotionFinishMixin.java new file mode 100644 index 0000000..90c2424 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/mixin/affliction/PotionFinishMixin.java @@ -0,0 +1,39 @@ +package com.overlord.qualityoflife.mixin.affliction; + +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 net.minecraft.world.World; +import net.minecraft.item.ItemStack; +import net.minecraft.item.PotionItem; +import net.minecraft.util.Identifier; +import net.minecraft.potion.PotionUtil; +import net.minecraft.entity.LivingEntity; +import net.minecraft.registry.Registries; +import net.minecraft.entity.player.PlayerEntity; +import com.overlord.qualityoflife.classes.registry.ModPotions; +import com.overlord.qualityoflife.classes.affliction.AfflictionManager; + +/** + * Hooks into PotionItem.finishUsing to handle custom potion effects + * Only triggers when potion drinking is actually finished (not on cancel/slot switch) + */ +@Mixin(PotionItem.class) +public class PotionFinishMixin +{ + @Inject(method = "finishUsing", at = @At("HEAD")) + private void onPotionFinish(ItemStack stack, World world, LivingEntity user, CallbackInfoReturnable cir) + { + if (world.isClient) return; + if (!(user instanceof PlayerEntity player)) return; + + Identifier potionId = Registries.POTION.getId(PotionUtil.getPotion(stack)); + + if (potionId.equals(ModPotions.BLACK_POISON_ID)) + AfflictionManager.instance().applyAffliction(player.getUuid()); + if (potionId.equals(ModPotions.CURE_POTION_ID)) + AfflictionManager.instance().removeAffliction(player.getUuid()); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/mixin/affliction/SplashPotionEntityMixin.java b/src/main/java/com/overlord/qualityoflife/mixin/affliction/SplashPotionEntityMixin.java new file mode 100644 index 0000000..9548a1f --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/mixin/affliction/SplashPotionEntityMixin.java @@ -0,0 +1,64 @@ +package com.overlord.qualityoflife.mixin.affliction; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; + +import net.minecraft.util.math.Box; +import net.minecraft.potion.Potion; +import net.minecraft.item.ItemStack; +import net.minecraft.util.Identifier; +import net.minecraft.potion.PotionUtil; +import net.minecraft.util.hit.HitResult; +import net.minecraft.entity.LivingEntity; +import net.minecraft.server.world.ServerWorld; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.entity.projectile.thrown.PotionEntity; +import com.overlord.qualityoflife.classes.registry.ModPotions; +import com.overlord.qualityoflife.classes.registry.ModEffects; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import com.overlord.qualityoflife.classes.affliction.AfflictionManager; + +/** + * Intercepts potion collision so we can: + */ +@Mixin(PotionEntity.class) +public class SplashPotionEntityMixin +{ + @Inject(method = "onCollision", at = @At("TAIL")) + private void onCollisionHook(HitResult hitResult, CallbackInfo ci) + { + PotionEntity self = (PotionEntity) (Object) this; + if (!(self.getWorld() instanceof ServerWorld serverWorld)) return; + + ItemStack stack = self.getStack(); + Potion potion = PotionUtil.getPotion(stack); + if (potion == null) return; + + Identifier id = net.minecraft.registry.Registries.POTION.getId(potion); + if (id == null) return; + + double x = self.getX(); + double y = self.getY(); + double z = self.getZ(); + Box area = new Box(x - 3.0, y - 3.0, z - 3.0, x + 3.0, y + 3.0, z + 3.0); + + if (id.equals(ModPotions.BLACK_POISON_ID)) + { + for (LivingEntity e : serverWorld.getEntitiesByClass(LivingEntity.class, area, ent -> ent instanceof PlayerEntity)) + { + PlayerEntity p = (PlayerEntity)e; + AfflictionManager.instance().applyAffliction(p.getUuid()); + } + } + else if (id.equals(ModPotions.CURE_POTION_ID)) + { + for (LivingEntity e : serverWorld.getEntitiesByClass(LivingEntity.class, area, ent -> ent instanceof PlayerEntity)) + { + PlayerEntity p = (PlayerEntity)e; + AfflictionManager.instance().removeAffliction(p.getUuid()); + p.removeStatusEffect(ModEffects.BLACK_POISON_MARKER); + } + } + } +} diff --git a/src/main/java/com/overlord/qualityoflife/mixin/ignoring/ChatPacketMixin.java b/src/main/java/com/overlord/qualityoflife/mixin/ignoring/ChatPacketMixin.java new file mode 100644 index 0000000..e1e19c6 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/mixin/ignoring/ChatPacketMixin.java @@ -0,0 +1,38 @@ +package com.overlord.qualityoflife.mixin.ignoring; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.UUID; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.server.network.ServerPlayNetworkHandler; +import net.minecraft.network.packet.s2c.play.ChatMessageS2CPacket; +import com.overlord.qualityoflife.classes.controller.IgnoreCommandController; + +/** + * Intercepts chat messages being sent to players + * Filters messages per-player based on ignore settings + */ +@Mixin(ServerPlayNetworkHandler.class) +public class ChatPacketMixin +{ + @Shadow + public ServerPlayerEntity player; + + @Inject( + method = "sendPacket(Lnet/minecraft/network/packet/Packet;)V", + at = @At("HEAD"), + cancellable = true + ) + private void filterChatPacket(net.minecraft.network.packet.Packet packet, CallbackInfo ci) + { + if (!(packet instanceof ChatMessageS2CPacket chatPacket)) return; + + UUID senderUuid = chatPacket.sender(); + if (senderUuid == null) return; + if (IgnoreCommandController.shouldBlockMessage(senderUuid, player.getUuid())) ci.cancel(); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/mixin/stacktrace/MixinCrashReport.java b/src/main/java/com/overlord/qualityoflife/mixin/stacktrace/MixinCrashReport.java new file mode 100644 index 0000000..456bd73 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/mixin/stacktrace/MixinCrashReport.java @@ -0,0 +1,43 @@ +package com.overlord.qualityoflife.mixin.stacktrace; + +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 net.minecraft.util.crash.CrashReport; +import com.overlord.qualityoflife.classes.controller.util.StackTraceUtility; + +/** + * Based on MixinTrace + */ +@Mixin(value = CrashReport.class) +@SuppressWarnings("MissingOrInvalidOpcode") +public abstract class MixinCrashReport +{ + @Shadow private StackTraceElement[] stackTrace; + + @Inject( + method = "addStackTrace", + at = @At( + value = "FIELD", + target = "Lnet/minecraft/util/crash/CrashReport;otherSections:Ljava/util/List;" + ) + ) + @SuppressWarnings("SpellCheckingInspection") + private void mixinAddTrace(StringBuilder crashReportBuilder, CallbackInfo ci) + { + int trailingNewlineCount = 0; + + if (crashReportBuilder.charAt(crashReportBuilder.length() - 1) == '\n') + { + crashReportBuilder.deleteCharAt(crashReportBuilder.length() - 1); + trailingNewlineCount++; + } + + StackTraceUtility.printTrace(stackTrace, crashReportBuilder); + + crashReportBuilder.append("\n".repeat(trailingNewlineCount)); + } +} diff --git a/src/main/java/com/overlord/qualityoflife/mixin/stacktrace/MixinCrashReportSection.java b/src/main/java/com/overlord/qualityoflife/mixin/stacktrace/MixinCrashReportSection.java new file mode 100644 index 0000000..b649bf0 --- /dev/null +++ b/src/main/java/com/overlord/qualityoflife/mixin/stacktrace/MixinCrashReportSection.java @@ -0,0 +1,21 @@ +package com.overlord.qualityoflife.mixin.stacktrace; + +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 net.minecraft.util.crash.CrashReportSection; +import com.overlord.qualityoflife.classes.controller.util.StackTraceUtility; + +@Mixin(value = CrashReportSection.class) +public abstract class MixinCrashReportSection +{ + @Shadow private StackTraceElement[] stackTrace; + + @Inject(method = "addStackTrace", at = @At("TAIL")) + private void mixinAddTrace(StringBuilder crashReportBuilder, CallbackInfo ci) { + StackTraceUtility.printTrace(stackTrace, crashReportBuilder); + } +} diff --git a/src/main/resources/assets/quality-of-life/icon.png b/src/main/resources/assets/quality-of-life/icon.png new file mode 100644 index 0000000..2b87e83 Binary files /dev/null and b/src/main/resources/assets/quality-of-life/icon.png differ diff --git a/src/main/resources/assets/quality-of-life/lang/en_us.json b/src/main/resources/assets/quality-of-life/lang/en_us.json new file mode 100644 index 0000000..a597688 --- /dev/null +++ b/src/main/resources/assets/quality-of-life/lang/en_us.json @@ -0,0 +1,15 @@ +{ + "item.quality-of-life.splash_black_poison_potion": "Nerve Agent", + "item.quality-of-life.black_poison_potion": "Nerve Agent", + + "item.minecraft.splash_potion.effect.black_poison": "Nerve Agent", + "item.minecraft.potion.effect.black_poison": "Nerve Agent", + + "effect.quality-of-life.black_poison_marker": "Nerve Agent", + "effect.quality-of-life.cure_black_poison_marker": "Antidote", + + "item.quality-of-life.black_poison_cure_potion": "Antidote Treatment Nerve Agent", + "item.quality-of-life.splash_black_poison_cure_potion": "Antidote Treatment Nerve Agent Autoinjector", + "item.minecraft.potion.effect.black_poison_cure": "Antidote Treatment Nerve Agent", + "item.minecraft.splash_potion.effect.black_poison_cure": "Antidote Treatment Nerve Agent Autoinjector" +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..981c937 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,41 @@ +{ + "schemaVersion": 1, + "id": "homestead-relay", + "version": "${version}", + "name": "Quality of Life", + "description": "Very cool mod fr fr 100%", + "authors": [ + "Overlord_303" + ], + "contact": { + "homepage": "https://fabricmc.net/", + "sources": "https://github.com/FabricMC/fabric-example-mod" + }, + "license": "CC0-1.0", + "icon": "assets/quality-of-life/icon.png", + "environment": "*", + "entrypoints": { + "main": [ + "com.overlord.qualityoflife.QualityOfLife" + ], + "client": [ + "com.overlord.qualityoflife.QualityOfLifeClient" + ] + }, + "mixins": [ + "quality-of-life.mixins.json", + { + "config": "quality-of-life.client.mixins.json", + "environment": "client" + } + ], + "depends": { + "fabricloader": ">=0.17.2", + "minecraft": "~1.20.1", + "java": ">=17", + "fabric-api": "*" + }, + "suggests": { + "another-mod": "*" + } +} \ No newline at end of file diff --git a/src/main/resources/quality-of-life.mixins.json b/src/main/resources/quality-of-life.mixins.json new file mode 100644 index 0000000..ab82616 --- /dev/null +++ b/src/main/resources/quality-of-life.mixins.json @@ -0,0 +1,19 @@ +{ + "required": true, + "package": "com.overlord.qualityoflife.mixin", + "compatibilityLevel": "JAVA_17", + "mixins": [ + "affliction.PlayerDeathMixin", + "affliction.PotionFinishMixin", + "affliction.SplashPotionEntityMixin", + "ignoring.ChatPacketMixin", + "stacktrace.MixinCrashReport", + "stacktrace.MixinCrashReportSection" + ], + "injectors": { + "defaultRequire": 1 + }, + "overwrites": { + "requireAnnotations": true + } +}