diff --git a/nounusedchunks-forge-1.19.3/.gitattributes b/nounusedchunks-forge-1.19.3/.gitattributes new file mode 100644 index 0000000..f811f6a --- /dev/null +++ b/nounusedchunks-forge-1.19.3/.gitattributes @@ -0,0 +1,5 @@ +# Disable autocrlf on generated files, they always generate with LF +# Add any extra files or paths here to make git stop saying they +# are changed when only line endings change. +src/generated/**/.cache/cache text eol=lf +src/generated/**/*.json text eol=lf diff --git a/nounusedchunks-forge-1.19.3/.gitignore b/nounusedchunks-forge-1.19.3/.gitignore new file mode 100644 index 0000000..12f8644 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/.gitignore @@ -0,0 +1,25 @@ +# eclipse +bin +*.launch +.settings +.metadata +.classpath +.project + +# idea +out +*.ipr +*.iws +*.iml +.idea + +# gradle +build +.gradle + +# other +eclipse +run + +# Files from Forge MDK +forge*changelog.txt diff --git a/nounusedchunks-forge-1.19.3/build.gradle b/nounusedchunks-forge-1.19.3/build.gradle new file mode 100644 index 0000000..571d6fb --- /dev/null +++ b/nounusedchunks-forge-1.19.3/build.gradle @@ -0,0 +1,228 @@ +buildscript { + repositories { + // These repositories are only for Gradle plugins, put any other repositories in the repository block further below + maven { url = 'https://maven.minecraftforge.net' } + mavenCentral() + maven { url = 'https://repo.spongepowered.org/repository/maven-public/' } + maven { url "https://maven.shedaniel.me/" } + } + dependencies { + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true + classpath group: 'org.spongepowered', name: 'mixingradle', version: '0.7-SNAPSHOT' + } +} +// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup. +plugins { + id 'eclipse' + id 'maven-publish' +} +apply plugin: 'net.minecraftforge.gradle' +apply plugin: 'org.spongepowered.mixin' + +// Include resources generated by data generators. +//sourceSets.main.resources { srcDir 'src/generated/resources' } +sourceSets { + main { + resources { srcDir 'src/generated/resources' } + ext.refMap = "mixins.nounusedchunks.refmap.json" + } +} + +mixin +{ + add sourceSets.main, 'mixins.nounusedchunks.refmap.json' + config 'nounusedchunks.mixins.json' + config 'nounusedchunks.client.mixins.json' +} + + +version = '1.4' +group = 'thecsdev' // http://maven.apache.org/guides/mini/guide-naming-conventions.html +archivesBaseName = 'nounusedchunks' + +// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. +java.toolchain.languageVersion = JavaLanguageVersion.of(17) + +println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" +minecraft { + // The mappings can be changed at any time and must be in the following format. + // Channel: Version: + // official MCVersion Official field/method names from Mojang mapping files + // parchment YYYY.MM.DD-MCVersion Open community-sourced parameter names and javadocs layered on top of official + // + // You must be aware of the Mojang license when using the 'official' or 'parchment' mappings. + // See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md + // + // Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge + // Additional setup is needed to use their mappings: https://github.com/ParchmentMC/Parchment/wiki/Getting-Started + // + // Use non-default mappings at your own risk. They may not always work. + // Simply re-run your setup task after changing the mappings to update your workspace. + mappings channel: 'official', version: '1.19.3' + + // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Currently, this location cannot be changed from the default. + + // Default run configurations. + // These can be tweaked, removed, or duplicated as needed. + runs { + client { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + property 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + property 'forge.logging.console.level', 'debug' + + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', 'examplemod' + + mods { + nounusedchunks { + source sourceSets.main + } + } + } + + server { + workingDirectory project.file('run') + + property 'forge.logging.markers', 'REGISTRIES' + + property 'forge.logging.console.level', 'debug' + + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', 'examplemod' + + mods { + nounusedchunks { + source sourceSets.main + } + } + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + property 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + property 'forge.logging.console.level', 'debug' + + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', 'examplemod' + + mods { + nounusedchunks { + source sourceSets.main + } + } + } + + data { + workingDirectory project.file('run') + + property 'forge.logging.markers', 'REGISTRIES' + + property 'forge.logging.console.level', 'debug' + + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') + + mods { + nounusedchunks { + source sourceSets.main + } + } + } + } +} + +// Include resources generated by data generators. +sourceSets.main.resources { srcDir 'src/generated/resources' } + +repositories { + // Put repositories for dependencies here + // ForgeGradle automatically adds the Forge maven and Maven Central for you + + // If you have mod jar dependencies in ./libs, you can declare them as a repository like so: + // flatDir { + // dir 'libs' + // } +} + +dependencies { + // Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed + // that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied. + // The userdev artifact is a special name and will get all sorts of transformations applied to it. + minecraft 'net.minecraftforge:forge:1.19.3-44.1.0' + + // Apply Mixin AP + annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' + + // Real mod deobf dependency examples - these get remapped to your current mappings + // compileOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}:api") // Adds JEI API as a compile dependency + // runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency + // implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency + + // Examples using mod jars from ./libs + // implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}") + + // For more info... + // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html + // http://www.gradle.org/docs/current/userguide/dependency_management.html +} + +// Example for how to get properties into the manifest for reading at runtime. +jar { + manifest { + attributes([ + "Specification-Title" : "examplemod", + "Specification-Vendor" : "examplemodsareus", + "Specification-Version" : "1", // We are version 1 of ourselves + "Implementation-Title" : project.name, + "Implementation-Version" : project.jar.archiveVersion, + "Implementation-Vendor" : "examplemodsareus", + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } +} + +// Example configuration to allow publishing using the maven-publish plugin +// This is the preferred method to reobfuscate your jar file +jar.finalizedBy('reobfJar') +// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing +// publish.dependsOn('reobfJar') + +publishing { + publications { + mavenJava(MavenPublication) { + artifact jar + } + } + repositories { + maven { + url "file://${project.projectDir}/mcmodsrepo" + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation +} diff --git a/nounusedchunks-forge-1.19.3/gradle.properties b/nounusedchunks-forge-1.19.3/gradle.properties new file mode 100644 index 0000000..878bf1f --- /dev/null +++ b/nounusedchunks-forge-1.19.3/gradle.properties @@ -0,0 +1,4 @@ +# Sets default memory used for gradle commands. Can be overridden by user or command line properties. +# This is required to provide enough memory for the Minecraft decompilation process. +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/gradle/wrapper/gradle-wrapper.jar b/nounusedchunks-forge-1.19.3/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/nounusedchunks-forge-1.19.3/gradle/wrapper/gradle-wrapper.jar differ diff --git a/nounusedchunks-forge-1.19.3/gradle/wrapper/gradle-wrapper.properties b/nounusedchunks-forge-1.19.3/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..41dfb87 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/nounusedchunks-forge-1.19.3/gradlew b/nounusedchunks-forge-1.19.3/gradlew new file mode 100644 index 0000000..c53aefa --- /dev/null +++ b/nounusedchunks-forge-1.19.3/gradlew @@ -0,0 +1,234 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# 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 \ + "$@" + +# 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/nounusedchunks-forge-1.19.3/gradlew.bat b/nounusedchunks-forge-1.19.3/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/NoUnusedChunks.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/NoUnusedChunks.java new file mode 100644 index 0000000..2b0e880 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/NoUnusedChunks.java @@ -0,0 +1,104 @@ +package thecsdev.nounusedchunks; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.minecraft.CrashReport; +import net.minecraft.ReportedException; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.loading.FMLEnvironment; +import thecsdev.nounusedchunks.client.NoUnusedChunksClient; +import thecsdev.nounusedchunks.config.NUCConfig; +import thecsdev.nounusedchunks.server.NoUnusedChunksServer; + +@Mod(NoUnusedChunks.ModID) +public class NoUnusedChunks +{ + // ================================================== + private static NoUnusedChunks Instance; + // -------------------------------------------------- + public static final Logger LOGGER = LoggerFactory.getLogger(getModID()); + // -------------------------------------------------- + public static final String ModName = "No Unused Chunks"; + public static final String ModID = "nounusedchunks"; + // ================================================== + public NoUnusedChunks() + { + //validate instance + if(validateInstance()) + crash("Attempting to initialize " + ModID, new RuntimeException(ModID + " has already been initialized.")); + + //on initialize + if(getClass().equals(NoUnusedChunks.class)) //check if not a subclass + { + //depending on the side, initialize NoUnusedChunks + if(FMLEnvironment.dist.isClient()) + new NoUnusedChunksClient(); + else if(FMLEnvironment.dist.isDedicatedServer()) + new NoUnusedChunksServer(); + else + crash("Attempting to initialize " + ModID, new RuntimeException("Invalid FMLEnvironment.dist()")); + + //do not proceed, return + return; + } + + //assign instance + Instance = this; + + //log stuff + LOGGER.info("Initializing '" + getModName() + "' as '" + getClass().getSimpleName() + "'."); + + //load config + NUCConfig.loadProperties(); + + //register this class as event listener + MinecraftForge.EVENT_BUS.register(this); + } + // -------------------------------------------------- + /** + * Returns true if the {@link #Instance} is valid. This + * should always return true. If it doesn't, the mod + * probably hasn't been initialized yet. + */ + public static boolean validateInstance() + { + if(Instance != null && (Instance instanceof NoUnusedChunksClient || Instance instanceof NoUnusedChunksServer)) + return true; + else return false; + } + // -------------------------------------------------- + /** + * Throws a {@link ReportedException} using a + * {@link CrashReport}. + */ + public static void crash(String crashMessage, Throwable exception) + { + CrashReport crashReport = CrashReport.forThrowable(exception, crashMessage); + throw new ReportedException(crashReport); + } + // ================================================== + public static String getModName() { return ModName; } + public static String getModID() { return ModID; } + public static NoUnusedChunks getInstance() { return Instance; } + // ================================================== + public static Component tt(String key) { return Component.translatable(key); } + public static Component lt(String text) { return Component.literal(text); } + // ================================================== + /** + * Returns true if a chunk is unused. + * (well, it's supposed to. idk) + */ + public static boolean isChunkUnused(ResourceKey worldRegKey, ChunkPos chunkPos, CompoundTag chunkNbt) + { + return chunkNbt.contains("InhabitedTime") && + chunkNbt.getLong("InhabitedTime") == 0; + } + // ================================================== +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/NoUnusedChunksClient.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/NoUnusedChunksClient.java new file mode 100644 index 0000000..927ed90 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/NoUnusedChunksClient.java @@ -0,0 +1,10 @@ +package thecsdev.nounusedchunks.client; + +import net.minecraft.client.Minecraft; +import thecsdev.nounusedchunks.NoUnusedChunks; + +public class NoUnusedChunksClient extends NoUnusedChunks +{ + public static Minecraft MCClient; + public NoUnusedChunksClient() { MCClient = Minecraft.getInstance(); } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/screen/NUCConfigScreen.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/screen/NUCConfigScreen.java new file mode 100644 index 0000000..a136a83 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/screen/NUCConfigScreen.java @@ -0,0 +1,108 @@ +package thecsdev.nounusedchunks.client.gui.screen; + +import static thecsdev.nounusedchunks.NoUnusedChunks.lt; +import static thecsdev.nounusedchunks.NoUnusedChunks.tt; + +import java.awt.Color; + +import org.jetbrains.annotations.Nullable; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraftforge.client.gui.ModListScreen; +import thecsdev.nounusedchunks.NoUnusedChunks; +import thecsdev.nounusedchunks.client.gui.widgets.StringWidget; +import thecsdev.nounusedchunks.client.gui.widgets.UnflagChanceSliderWidget; +import thecsdev.nounusedchunks.config.NUCConfig; + +public class NUCConfigScreen extends Screen +{ + // ================================================== + public static final int BG_COLOR = new Color(0, 0, 0, 120).getRGB(); + public static final int OL_COLOR = new Color(255, 255, 255, 50).getRGB(); + // -------------------------------------------------- + public final ModListScreen parent; + private Button btn_enabled; + private UnflagChanceSliderWidget slider_ufc; + private Button btn_done; + // -------------------------------------------------- + private int x1, y1, x2, y2, y3; + // ================================================== + public NUCConfigScreen(ModListScreen parent) + { + super(NoUnusedChunks.tt("nounusedchunks.config.title")); + this.parent = parent; + } + // -------------------------------------------------- + @Nullable public Button getBtnEnabled() { return btn_enabled; } + @Nullable public Button getBtnDone() { return btn_done; } + @Nullable public UnflagChanceSliderWidget getSliderUfc() { return slider_ufc; } + // -------------------------------------------------- + @Override + public void onClose() + { + this.minecraft.setScreen(parent); + NUCConfig.saveProperties(); + } + // ================================================== + @Override + protected void init() + { + //super + super.init(); + + //calculate bg coordinates + this.x1 = 10; + this.y1 = 10; + this.x2 = this.width - 10; + this.y2 = this.height - 45; + this.y3 = this.height - 40; + + //category + this.addRenderableWidget(new StringWidget(this.width / 2, y1 + 15, tt("nounusedchunks.config.general"), font) + .setCentered()); + + //enabled + this.addRenderableWidget(new StringWidget(x1 + 10, y1 + 30, tt("nounusedchunks.config.general.enabled"), font) + .setTooltip(tt("nounusedchunks.config.general.enabled.tooltip"))); + this.addRenderableWidget(btn_enabled = Button.builder(lt(Boolean.toString(NUCConfig.ENABLED)), arg0 -> + { + NUCConfig.ENABLED = !NUCConfig.ENABLED; + arg0.setMessage(lt(Boolean.toString(NUCConfig.ENABLED))); + }) + .bounds(x2 - 160, y1 + 25, 150, 20) + .build() + ); + + //un-flag chance + this.addRenderableWidget(new StringWidget(x1 + 10, y1 + 55, tt("nounusedchunks.config.general.unflag_chance"), font) + .setTooltip(tt("nounusedchunks.config.general.unflag_chance.tooltip"))); + this.addRenderableWidget(slider_ufc = new UnflagChanceSliderWidget(btn_enabled.getX(), btn_enabled.getY() + 25, btn_enabled.getWidth(), 20)); + + //done + this.addRenderableWidget(btn_done = Button.builder(tt("gui.done"), arg0 -> onClose()).bounds((this.width / 2) - 75, y3 + 5, 150, 20).build()); + } + // -------------------------------------------------- + @Override + public void render(PoseStack matrices, int mouseX, int mouseY, float delta) + { + //background rendering + renderBackground(matrices); + fill(matrices, x1 - 1, y1 - 1, x2 + 1, y2 + 1, OL_COLOR); + fill(matrices, x1, y1, x2, y2, BG_COLOR); + //fill(matrices, x1, y3, x2, y4, BG_COLOR); + + //widget rendering + super.render(matrices, mouseX, mouseY, delta); + + //draw tooltips + this.children().forEach(child -> + { + if(child instanceof StringWidget && child.isMouseOver(mouseX, mouseY)) + ((StringWidget)child).renderToolTip(matrices, mouseX, mouseY); + }); + } + // ================================================== +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/util/GuiUtils.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/util/GuiUtils.java new file mode 100644 index 0000000..ae34ecc --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/util/GuiUtils.java @@ -0,0 +1,78 @@ +package thecsdev.nounusedchunks.client.gui.util; + +import static net.minecraft.client.gui.GuiComponent.drawString; +import static net.minecraft.client.gui.GuiComponent.fill; +import static thecsdev.nounusedchunks.NoUnusedChunks.lt; + +import java.awt.Color; +import java.awt.Dimension; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.network.chat.Component; +import thecsdev.nounusedchunks.client.NoUnusedChunksClient; + +public class GuiUtils +{ + // -------------------------------------------------- + public static final int COLOR_BLACK = Color.black.getRGB(); + public static final int COLOR_WHITE = Color.white.getRGB(); + public static final int COLOR_TOOLTIP_OUTLINE = new Color(27,0,62).getRGB(); + public static final int COLOR_TOOLTIP_BGROUND = new Color(15,0,15).getRGB(); + // -------------------------------------------------- + public static void drawTooltip(PoseStack matrices, int mouseX, int mouseY, Component text) + { + Minecraft MC = NoUnusedChunksClient.MCClient; + Font tr = MC.font; + + matrices.pushPose(); + matrices.translate(0, 0, 100); + + //get text size so we can know how big the tooltip will be + Dimension textSize = getTextSize(tr, text); + textSize = new Dimension(textSize.width + 10, textSize.height + 10); + + //offset the X for the tooltip + mouseX += 5; + if(MC.screen != null) + { + int aX = mouseX + textSize.width; + if(aX > MC.screen.width) + mouseX -= (textSize.width + 5); + } + + //fill in a tooltip square background + fill(matrices, mouseX, mouseY, mouseX + textSize.width, mouseY + textSize.height, COLOR_TOOLTIP_OUTLINE); + fill(matrices, mouseX + 2, mouseY + 2, mouseX + textSize.width - 2, mouseY + textSize.height - 2, COLOR_TOOLTIP_BGROUND); + + //draw text + String textStr = text.getString(); + String[] lines = textStr.split("(\\r?\\n)|(\\\\n)"); + + int lineY = 0; + for (String line : lines) + { + drawString(matrices, tr, lt(line), mouseX + 5, mouseY + 5 + lineY, COLOR_WHITE); + lineY += tr.wordWrapHeight(line, textSize.width); + } + + matrices.popPose(); + } + // -------------------------------------------------- + public static Dimension getTextSize(Font tr, Component text) + { + String textStr = text.getString(); + String[] lines = textStr.split("(\\r?\\n)|(\\\\n)"); + int maxWidth = 0; + for (String line : lines) + { + int lineWidth = tr.width(line); + if(lineWidth > maxWidth) + maxWidth = lineWidth; + } + return new Dimension(maxWidth, tr.wordWrapHeight(textStr, maxWidth)); + } + // -------------------------------------------------- +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/ActionCheckboxWidget.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/ActionCheckboxWidget.java new file mode 100644 index 0000000..f6a001c --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/ActionCheckboxWidget.java @@ -0,0 +1,45 @@ +package thecsdev.nounusedchunks.client.gui.widgets; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.Checkbox; +import net.minecraft.network.chat.Component; +import thecsdev.nounusedchunks.client.gui.util.GuiUtils; + +public class ActionCheckboxWidget extends Checkbox +{ + // -------------------------------------------------- + public interface ACCallback { public void onPress(ActionCheckboxWidget checkbox); } + public final ACCallback callback; + public final Font tr; + public Component tooltip; + // -------------------------------------------------- + @SuppressWarnings("resource") + public ActionCheckboxWidget(int x, int y, int width, int height, Component message, boolean checked, boolean showMessage, ACCallback callback) + { + super(x, y, width, height, message, checked, showMessage); + this.callback = callback; + this.tr = Minecraft.getInstance().font; + } + + public void setTooltip(Component text) { this.tooltip = text; } + // -------------------------------------------------- + @Override + public void onPress() + { + super.onPress(); + if(callback != null) + callback.onPress(this); + } + + @Override + public void render(PoseStack matrices, int mouseX, int mouseY, float delta) + { + super.render(matrices, mouseX, mouseY, delta); + if(this.isHovered) + GuiUtils.drawTooltip(matrices, mouseX, mouseY, tooltip); + } + // -------------------------------------------------- +} diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/StringWidget.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/StringWidget.java new file mode 100644 index 0000000..2dd96b9 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/StringWidget.java @@ -0,0 +1,48 @@ +package thecsdev.nounusedchunks.client.gui.widgets; + +import com.mojang.blaze3d.vertex.PoseStack; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.AbstractWidget; +import net.minecraft.client.gui.narration.NarratedElementType; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.network.chat.Component; +import thecsdev.nounusedchunks.client.gui.util.GuiUtils; + +public class StringWidget extends AbstractWidget +{ + // ================================================== + public final Font font; + public boolean isCentered = false; + public int color = -1; + public Component tooltip; + // -------------------------------------------------- + public StringWidget(int x, int y, Component text, Font font) + { + super(x, y - (font.lineHeight / 2), font.width(text.getString()), font.lineHeight, text); + this.font = font; + } + public StringWidget setCentered() { isCentered = true; return this; } + public StringWidget setColored(int color) { this.color = color; return this; } + public StringWidget setTooltip(Component tooltip) { this.tooltip = tooltip; return this; } + // ================================================== + protected @Override void updateWidgetNarration(NarrationElementOutput neo) { neo.add(NarratedElementType.TITLE, getMessage()); } + protected @Override boolean clicked(double p_93681_, double p_93682_) { return false; } + // -------------------------------------------------- + public void renderToolTip(PoseStack matrices, int mouseX, int mouseY) + { + if(isHovered && tooltip != null) + GuiUtils.drawTooltip(matrices, mouseX, mouseY, tooltip); + } + // -------------------------------------------------- + @Override + public void render(PoseStack matrices, int mouseX, int mouseY, float delta) + { + int x = getX(), y = getY(); + this.isHovered = mouseX >= x && mouseY >= y && mouseX < x + this.width && mouseY < y + this.height; + + if(!isCentered) drawString(matrices, font, getMessage(), x, y, color); + else drawCenteredString(matrices, font, getMessage(), x, y, color); + } + // ================================================== +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/UnflagChanceSliderWidget.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/UnflagChanceSliderWidget.java new file mode 100644 index 0000000..9bfa588 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/gui/widgets/UnflagChanceSliderWidget.java @@ -0,0 +1,21 @@ +package thecsdev.nounusedchunks.client.gui.widgets; + +import static thecsdev.nounusedchunks.NoUnusedChunks.lt; + +import net.minecraft.client.gui.components.AbstractSliderButton; +import thecsdev.nounusedchunks.config.NUCConfig; + +public class UnflagChanceSliderWidget extends AbstractSliderButton +{ + public UnflagChanceSliderWidget(int x, int y, int w, int h) + { + super(x, y, w, h, lt("N/A"), (float)NUCConfig.UNFLAG_CHANCE / 100); + updateMessage(); + } + + @Override protected void updateMessage() { setMessage(lt(valInt() + "%")); } + @Override protected void applyValue() { NUCConfig.UNFLAG_CHANCE = valInt(); } + + private int valInt() { return clamp((int) (this.value * 100), 0, 100); } + private static int clamp(int i, int min, int max) { return Math.max(Math.min(i, max), 0); } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/mixin/BackupConfirmScreenMixin.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/mixin/BackupConfirmScreenMixin.java new file mode 100644 index 0000000..e13a2c4 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/mixin/BackupConfirmScreenMixin.java @@ -0,0 +1,89 @@ +package thecsdev.nounusedchunks.client.mixin; + +import static thecsdev.nounusedchunks.NoUnusedChunks.tt; +import static thecsdev.nounusedchunks.config.NUCConfig.OW_RUC; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; +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.client.gui.components.AbstractButton; +import net.minecraft.client.gui.components.Checkbox; +import net.minecraft.client.gui.screens.BackupConfirmScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import thecsdev.nounusedchunks.client.gui.widgets.ActionCheckboxWidget; + +@Mixin(BackupConfirmScreen.class) +public abstract class BackupConfirmScreenMixin extends Screen +{ + // ================================================== + public BackupConfirmScreenMixin(Component title) { super(title); } + // ================================================== + public ActionCheckboxWidget nuc_removeUnusedChunksCheckbox; + //public ActionCheckboxWidget nuc_removeLightCacheCheckbox; -- Obsolete as of forge-1.19.x + // -------------------------------------------------- + @Accessor("promptForCacheErase") + public abstract boolean getPromptForCacheErase(); + + @Accessor("eraseCache") + public abstract Checkbox getEraseCache(); + + @Accessor("listener") + public abstract BackupConfirmScreen.Listener getListener(); + // ================================================== + @Inject(method = "init", at = @At("TAIL")) + public void init(CallbackInfo callback) + { + //define the check-box + int i = getEraseCache().getY(), j = getEraseCache().getHeight() + 5; + + /*nuc_removeLightCacheCheckbox = new ActionCheckboxWidget( + this.width / 2 - 155 + 80, i + j, + 150, 20, + tt("nounusedchunks.backupprompt.removelightcache"), false, true, + checkbox -> {}); + nuc_removeLightCacheCheckbox.setTooltip(tt("nounusedchunks.backupprompt.removelightcache.tooltip")); + nuc_removeLightCacheCheckbox.active = false;*/ + + nuc_removeUnusedChunksCheckbox = new ActionCheckboxWidget( + this.width / 2 - 155 + 80, i + j, + 150, 20, + tt("nounusedchunks.backupprompt.removeuninhabitedchunks"), OW_RUC, true, + checkbox -> OW_RUC = checkbox.selected()); + nuc_removeUnusedChunksCheckbox.setTooltip(tt("nounusedchunks.backupprompt.removeuninhabitedchunks.tooltip")); + + //if the game is showing the check-boxes, add the check-box below the + //vanilla one, and move the buttons down + if(getPromptForCacheErase()) + { + //add the check-box + addRenderableWidget(nuc_removeUnusedChunksCheckbox); + //addRenderableWidget(nuc_removeLightCacheCheckbox); + + //move the stuff such as buttons and other UI elements below it a little bit down + this.children().forEach(drawable -> + { + //ignore non-clickables, + //ignore the removeUnusedChunks checkbox + if(!(drawable instanceof AbstractButton) || + drawable == nuc_removeUnusedChunksCheckbox /*|| drawable == nuc_removeLightCacheCheckbox*/) + return; + AbstractButton cw = (AbstractButton)drawable; + + //ignore above ones + if(cw.getY() < nuc_removeUnusedChunksCheckbox.getY() - 5) + return; + + //move a bit down + cw.setY(cw.getY() + j + 10); + }); + } + + //now position the other checkbox (edit: not anymore) + //nuc_removeUnusedChunksCheckbox.y = nuc_removeLightCacheCheckbox.y + nuc_removeLightCacheCheckbox.getHeight() + 5; + } + // ================================================== +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/mixin/ModListScreenMixin.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/mixin/ModListScreenMixin.java new file mode 100644 index 0000000..89542b3 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/client/mixin/ModListScreenMixin.java @@ -0,0 +1,45 @@ +package thecsdev.nounusedchunks.client.mixin; + +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.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraftforge.client.gui.ModListScreen; +import net.minecraftforge.client.gui.widget.ModListWidget; +import thecsdev.nounusedchunks.NoUnusedChunks; +import thecsdev.nounusedchunks.client.gui.screen.NUCConfigScreen; + +@Mixin(ModListScreen.class) +public abstract class ModListScreenMixin extends Screen +{ + protected ModListScreenMixin(Component p_96550_) { super(p_96550_); } + + @Shadow public ModListWidget.ModEntry selected; + @Shadow public Button configButton; + + @Inject(method = "displayModConfig", at = @At("HEAD"), cancellable = true, remap = false) + public void onDisplayModConfig(CallbackInfo callback) + { + //check if selection is this mod + if (selected == null || + !selected.getInfo().getModId().equals(NoUnusedChunks.ModID)) + return; + + //open screen + Minecraft.getInstance().setScreen(new NUCConfigScreen((ModListScreen)(Object)this)); + callback.cancel(); + } + + @Inject(method = "updateCache", at = @At("RETURN"), remap = false) + public void onUpdateCache(CallbackInfo callback) + { + if(this.selected != null && this.selected.getInfo().getModId().equals(NoUnusedChunks.ModID)) + this.configButton.active = true; + } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/config/NUCConfig.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/config/NUCConfig.java new file mode 100644 index 0000000..82fb576 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/config/NUCConfig.java @@ -0,0 +1,109 @@ +package thecsdev.nounusedchunks.config; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Properties; + +import thecsdev.nounusedchunks.NoUnusedChunks; + +public final class NUCConfig +{ + // ================================================== + public static boolean ENABLED = true; + public static int UNFLAG_CHANCE = 100; + // -------------------------------------------------- TEMP. VALUES: + public static boolean OW_RUC = false; //remove unused chunks + // ================================================== + public static void saveProperties() + { + try + { + //get and make sure the properties file exists + File fProp = getPropertiesFile(); + if(!fProp.exists()) + { + fProp.getParentFile().mkdirs(); + fProp.createNewFile(); + } + + //create a Properties instance and store the properties + Properties prop = new Properties(); + prop.setProperty("ENABLED", Boolean.toString(ENABLED)); + prop.setProperty("UNFLAG_CHANCE", Integer.toString(UNFLAG_CHANCE)); + + //save the properties + FileOutputStream fos = new FileOutputStream(fProp); + prop.store(fos, NoUnusedChunks.ModID + " properties"); + fos.close(); + + //log + NoUnusedChunks.LOGGER.info("Saved '" + NoUnusedChunks.ModID + "' config."); + } + catch(IOException ioExc) + { + //if saving is unsuccessful, throw a CrashException + NoUnusedChunks.crash("Unable to save the '" + NoUnusedChunks.ModID + "' mod config.", ioExc); + } + } + // -------------------------------------------------- + public static void loadProperties() + { + try + { + //get and make sure the properties file exists + File fProp = getPropertiesFile(); + if(!fProp.exists()) + { + NoUnusedChunks.LOGGER.info("Could not load '" + NoUnusedChunks.ModID + "' config. File not found."); + return; + } + + //create a Properties instance and load the properties + Properties prop = new Properties(); + FileInputStream fis = new FileInputStream(fProp); + prop.load(fis); + fis.close(); + + //read the properties + ENABLED = smartBool(prop.getProperty("ENABLED"), true); + UNFLAG_CHANCE = smartInt(prop.getProperty("UNFLAG_CHANCE"), 1, 100, 100); + + //log + NoUnusedChunks.LOGGER.info("Loaded '" + NoUnusedChunks.ModID + "' config."); + } + catch(IOException ioExc) + { + //if loading is unsuccessful, throw a CrashException + NoUnusedChunks.crash("Unable to load the '" + NoUnusedChunks.ModID + "' mod config.", ioExc); + } + } + // ================================================== + /** + * Returns the {@link File} where the + * {@link #PROPERTIES} should be stored. + */ + public static File getPropertiesFile() + { + return new File(System.getProperty("user.dir") + "/config/" + NoUnusedChunks.ModID + ".properties"); + } + // ================================================== + //private static boolean smartBool(String arg0) { return smartBool(arg0, true); } + private static boolean smartBool(String arg0, boolean def) + { + if(arg0 == null) return def; + String a = arg0.split(" ")[0].toLowerCase(); + return (a.startsWith("true") || a.startsWith("ye") || + a.startsWith("ok") || a.startsWith("sur")) && a.length() <= 5; + } + + private static int smartInt(String arg0, int min, int max, int def) + { + try { return clamp(Integer.parseInt(arg0), min, max); } + catch(Exception e) { return clamp(def, min, max); } + } + + private static int clamp(int in, int min, int max) { return Math.max(min, Math.min(max, in)); } + // ================================================== +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/mixin/ChunkStatusMixin.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/mixin/ChunkStatusMixin.java new file mode 100644 index 0000000..1a37081 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/mixin/ChunkStatusMixin.java @@ -0,0 +1,68 @@ +package thecsdev.nounusedchunks.mixin; + +import static thecsdev.nounusedchunks.config.NUCConfig.ENABLED; +import static thecsdev.nounusedchunks.config.NUCConfig.UNFLAG_CHANCE; + +import java.util.List; +import java.util.Random; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.function.Function; + +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 com.mojang.datafixers.util.Either; + +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ThreadedLevelLightEngine; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkStatus; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; + +@Mixin(value = ChunkStatus.class, remap = true) +public abstract class ChunkStatusMixin +{ + @Inject(method = "generate", at = @At("RETURN")) + public void nounusedchunks_onGenerate( + Executor executor, ServerLevel world, ChunkGenerator chunkGenerator, + StructureTemplateManager structureManager, ThreadedLevelLightEngine lightingProvider, + Function>> fullChunkConverter, + List chunkAccesses, boolean bl, + CallbackInfoReturnable>> callback) + { + //handle properties + if(!ENABLED) return; + if(UNFLAG_CHANCE != 100) + { + Random rnd = new Random(); + if(!(UNFLAG_CHANCE >= rnd.nextInt(0, 101))) return; + } + + //turn the action into a Runnable task + Runnable task = () -> + { + try + { + //get and null check the return value + CompletableFuture> rValue = callback.getReturnValue(); + if(rValue == null || !rValue.isDone()) return; //do not remove the isDone check, weird deadlocks occur when you do + + //get and null check the chunk + ChunkAccess chunk = rValue.get().left().orElse(null); + if(chunk == null) return; + + //unmark the chunk + chunk.setUnsaved(false); + } + catch(Exception exc) { exc.printStackTrace(); } + }; + + //let the server execute the task once it is able to + world.getServer().execute(task); + } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/mixin/WorldUpgraderMixin.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/mixin/WorldUpgraderMixin.java new file mode 100644 index 0000000..acfb73f --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/mixin/WorldUpgraderMixin.java @@ -0,0 +1,252 @@ +package thecsdev.nounusedchunks.mixin; + +import static thecsdev.nounusedchunks.config.NUCConfig.OW_RUC; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; +import java.util.concurrent.ThreadFactory; + +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +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 com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.mojang.datafixers.DataFixer; + +import it.unimi.dsi.fastutil.objects.Object2FloatMap; +import net.minecraft.ReportedException; +import net.minecraft.SharedConstants; +import net.minecraft.Util; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.worldupdate.WorldUpgrader; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.storage.ChunkStorage; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.storage.DimensionDataStorage; +import net.minecraft.world.level.storage.LevelStorageSource; +import thecsdev.nounusedchunks.NoUnusedChunks; + +@Mixin(value = WorldUpgrader.class, priority = 1100) +public abstract class WorldUpgraderMixin +{ + @Shadow public static Logger LOGGER; + @Shadow public static ThreadFactory THREAD_FACTORY; + @Shadow public Set> levels; + @Shadow public Registry dimensions; + @Shadow public boolean eraseCache; + @Shadow public LevelStorageSource.LevelStorageAccess levelStorage; + @Shadow public DataFixer dataFixer; + @Shadow public volatile boolean running; + @Shadow public volatile boolean finished; + @Shadow public volatile float progress; + @Shadow public volatile int totalChunks; + @Shadow public volatile int converted; + @Shadow public volatile int skipped; + @Shadow public Object2FloatMap> progressMap; + @Shadow public volatile Component status; + @Shadow public DimensionDataStorage overworldDataStorage; + + @Shadow public abstract List getAllChunkPos(ResourceKey levelKey); + + @Inject(method = "work", at = @At("HEAD"), cancellable = true) + public void onWork(CallbackInfo callback) + { + //if no OW_RUC, then ignore this process + if(!OW_RUC) return; + callback.cancel(); + + // ----------------------------- OW & RUC ----------------------------- + LOGGER.info("Using \"" + NoUnusedChunks.ModID + "'s\" WorldUpgrader and optimization system."); + + //retrieve chunk positions and a total count of chunks + this.totalChunks = 0; + Builder, ListIterator> builder = ImmutableMap.builder(); + for(ResourceKey worldKey : levels) + { + List list = this.getAllChunkPos(worldKey); + builder.put(worldKey, list.listIterator()); + this.totalChunks += list.size(); + } + + //if there are no chunks, return + if (this.totalChunks == 0) + { + this.finished = true; + return; + } + + //retrieve chunk regions + float f1 = (float)this.totalChunks; + ImmutableMap, ListIterator> immutablemap = builder.build(); + Builder, ChunkStorage> worldRegionFilesBuilder = ImmutableMap.builder(); + Builder, ChunkStorage> __worldTempRegionFilesBuilder = ImmutableMap.builder(); + for(ResourceKey worldKey : levels) + { + //get region directory path of the world (dimension) + Path path = this.levelStorage.getDimensionPath(worldKey); + + //create region file builders + worldRegionFilesBuilder.put(worldKey, new ChunkStorage(path.resolve("region"), this.dataFixer, false)); //dsync off + __worldTempRegionFilesBuilder.put(worldKey, new ChunkStorage(path.resolve("region") + .resolve(NoUnusedChunks.ModID + "_temp"), this.dataFixer, true)); + } + ImmutableMap, ChunkStorage> worldRegionFiles = worldRegionFilesBuilder.build(); + ImmutableMap, ChunkStorage> __worldTempRegionFiles = __worldTempRegionFilesBuilder.build(); + + //now for the upgrading process + long i = Util.getMillis(); + this.status = NoUnusedChunks.tt("optimizeWorld.stage.upgrading"); + while(this.running) + { + //flags + boolean willKeepUpgradingChunks = false; + float progressTrack = 0.0F; + + //iterate ResourceKey-s + for(ResourceKey worldKey : levels) + { + ListIterator worldChunkIterator = immutablemap.get(worldKey); + ChunkStorage versionedChunkStorage = worldRegionFiles.get(worldKey); + ChunkStorage __vcsTemp = __worldTempRegionFiles.get(worldKey); + + if (worldChunkIterator.hasNext()) + { + ChunkPos chunkPos = worldChunkIterator.next(); + boolean willChunkNotSkip = false; + + try + { + CompoundTag chunkNbt = versionedChunkStorage.read(chunkPos).join().orElse(null); + if (chunkNbt != null) + { + int chunkNbtVersion = ChunkStorage.getVersion(chunkNbt); + ChunkGenerator chunkgenerator = dimensions.getOrThrow(Registries.levelToLevelStem(worldKey)).generator(); + CompoundTag chunkNbtUpdated = versionedChunkStorage.upgradeChunkTag(worldKey, () -> this.overworldDataStorage, chunkNbt, chunkgenerator.getTypeNameForDataFixer()); + ChunkPos chunkPosUpdated = new ChunkPos(chunkNbtUpdated.getInt("xPos"), chunkNbtUpdated.getInt("zPos")); + + if (!chunkPosUpdated.equals(chunkPos)) + LOGGER.warn("Chunk {} has invalid position {}", chunkPos, chunkPosUpdated); + + @SuppressWarnings("deprecation") + boolean chunkChangesMade = chunkNbtVersion < SharedConstants.getCurrentVersion().getWorldVersion(); + boolean chunkIsUnused = OW_RUC && NoUnusedChunks.isChunkUnused(worldKey, chunkPos, chunkNbtUpdated); + + if (this.eraseCache && !chunkIsUnused) + { + chunkChangesMade = chunkChangesMade || chunkNbtUpdated.contains("Heightmaps"); + chunkChangesMade = chunkChangesMade || chunkNbtUpdated.contains("isLightOn"); + chunkNbtUpdated.remove("Heightmaps"); + chunkNbtUpdated.remove("isLightOn"); + + // ----- Forge-1.19.x - This Forge version erases lighting cache as well. + //erase chunk section cache (block and sky light) + ListTag nbtList = chunkNbtUpdated.getList("sections", 10); + for (int j = 0; j < nbtList.size(); j++) + { + CompoundTag nbtCompound3 = nbtList.getCompound(j); + chunkChangesMade = chunkChangesMade || nbtCompound3.contains("BlockLight"); + chunkChangesMade = chunkChangesMade || nbtCompound3.contains("SkyLight"); + nbtCompound3.remove("BlockLight"); + nbtCompound3.remove("SkyLight"); + } + } + else if(chunkIsUnused) + { + chunkNbtUpdated = null; + chunkChangesMade = true; + } + + if(!chunkIsUnused) __vcsTemp.write(chunkPos, chunkNbtUpdated); + if (chunkChangesMade) + { + //versionedChunkStorage.write(chunkPos, chunkNbtUpdated); -- already stored in __vcsTemp + willChunkNotSkip = true; + } + } + } + catch (ReportedException crashException) + { + Throwable crashCause = crashException.getCause(); + if (!(crashCause instanceof IOException)) { throw crashException; } + LOGGER.error("Error upgrading chunk {}", chunkPos, crashCause); + } + catch (Exception crashIoExc) + { + if(crashIoExc instanceof IOException) + LOGGER.error("Error upgrading chunk {}", chunkPos, crashIoExc); + else throw crashIoExc; + } + + if (willChunkNotSkip) { ++this.converted; } + else { ++this.skipped; } + + willKeepUpgradingChunks = true; + } + + float f2 = (float)worldChunkIterator.nextIndex() / f1; + this.progressMap.put(worldKey, f2); + progressTrack += f2; + } + + this.progress = progressTrack; + if (!willKeepUpgradingChunks) { this.running = false; } + } + + //finishing... + this.status = NoUnusedChunks.tt("optimizeWorld.stage.finished"); + worldRegionFiles.forEach((wrKey, vcsValue) -> + { + try + { + //close the chunk storages + vcsValue.close(); + + ChunkStorage __vcsTempValue = __worldTempRegionFiles.get(wrKey); + if(__vcsTempValue != null) __vcsTempValue.close(); + + //move the temp. region files to override the old ones + Path worldRegDir = this.levelStorage.getDimensionPath(wrKey).resolve("region"); + Path worldRegTempDir = worldRegDir.resolve(NoUnusedChunks.ModID + "_temp"); + for(File wrtdChild : worldRegTempDir.toFile().listFiles()) + { + Files.move( + wrtdChild.toPath(), + worldRegDir.resolve(wrtdChild.getName()), + StandardCopyOption.REPLACE_EXISTING); + } + worldRegTempDir.toFile().deleteOnExit(); + FileUtils.deleteDirectory(worldRegTempDir.toFile()); + } + catch (IOException ioexception) { LOGGER.error("Error upgrading chunk", (Throwable)ioexception); } + catch (NullPointerException e) {} //just in case Forge has this problem as well + }); + + this.overworldDataStorage.save(); + + //finish measuring, and log the time. then mark 'done' as true + i = Util.getMillis() - i; + LOGGER.info("World optimizaton finished after {} ms", (long)i); + this.finished = true; + + //clear temp. config variables. + OW_RUC = false; + } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/server/NoUnusedChunksServer.java b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/server/NoUnusedChunksServer.java new file mode 100644 index 0000000..6f42248 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/java/thecsdev/nounusedchunks/server/NoUnusedChunksServer.java @@ -0,0 +1,8 @@ +package thecsdev.nounusedchunks.server; + +import thecsdev.nounusedchunks.NoUnusedChunks; + +public class NoUnusedChunksServer extends NoUnusedChunks +{ + +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/META-INF/mods.toml b/nounusedchunks-forge-1.19.3/src/main/resources/META-INF/mods.toml new file mode 100644 index 0000000..f34d374 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/resources/META-INF/mods.toml @@ -0,0 +1,26 @@ +modLoader="javafml" +loaderVersion="[41,)" +license="LGPL-3.0-or-later" + +[[mods]] +modId="nounusedchunks" +version="1.4" +displayName="No Unused Chunks" +description="Reduces world size by discarding unused chunks." +logoFile="nounusedchunks_logo.png" +authors="TheCSDev" +credits="" + +[[dependencies.nounusedchunks]] + modId="forge" + mandatory=true + versionRange="[44,)" + ordering="NONE" + side="BOTH" + +[[dependencies.nounusedchunks]] + modId="minecraft" + mandatory=true + versionRange="[1.19.3,1.20)" + ordering="NONE" + side="BOTH" diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/assets/nounusedchunks/lang/en_us.json b/nounusedchunks-forge-1.19.3/src/main/resources/assets/nounusedchunks/lang/en_us.json new file mode 100644 index 0000000..38e9970 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/resources/assets/nounusedchunks/lang/en_us.json @@ -0,0 +1,13 @@ +{ + "nounusedchunks.backupprompt.removeuninhabitedchunks": "Erase uninhabited chunks", + "nounusedchunks.backupprompt.removeuninhabitedchunks.tooltip": "Erases all chunks that were never inhabited by a player.\nWhile this may reduce the world size by a lot, keep in\nmind that this may also remove chunks you might need,\nwithout actually having visited them. For example, this\nmay end up removing chunks modified by another mod or a\ntool or a program. Please back up your world before\ndoing this, and make sure the chunks got removed properly.", + "nounusedchunks.backupprompt.removelightcache": "Erase lighting cache", + "nounusedchunks.backupprompt.removelightcache.tooltip": "Lighting cache is already erased\nautomatically as of forge-1.19.x", + + "nounusedchunks.config.title": "No Unused Chunks config", + "nounusedchunks.config.general": "General", + "nounusedchunks.config.general.enabled": "Enabled", + "nounusedchunks.config.general.enabled.tooltip": "Whether the mod is enabled or not.\nWhen enabled, newly generated chunks that\nhave been untouched will not be\nmarked as 'needs saving'.", + "nounusedchunks.config.general.unflag_chance": "Un-Flag chance (advanced)", + "nounusedchunks.config.general.unflag_chance.tooltip": "Defines the chance a newly generated chunk will not be marked\nas 'needs saving'. Lower chance means more newly generated\nchunks will immediately get saved like they would normally\nwhile saving performance at the cost of drive storage, while\nhigher values will make the mod unmark more newly generated\nchunks as 'needs saving' and thus saving more storage at the\ncost of performance." +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/assets/nounusedchunks/lang/ru_ru.json b/nounusedchunks-forge-1.19.3/src/main/resources/assets/nounusedchunks/lang/ru_ru.json new file mode 100644 index 0000000..4b9fa67 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/resources/assets/nounusedchunks/lang/ru_ru.json @@ -0,0 +1,11 @@ +{ + "nounusedchunks.backupprompt.removeuninhabitedchunks": "Удалить необитаемые чанки", + "nounusedchunks.backupprompt.removeuninhabitedchunks.tooltip": "Удалить все чанки, которые никогда не посещал игрок.\nХоть это и может значительно уменьшить размер мира,\nимейте ввиду, что удаление может затронуть и нужные\nвам чанки, которые вы никогда не посещали. Например,\nсозданные другим модом или программой.\nПожалуйста, сохраняйте резервные копии мира перед\nиспользованием этой функции и всегда убеждайтесь,\nчто она сработала без ошибок.", + + "nounusedchunks.clothconfig.title": "Настройки No Unused Chunks", + "nounusedchunks.clothconfig.general": "Основные", + "nounusedchunks.clothconfig.general.enabled": "Включён", + "nounusedchunks.clothconfig.general.enabled.tooltip": "Основной переключатель работы мода.\nЕсли включён, новые неизменённые чанки\nне будут помечаться как требующие сохранения.", + "nounusedchunks.clothconfig.general.unflag_chance": "Вероятность удаления (расширенные)", + "nounusedchunks.clothconfig.general.unflag_chance.tooltip": " Вероятность того, что сгенерированный чанк\nне будет помечен как требующий сохранения.\n\n Чем ниже значение, тем больше новых чанков\nбудет сохранено сразу после их генерации,\nповышая производительность за счёт меньшей\nэкономии места на диске.\n Чем выше значение, тем меньше новых чанков\nбудет помечаться как требующие сохранения,\nэкономя пространство на диске за счёт\nснижения производительности.", +} diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks.client.mixins.json b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks.client.mixins.json new file mode 100644 index 0000000..baba9ee --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks.client.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "thecsdev.nounusedchunks.client.mixin", + "refmap": "mixins.nounusedchunks.refmap.json", + "compatibilityLevel": "JAVA_17", + "client": ["ModListScreenMixin", "BackupConfirmScreenMixin"], + "injectors": + { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks.mixins.json b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks.mixins.json new file mode 100644 index 0000000..6869c59 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "thecsdev.nounusedchunks.mixin", + "refmap": "mixins.nounusedchunks.refmap.json", + "compatibilityLevel": "JAVA_17", + "mixins": ["ChunkStatusMixin", "WorldUpgraderMixin"], + "injectors": + { + "defaultRequire": 1 + } +} \ No newline at end of file diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks_logo.aseprite b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks_logo.aseprite new file mode 100644 index 0000000..6841762 Binary files /dev/null and b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks_logo.aseprite differ diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks_logo.png b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks_logo.png new file mode 100644 index 0000000..f9722dd Binary files /dev/null and b/nounusedchunks-forge-1.19.3/src/main/resources/nounusedchunks_logo.png differ diff --git a/nounusedchunks-forge-1.19.3/src/main/resources/pack.mcmeta b/nounusedchunks-forge-1.19.3/src/main/resources/pack.mcmeta new file mode 100644 index 0000000..e8d7783 --- /dev/null +++ b/nounusedchunks-forge-1.19.3/src/main/resources/pack.mcmeta @@ -0,0 +1,9 @@ +{ + "pack": + { + "description": "examplemod resources", + "pack_format": 9, + "forge:resource_pack_format": 8, + "forge:data_pack_format": 9 + } +}