diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 9e3b233a..a835a44a 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -1,73 +1,61 @@ -# This workflow will build a Java project with Gradle -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle - -name: auto-release - -on: - push: - tags: - - 'v*' - -jobs: - first: - name: Check release tag - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - - run: | - prop() { grep -P "^\s*[^#]?${1}=.*$" './gradle.properties' | cut -d'=' -f2; } - echo "GIT_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - echo "MOD_VERSION=`echo $(prop "mod_version")`" >> $GITHUB_ENV - - - run: if [ "${{env.GIT_TAG}}" != "v${{env.MOD_VERSION}}" ];then exit 1;fi - - second: - name: Build and publish - runs-on: ubuntu-latest - needs: first - permissions: - contents: write - packages: write - - steps: - - uses: actions/checkout@v4 - - - name: Set up JDK 17 - uses: actions/setup-java@v4 - with: - java-version: '17' - distribution: 'temurin' - architecture: 'x64' - cache: 'gradle' - - - name: Build and publish with Gradle - env: - IS_RELEASE: true - GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} - ORG_GRADLE_PROJECT_signingKey: ${{secrets.RELEASE_SIGNING_GPG_PRIVATE_KEY}} - ORG_GRADLE_PROJECT_signingPassword: ${{secrets.RELEASE_SIGNING_GPG_PASSPHRASE}} - AUIOC_MAVEN_USERNAME: ${{secrets.AUIOC_MAVEN_USERNAME}} - AUIOC_MAVEN_TOKEN: ${{secrets.AUIOC_MAVEN_TOKEN}} - run: | - chmod +x ./gradlew - ./gradlew runData - ./gradlew build publish generateUpdateJson - mkdir ./pages - cp -r ./build/tmp/update/. ./pages/ - - - name: Update update JSON - uses: JamesIves/github-pages-deploy-action@v4 - with: - clean: false - target-folder: update - branch: gh-pages - folder: pages - - - name: Github release - uses: softprops/action-gh-release@v1 - with: - files: | - build/libs/*.jar - build/libs/*.asc +name: auto-release + +on: + push: + tags: + - 'v*' + +jobs: + first: + name: Check release tag + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - run: | + prop() { grep -P "^\s*[^#]?${1}=.*$" './gradle.properties' | cut -d'=' -f2; } + echo "GIT_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV + echo "MOD_VERSION=`echo $(prop "mod_version")`" >> $GITHUB_ENV + + - run: if [ "${{env.GIT_TAG}}" != "v${{env.MOD_VERSION}}" ];then exit 1;fi + + second: + name: Build and publish + runs-on: ubuntu-latest + needs: first + permissions: + contents: write + packages: write + + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + architecture: 'x64' + cache: 'gradle' + + - name: Build and publish with Gradle + env: + IS_RELEASE: true + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + ORG_GRADLE_PROJECT_signingKey: ${{secrets.RELEASE_SIGNING_GPG_PRIVATE_KEY}} + ORG_GRADLE_PROJECT_signingPassword: ${{secrets.RELEASE_SIGNING_GPG_PASSPHRASE}} + AUIOC_MAVEN_USERNAME: ${{secrets.AUIOC_MAVEN_USERNAME}} + AUIOC_MAVEN_TOKEN: ${{secrets.AUIOC_MAVEN_TOKEN}} + run: | + chmod +x ./gradlew + ./gradlew build publish + + - name: Github release + uses: softprops/action-gh-release@v1 + with: + files: | + build/libs/*.jar + build/libs/*.asc diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index 93467852..7ad324af 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -1,6 +1,3 @@ -# This workflow will build a Java project with Gradle -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle - name: dev-build on: @@ -18,11 +15,13 @@ jobs: steps: - uses: actions/checkout@v4 + with: + submodules: recursive - - name: Set up JDK 17 + - name: Set up JDK 21 uses: actions/setup-java@v4 with: - java-version: '17' + java-version: '21' distribution: 'temurin' architecture: 'x64' cache: 'gradle' @@ -30,12 +29,11 @@ jobs: - name: Build with Gradle run: | chmod +x ./gradlew - ./gradlew runData ./gradlew build echo "ARTIFACT_NAME=`cat ./build/tmp/artifact-name.txt`" >> $GITHUB_ENV - name: Upload build artifacts - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v4 with: name: ${{env.ARTIFACT_NAME}} path: build/libs diff --git a/.gitignore b/.gitignore index 1957d4d1..05bc46cf 100644 --- a/.gitignore +++ b/.gitignore @@ -11,21 +11,19 @@ out *.ipr *.iws *.iml -.idea - -# vscode -.vscode +.idea/* +!.idea/copyright +!.idea/scopes # gradle build .gradle # other -**/test/DevTest*.java -src/generated eclipse run runs run-data +src/generated repo diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..e0de95c9 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "scripts"] + path = scripts + url = git@github.com:auioc/mcmod-scripts.git diff --git a/.idea/copyright/auioc_mcmod_gplv3.xml b/.idea/copyright/auioc_mcmod_gplv3.xml new file mode 100644 index 00000000..da2f44d7 --- /dev/null +++ b/.idea/copyright/auioc_mcmod_gplv3.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 00000000..6866eeac --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/scopes/src_auioc.xml b/.idea/scopes/src_auioc.xml new file mode 100644 index 00000000..8e5aa977 --- /dev/null +++ b/.idea/scopes/src_auioc.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/scopes/src_coremods.xml b/.idea/scopes/src_coremods.xml new file mode 100644 index 00000000..a2e556db --- /dev/null +++ b/.idea/scopes/src_coremods.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/README.md b/README.md index b3cdfe9d..4c298fe5 100644 --- a/README.md +++ b/README.md @@ -4,19 +4,23 @@ Shared library for AH's Minecraft mods. +**! 1.21 Porting is in Progress !** + [![GitHub license](https://img.shields.io/github/license/auioc/arnicalib-mcmod?style=flat-square)](/LICENSE) -[![GitHub release](https://img.shields.io/github/v/release/auioc/arnicalib-mcmod?style=flat-square)](https://github.com/auioc/arnicalib-mcmod/releases/latest) + +![Minecraft](https://img.shields.io/static/v1?label=Minecraft&message=1.21.4&color=00aa00&style=flat-square) +[![NeoForge](https://img.shields.io/static/v1?label=NeoForge&message=21.4.50-beta&color=e04e14&style=flat-square)](https://neoforged.net/) ![Mappings](https://img.shields.io/static/v1?label=Mappings&message=parchment&color=00aa00&style=flat-square)
-![OpenJDK](https://img.shields.io/static/v1?label=OpenJDK&message=17&color=brightgreen&logo=java&style=flat-square) -[![Gradle](https://img.shields.io/static/v1?label=Gradle&message=8.1.1&color=brightgreen&logo=gradle&style=flat-square)](https://docs.gradle.org/8.1.1/release-notes.html) +![OpenJDK](https://img.shields.io/static/v1?label=OpenJDK&message=21&color=brightgreen&logo=java&style=flat-square) +[![Gradle](https://img.shields.io/static/v1?label=Gradle&message=8.11.1&color=brightgreen&logo=gradle&style=flat-square)](https://docs.gradle.org/8.11.1/release-notes.html) + + ## Maintainers - [@WakelessSloth56](https://github.com/WakelessSloth56) diff --git a/build.gradle b/build.gradle index 42237414..7da9e3dd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,33 +1,128 @@ plugins { id 'java-library' - id 'eclipse' - id 'idea' id 'maven-publish' - id 'net.neoforged.gradle.userdev' version '7.0.80' + id 'net.neoforged.moddev' version '1.0.23' + id 'idea' +} + +tasks.named('wrapper', Wrapper).configure { + distributionType = Wrapper.DistributionType.BIN } -java.toolchain.languageVersion = JavaLanguageVersion.of(17) +version = mod_version +group = mod_group_id + +repositories { + mavenLocal() +} + +base { + archivesName = mod_id +} + +java.toolchain.languageVersion = JavaLanguageVersion.of(21) + +neoForge { + version = project.neo_version + + parchment { + mappingsVersion = project.parchment_mappings_version + minecraftVersion = project.parchment_minecraft_version + } + + // This line is optional. Access Transformers are automatically detected + // accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg') + + runs { + client { + client() + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id + } + + server { + server() + programArgument '--nogui' + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id + } -repositories {} -dependencies {} + gameTestServer { + type = "gameTestServer" + systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id + } -apply from: "${scripts_url}/minecraft/neo/minecraft.gradle" -runs { - configureEach { - // systemProperty 'forge.logging.markers', 'REGISTRIES' - systemProperty 'forge.logging.console.level', 'debug' - systemProperty 'mixin.debug', 'true' + serverData { + serverData() + programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() + } + + clientData { + clientData() + programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() + } + + configureEach { + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + systemProperty 'forge.logging.markers', 'REGISTRIES' + + logLevel = org.slf4j.event.Level.DEBUG + } + } + + mods { + "${mod_id}" { + sourceSet(sourceSets.main) + } } } -apply from: "${scripts_url}/minecraft/neo/resources.gradle" -apply from: "${scripts_url}/minecraft/neo/build-info.gradle" -apply from: "${scripts_url}/minecraft/neo/artifacts.gradle" -apply from: "${scripts_url}/minecraft/neo/publishing.gradle" -apply from: "${scripts_url}/common/signing.gradle" -apply from: "${scripts_url}/minecraft/neo/custom-clean.gradle" -apply from: "${scripts_url}/minecraft/neo/update-json.gradle" +sourceSets.main.resources { srcDir 'src/generated/resources' } + +configurations { + runtimeClasspath.extendsFrom localRuntime +} + +dependencies { + // Example mod dependency using a mod jar from ./libs with a flat dir repository + // This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar + // The group id is ignored when searching -- in this case, it is "blank" + // implementation "blank:coolmod-${mc_version}:${coolmod_version}" -tasks.withType(JavaCompile).configureEach { - options.encoding = 'UTF-8' + // Example mod dependency using a file as dependency + // implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar") +} + +var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) { + var replaceProperties = [ + minecraft_version : minecraft_version, + minecraft_version_range: minecraft_version_range, + neo_version : neo_version, + neo_version_range : neo_version_range, + loader_version_range : loader_version_range, + mod_id : mod_id, + mod_name : mod_name, + mod_license : mod_license, + mod_version : mod_version, + mod_authors : mod_authors, + mod_description : mod_description + ] + + inputs.properties replaceProperties + expand replaceProperties + from "src/main/templates" + into "build/generated/sources/modMetadata" +} +sourceSets.main.resources.srcDir generateModMetadata +neoForge.ideSyncTask generateModMetadata + +apply from: 'scripts/gradle/build-info.gradle' +apply from: 'scripts/gradle/artifacts.gradle' +apply from: 'scripts/gradle/publishing.gradle' + +idea { + module { + downloadSources = true + downloadJavadoc = true + } } diff --git a/gradle.properties b/gradle.properties index 4a2db5ea..59dbafe2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,25 +1,23 @@ -# Sets default memory used for gradle commands. Can be overridden by user or command line properties. -#org.gradle.jvmargs= -org.gradle.daemon=false -org.gradle.debug=false +org.gradle.jvmargs=-Xmx1G +org.gradle.daemon=true +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.configuration-cache=false -scripts_url=https://hi.auioc.org/gradle-scripts +parchment_minecraft_version=1.21.4 +parchment_mappings_version=2025.01.05 -neogradle.subsystems.parchment.minecraftVersion=1.20.3 -neogradle.subsystems.parchment.mappingsVersion=2023.12.31 - -minecraft_version=1.20.4 -minecraft_version_range=[1.20.4,1.21) -neo_version=20.4.80-beta -neo_version_range=[20.4,) -loader_version_range=[2,) +minecraft_version=1.21.4 +minecraft_version_range=[1.21.4, 1.22) +neo_version=21.4.50-beta +neo_version_range=[21.4.50-beta,) +loader_version_range=[4,) mod_repository=auioc/arnicalib-mcmod mod_id=arnicalib mod_name=ArnicaLib -mod_group_id=org.auioc.mcmod -mod_version=6.1.3 mod_license=GNU GPLv3 -mod_authors=WakelessSloth56, LainIO24 -mod_credits=AUIOC -mod_description=Shared library for AH's Minecraft mods. +mod_version=7.0.0 +mod_group_id=org.auioc.mcmod +mod_authors=AUIOC.ORG +mod_description=ArnicaLib diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 943f0cbf..a4b76b95 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37aef8d3..e2847c82 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 65dcd68d..f5feea6d 100644 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# 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/. @@ -83,10 +85,9 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -# 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"' +# 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 +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,10 +134,13 @@ 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. + 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. @@ -144,7 +148,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +156,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -197,11 +201,15 @@ if "$cygwin" || "$msys" ; then 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. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59f..9b42019c 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,92 +1,94 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@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 + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/scripts b/scripts new file mode 160000 index 00000000..6d90cfcd --- /dev/null +++ b/scripts @@ -0,0 +1 @@ +Subproject commit 6d90cfcde1ab669cc1a90fa6f60919b11324fbb1 diff --git a/settings.gradle b/settings.gradle index 888ce402..203cfd9b 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,7 +7,7 @@ pluginManagement { } plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.9.0' } -rootProject.name = 'arnicalib' +rootProject.name = 'ArnicaLib' diff --git a/src/main/java/org/auioc/mcmod/arnicalib/ArnicaLib.java b/src/main/java/org/auioc/mcmod/arnicalib/ArnicaLib.java index 8aa4bbde..e64bb3ef 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/ArnicaLib.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/ArnicaLib.java @@ -1,59 +1,57 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib; - -import net.minecraft.resources.ResourceLocation; -import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.common.Mod; -import org.apache.logging.log4j.Logger; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; -import org.auioc.mcmod.arnicalib.game.mod.BuildInfo; -import org.auioc.mcmod.arnicalib.game.mod.IHMod; -import org.auioc.mcmod.arnicalib.mod.Initialization; - -@Mod(ArnicaLib.MOD_ID) -public final class ArnicaLib implements IHMod { - - public static final String MOD_ID = "arnicalib"; - public static final String MOD_NAME = "ArnicaLib"; - public static final Logger LOGGER = LogUtil.getLogger(MOD_NAME); - public static final BuildInfo BUILD_INFO = BuildInfo.fromPackage(ArnicaLib.class); - - private static IEventBus modEventBus; - - public ArnicaLib(IEventBus modEventBus) { - ArnicaLib.modEventBus = modEventBus; - IHMod.validateVersion(BUILD_INFO, LOGGER); - Initialization.init(); - } - - public static IEventBus getModEventBus() { - return modEventBus; - } - - public static ResourceLocation id(String path) { - return new ResourceLocation(MOD_ID, path); - } - - public static String i18n(String key) { - return MOD_ID + "." + key; - } - -} +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib; + +import net.minecraft.resources.ResourceLocation; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; +import org.auioc.mcmod.arnicalib.game.util.BuildInfo; +import org.auioc.mcmod.arnicalib.mod.Initialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +@Mod(ArnicaLib.MOD_ID) +public final class ArnicaLib { + + public static final String MOD_ID = "arnicalib"; + public static final String MOD_NAME = "ArnicaLib"; + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_NAME); + public static final Marker MARKER = MarkerFactory.getMarker("CORE"); + public static final BuildInfo BUILD_INFO = BuildInfo.fromPackage(ArnicaLib.class); + + private static IEventBus modEventBus; + + public ArnicaLib(IEventBus modEventBus) { + ArnicaLib.modEventBus = modEventBus; + BUILD_INFO.log(LOGGER, MARKER); + Initialization.init(); + } + + public static IEventBus modEventBus() { + return modEventBus; + } + + public static ResourceLocation id(String path) { + return ResourceLocation.fromNamespaceAndPath(MOD_ID, path); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/awt/ImageUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/awt/ImageUtils.java deleted file mode 100644 index 88d0808c..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/awt/ImageUtils.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.awt; - -import java.awt.Color; -import java.awt.Rectangle; -import java.awt.color.ColorSpace; -import java.awt.image.BufferedImage; - -import org.auioc.mcmod.arnicalib.base.function.BiIntFunction; -import org.auioc.mcmod.arnicalib.base.validate.Validate; - -public class ImageUtils { - - public static Color getColor(BufferedImage image, int x, int y) { - Validate.isTrue(image.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_RGB); - var pixel = image.getData().getPixel(x, y, new int[4]); - return new Color(pixel[0], pixel[1], pixel[2], pixel[3]); - } - - public static Color[] getColors(BufferedImage image, int x, int y, int w, int h) { - int pixelCount = w * h; - var colors = new Color[pixelCount]; - int i = 0; - for (int _y = y, y0 = y + h; _y < y0; ++_y) { - for (int _x = x, x0 = x + w; _x < x0; ++_x) { - colors[i] = getColor(image, _x, _y); - i++; - } - } - return colors; - } - - public static Color[] getColors(BufferedImage image, BiIntFunction rectangle) { - var rect = rectangle.apply(image.getWidth(), image.getHeight()); - return getColors(image, rect.x, rect.y, rect.width, rect.height); - } - - public static int[] getARGBColors(BufferedImage image, BiIntFunction rectangle) { - var colors = ImageUtils.getColors(image, rectangle); - var argbColors = new int[colors.length]; - for (int i = 0; i < colors.length; i++) argbColors[i] = colors[i].getRGB(); - return argbColors; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/Cache.java b/src/main/java/org/auioc/mcmod/arnicalib/base/cache/Cache.java deleted file mode 100644 index 0f01eda0..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/Cache.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.cache; - -public interface Cache { - - V get(K key); - - void put(K key, V value); - - void clear(); - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/LoadingCache.java b/src/main/java/org/auioc/mcmod/arnicalib/base/cache/LoadingCache.java deleted file mode 100644 index 8cd76bd7..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/LoadingCache.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.cache; - -import javax.annotation.Nonnull; - -public interface LoadingCache extends Cache { - - @Nonnull - V load(K key); - - @Override - default void put(K key, V value) { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/PlainCache.java b/src/main/java/org/auioc/mcmod/arnicalib/base/cache/PlainCache.java deleted file mode 100644 index 7a88e518..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/PlainCache.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.cache; - -import java.util.HashMap; -import java.util.Optional; -import javax.annotation.Nullable; - -public class PlainCache implements Cache { - - private final HashMap map = new HashMap(); - - @Nullable - @Override - public V get(K key) { - return map.get(key); - } - - public Optional getOptional(K key) { - return Optional.ofNullable(get(key)); - } - - @Override - public void put(K key, V value) { - map.put(key, value); - } - - @Override - public void clear() { - map.clear(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/PlainLoadingCache.java b/src/main/java/org/auioc/mcmod/arnicalib/base/cache/PlainLoadingCache.java deleted file mode 100644 index fb3fe755..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/cache/PlainLoadingCache.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.cache; - -import java.util.HashMap; -import java.util.function.Function; -import javax.annotation.Nonnull; - -public class PlainLoadingCache implements LoadingCache { - - private final HashMap map = new HashMap(); - private final Function loader; - - public PlainLoadingCache(Function loader) { - this.loader = loader; - } - - @Nonnull - @Override - public V get(K key) { - return (map.containsKey(key)) ? map.get(key) : load(key); - } - - @Nonnull - @Override - public V load(K key) { - V value = loader.apply(key); - map.put(key, value); - return value; - } - - - @Override - public void clear() { - map.clear(); - } - - public void refresh(K key) { - load(key); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/collection/ListUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/collection/ListUtils.java index 0311f97f..4022f3ab 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/collection/ListUtils.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/collection/ListUtils.java @@ -1,112 +1,108 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.collection; - -import org.apache.commons.lang3.Validate; - -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.IntStream; - -public class ListUtils { - - public static T getLast(List list) { - Validate.notEmpty(list); - return list.get(list.size() - 1); - } - - public static Optional getOptional(List list, int index) { - return (index >= 0 && index < list.size()) ? Optional.ofNullable(list.get(index)) : Optional.empty(); - } - - public static T getOrDefault(List list, int index, T defaultValue) { - return (index >= 0 && index < list.size()) ? list.get(index) : defaultValue; - } - - - public static int indexOf(List list, Predicate predicate, int ordinal) { - for (int i = 0, l = list.size(); i < l; ++i) { - if (predicate.test(list.get(i))) { - if (ordinal <= 0) return i; - ordinal--; - } - } - return -1; - } - - public static int indexOf(List list, Predicate predicate) { - return indexOf(list, predicate, 0); - } - - public static int lastIndexOf(List list, Predicate predicate, int ordinal) { - for (int i = list.size() - 1; i >= 0; --i) { - if (predicate.test(list.get(i))) { - if (ordinal <= 0) return i; - ordinal--; - } - } - return -1; - } - - public static int lastIndexOf(List list, Predicate predicate) { - return lastIndexOf(list, predicate, 0); - } - - public static int[] allIndexesOf(List list, Predicate predicate) { - return IntStream - .range(0, list.size()) - .filter((i) -> predicate.test(list.get(i))) - .toArray(); - } - - - public static List findAll(List list, Predicate predicate) { - return list.stream().filter(predicate).toList(); - } - - public static Optional findFirst(List list, Predicate predicate) { - return list.stream().filter(predicate).findFirst(); - } - - public static Optional findFirst(List list, Predicate predicate, int ordinal) { - return getOptional(list, indexOf(list, predicate, ordinal)); - } - - public static Optional findLast(List list, Predicate predicate, int ordinal) { - return getOptional(list, lastIndexOf(list, predicate, ordinal)); - } - - - public static boolean add(List list, int index, T element) { - if (index > list.size() || index < 0) return false; - list.add(index, element); - return true; - } - - public static boolean addBefore(List list, Predicate refPredicate, T element) { - return add(list, indexOf(list, refPredicate), element); - } - - public static boolean addAfter(List list, Predicate refPredicate, T element) { - return add(list, indexOf(list, refPredicate) + 1, element); - } - -} +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.base.collection; + +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.IntStream; + +public class ListUtils { + + public static Optional getOptional(List list, int index) { + return (index >= 0 && index < list.size()) ? Optional.ofNullable(list.get(index)) : Optional.empty(); + } + + public static T getOrDefault(List list, int index, T defaultValue) { + return (index >= 0 && index < list.size()) ? list.get(index) : defaultValue; + } + + // ============================================================================================================== // + + public static int indexOf(List list, Predicate predicate, int ordinal) { + for (int i = 0, l = list.size(); i < l; ++i) { + if (predicate.test(list.get(i))) { + if (ordinal <= 0) return i; + ordinal--; + } + } + return -1; + } + + public static int indexOf(List list, Predicate predicate) { + return indexOf(list, predicate, 0); + } + + public static int lastIndexOf(List list, Predicate predicate, int ordinal) { + for (int i = list.size() - 1; i >= 0; --i) { + if (predicate.test(list.get(i))) { + if (ordinal <= 0) return i; + ordinal--; + } + } + return -1; + } + + public static int lastIndexOf(List list, Predicate predicate) { + return lastIndexOf(list, predicate, 0); + } + + public static int[] allIndexesOf(List list, Predicate predicate) { + return IntStream + .range(0, list.size()) + .filter((i) -> predicate.test(list.get(i))) + .toArray(); + } + + // ============================================================================================================== // + + public static List findAll(List list, Predicate predicate) { + return list.stream().filter(predicate).toList(); + } + + public static Optional findFirst(List list, Predicate predicate) { + return list.stream().filter(predicate).findFirst(); + } + + public static Optional findFirst(List list, Predicate predicate, int ordinal) { + return getOptional(list, indexOf(list, predicate, ordinal)); + } + + public static Optional findLast(List list, Predicate predicate, int ordinal) { + return getOptional(list, lastIndexOf(list, predicate, ordinal)); + } + + // ============================================================================================================== // + + public static boolean add(List list, int index, T element) { + if (index > list.size() || index < 0) return false; + list.add(index, element); + return true; + } + + public static boolean addBefore(List list, Predicate refPredicate, T element) { + return add(list, indexOf(list, refPredicate), element); + } + + public static boolean addAfter(List list, Predicate refPredicate, T element) { + return add(list, indexOf(list, refPredicate) + 1, element); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/IHProjectile.java b/src/main/java/org/auioc/mcmod/arnicalib/base/event/CancelFlag.java similarity index 67% rename from src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/IHProjectile.java rename to src/main/java/org/auioc/mcmod/arnicalib/base/event/CancelFlag.java index 729778c7..c3632c97 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/IHProjectile.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/event/CancelFlag.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * @@ -17,17 +17,25 @@ * this program. If not, see . */ -package org.auioc.mcmod.arnicalib.game.entity.projectile; +package org.auioc.mcmod.arnicalib.base.event; -import javax.annotation.Nullable; +/** + * @since 7.0.0 + */ +public class CancelFlag { + + private boolean canceled = false; -import net.minecraft.world.phys.Vec3; + public boolean isCanceled() { + return this.canceled; + } -public interface IHProjectile { + public void cancel() { + this.canceled = true; + } - @Nullable - default Vec3 getShootingPosition() { - return null; + public void keep() { + this.canceled = false; } } diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/server/TpsRecord.java b/src/main/java/org/auioc/mcmod/arnicalib/base/event/EventResult.java similarity index 81% rename from src/main/java/org/auioc/mcmod/arnicalib/game/server/TpsRecord.java rename to src/main/java/org/auioc/mcmod/arnicalib/base/event/EventResult.java index cd6b9836..35e6be11 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/server/TpsRecord.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/event/EventResult.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * @@ -17,8 +17,13 @@ * this program. If not, see . */ -package org.auioc.mcmod.arnicalib.game.server; - -public record TpsRecord(double mspt, double tps) { +package org.auioc.mcmod.arnicalib.base.event; +/** + * @since 7.0.0 + */ +public enum EventResult { + ALLOW, + DEFAULT, + DENY; } diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/file/FileUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/file/FileUtils.java deleted file mode 100644 index 8e1007fd..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/file/FileUtils.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.file; - -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public class FileUtils extends org.apache.commons.io.FileUtils { - - private static final Marker MARKER = LogUtil.getMarker(FileUtils.class); - - public static File getOrCreateDirectory(String directoryName) throws IOException { - var file = new File(directoryName); - - if (file.exists()) return file; - - if (file.mkdirs()) { - LOGGER.warn(MARKER, "Directory \"" + file + "\" does not exist, create"); - return file; - } - throw new IOException("Could not create directory \"" + file + "\""); - } - - public static File getFile(String fileName) throws IOException { - var file = new File(fileName); - - if (file.getParentFile().exists()) return file; - - if (file.getParentFile().mkdirs()) { - LOGGER.warn(MARKER, "Parent directory of file \"" + file + "\" does not exist, create"); - return file; - } - throw new IOException("Could not create parent directory of file \"" + file + "\""); - } - - /** - * Reads the contents of a file into a String using the UTF-8 charset. The file is always closed. - * - * @param file the file to read, must not be {@code null} - * @return the file contents, never {@code null} - * @throws NullPointerException if file is {@code null}. - * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading. - * @throws IOException if an I/O error occurs. - * @see org.apache.commons.io.FileUtils#readFileToString(File, Charset) - * @since 5.1.4 - */ - public static String readFileToString(final File file) throws IOException { - return readFileToString(file, StandardCharsets.UTF_8); - } - - /** - * Writes a String to a file creating the file if it does not exist using the UTF-8 charset. - * - * @param file the file to write - * @param data the content to write to the file - * @throws IOException in case of an I/O error - * @see org.apache.commons.io.FileUtils#writeStringToFile(File, String, Charset, boolean) - * @since 5.1.4 - */ - public static void writeStringToFile(final File file, final String data) throws IOException { - writeStringToFile(file, data, StandardCharsets.UTF_8, false); - } - - // ====================================================================== // - - @Deprecated - private FileUtils() { } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/file/JarUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/file/JarUtils.java deleted file mode 100644 index eed37c25..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/file/JarUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.file; - -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; - -import java.io.IOException; -import java.net.URL; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public class JarUtils { - - public static final Marker MARKER = LogUtil.getMarker(JarUtils.class); - - public static Attributes getManifest(Class clazz) throws IOException { - try { - String path = clazz.getResource(clazz.getSimpleName() + ".class").toString(); - return new Manifest(new URL(path.substring(0, path.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF").openStream()).getMainAttributes(); - } catch (Exception e) { - LOGGER.warn(MARKER, "MANIFEST.MF of " + clazz.getSimpleName() + ".class could not be read. If this is a development environment you can ignore this message."); - throw e; - } - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/FailableTriPredicate.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/FailableTriPredicate.java deleted file mode 100644 index 39f02dab..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/FailableTriPredicate.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -import java.util.Objects; - -@FunctionalInterface -public interface FailableTriPredicate { - - boolean test(T t, U u, V v) throws E; - - default FailableTriPredicate and(FailableTriPredicate other) { - Objects.requireNonNull(other); - return (t, u, v) -> test(t, u, v) && other.test(t, u, v); - } - - default FailableTriPredicate negate() { - return (t, u, v) -> !test(t, u, v); - } - - default FailableTriPredicate or(FailableTriPredicate other) { - Objects.requireNonNull(other); - return (t, u, v) -> test(t, u, v) || other.test(t, u, v); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/BiIntFunction.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/IntToFloatFunction.java similarity index 85% rename from src/main/java/org/auioc/mcmod/arnicalib/base/function/BiIntFunction.java rename to src/main/java/org/auioc/mcmod/arnicalib/base/function/IntToFloatFunction.java index 75aefdb6..e8f36584 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/BiIntFunction.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/function/IntToFloatFunction.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * @@ -19,9 +19,12 @@ package org.auioc.mcmod.arnicalib.base.function; +/** + * @since 7.0.0 + */ @FunctionalInterface -public interface BiIntFunction { +public interface IntToFloatFunction { - R apply(int left, int right); + float applyAsFloat(int value); } diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadConsumer.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadConsumer.java deleted file mode 100644 index 2dec0042..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadConsumer.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -import java.util.Objects; - -@FunctionalInterface -public interface QuadConsumer { - - void accept(T t, U u, V v, W w); - - default QuadConsumer andThen(QuadConsumer after) { - Objects.requireNonNull(after); - return (t, u, v, w) -> { - accept(t, u, v, w); - after.accept(t, u, v, w); - }; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadPredicate.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadPredicate.java deleted file mode 100644 index 5a4a824e..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadPredicate.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -import java.util.Objects; - -@FunctionalInterface -public interface QuadPredicate { - - boolean test(T t, U u, V v, W w); - - default QuadPredicate negate() { - return (t, u, v, w) -> !test(t, u, v, w); - } - - default QuadPredicate and(QuadPredicate other) { - Objects.requireNonNull(other); - return (t, u, v, w) -> test(t, u, v, w) && other.test(t, u, v, w); - } - - default QuadPredicate or(QuadPredicate other) { - Objects.requireNonNull(other); - return (t, u, v, w) -> test(t, u, v, w) || other.test(t, u, v, w); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringFunction.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringFunction.java index 99a178c6..71a72413 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringFunction.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringFunction.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2022-2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringUnaryOperator.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringUnaryOperator.java deleted file mode 100644 index 2b808f3c..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/StringUnaryOperator.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -import java.util.function.UnaryOperator; - -@FunctionalInterface -public interface StringUnaryOperator extends UnaryOperator { - - @Deprecated(since = "6.0.3", forRemoval = true) - default String applyAsString(String s) { - return apply(s); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/ThrowableSupplier.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/ThrowableSupplier.java deleted file mode 100644 index 3b34a23f..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/ThrowableSupplier.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -import java.util.function.Supplier; - -@FunctionalInterface -public interface ThrowableSupplier { - - Supplier create(String message); - - @FunctionalInterface - interface Any extends ThrowableSupplier { - } - - - @FunctionalInterface - interface Error extends ThrowableSupplier { - } - - - @FunctionalInterface - interface Exception extends ThrowableSupplier { - } - - - @FunctionalInterface - interface RuntimeException extends ThrowableSupplier { - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/ToStringFunction.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/ToStringFunction.java index e70d9cf5..ff2816d0 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/ToStringFunction.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/function/ToStringFunction.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2022-2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/TriConsumer.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/TriConsumer.java deleted file mode 100644 index 5be3444d..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/TriConsumer.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -import java.util.Objects; - -@FunctionalInterface -public interface TriConsumer { - - void accept(T t, U u, V v); - - default TriConsumer andThen(TriConsumer after) { - Objects.requireNonNull(after); - return (t, u, v) -> { - accept(t, u, v); - after.accept(t, u, v); - }; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/VoidPredicate.java b/src/main/java/org/auioc/mcmod/arnicalib/base/function/VoidPredicate.java deleted file mode 100644 index 12be202d..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/VoidPredicate.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.function; - -@FunctionalInterface -public interface VoidPredicate { - - boolean test(); - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/holder/IObjectHolder.java b/src/main/java/org/auioc/mcmod/arnicalib/base/holder/IObjectHolder.java deleted file mode 100644 index 4c2459a2..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/holder/IObjectHolder.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.holder; - -public interface IObjectHolder { - - T get(); - - void set(T value); - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/holder/ObjectHolder.java b/src/main/java/org/auioc/mcmod/arnicalib/base/holder/ObjectHolder.java deleted file mode 100644 index 21c986c9..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/holder/ObjectHolder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.holder; - -public class ObjectHolder implements IObjectHolder { - - protected T value; - - public ObjectHolder(T value) { - this.value = value; - } - - @Override - public T get() { - return this.value; - } - - @Override - public void set(T value) { - this.value = value; - } - - @Override - public String toString() { - return super.toString() + "(" + this.value.toString() + ")"; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/log/LogUtil.java b/src/main/java/org/auioc/mcmod/arnicalib/base/log/LogUtil.java deleted file mode 100644 index 42b69bbe..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/log/LogUtil.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.log; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -public class LogUtil { - - private LogUtil() { } - - private static StackTraceElement getCaller() { - StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); - - StackTraceElement caller = null; - - String logClassName = LogUtil.class.getName(); - - int i = 0; - for (int len = callStack.length; i < len; i++) { - if (logClassName.equals(callStack[i].getClassName())) { - break; - } - } - - caller = callStack[i + 3]; - return caller; - } - - public static Logger getLoggerByCaller() { - return LogManager.getLogger(getCaller().getClassName()); - } - - public static Logger getLogger(String name) { - return LogManager.getLogger(name); - } - - public static Marker getMarker(String marker) { - return MarkerManager.getMarker(marker); - } - - public static Marker getMarker(Class clazz) { - return MarkerManager.getMarker(clazz.getSimpleName()); - } - - - public static void trace(Object msg) { - getLoggerByCaller().trace(msg); - } - - public static void debug(Object msg) { - getLoggerByCaller().debug(msg); - } - - public static void info(Object msg) { - getLoggerByCaller().info(msg); - } - - public static void warn(Object msg) { - getLoggerByCaller().warn(msg); - } - - public static void error(Object msg) { - getLoggerByCaller().error(msg); - } - - public static void error(Object msg, Throwable t) { - getLoggerByCaller().error(msg, t); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/math/MathUtil.java b/src/main/java/org/auioc/mcmod/arnicalib/base/math/MathUtil.java deleted file mode 100644 index 19d7bff5..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/math/MathUtil.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.math; - -import java.util.function.DoubleUnaryOperator; -import java.util.function.IntUnaryOperator; - -public class MathUtil { - - public static int sigma(int n, int m, IntUnaryOperator f) { - int r = 0; - for (int i = m, _n = n + 1; i < _n; ++i) r += f.applyAsInt(i); - return r; - } - - public static double sigma(int n, int m, DoubleUnaryOperator f) { - double r = 0.0D; - for (int i = m, _n = n + 1; i < _n; ++i) r += f.applyAsDouble((double) i); - return r; - } - - public static double log(double a, double n) { - return Math.log(n) / Math.log(a); - } - - public static double log2(double n) { - return log(2.0D, n); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/math/MathUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/math/MathUtils.java new file mode 100644 index 00000000..d521c573 --- /dev/null +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/math/MathUtils.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.base.math; + +import org.auioc.mcmod.arnicalib.base.function.IntToFloatFunction; + +import java.util.function.IntToDoubleFunction; +import java.util.function.IntUnaryOperator; + +public class MathUtils { + + /** + * @param n upper bound of the summation + * @param k lower bound of the summation + * @param f function to produce each term of the summation, the index is passed as parameter + */ + public static int sigma(int n, int k, IntUnaryOperator f) { + int r = 0; + for (int i = k, _n = n + 1; i < _n; ++i) r += f.applyAsInt(i); + return r; + } + + /** + * @param n upper bound of the summation + * @param k lower bound of the summation + * @param f function to produce each term of the summation, the index is passed as parameter + */ + public static double sigma(int n, int k, IntToDoubleFunction f) { + double r = 0.0D; + for (int i = k, _n = n + 1; i < _n; ++i) r += f.applyAsDouble(i); + return r; + } + + /** + * @param n upper bound of the summation + * @param k lower bound of the summation + * @param f function to produce each term of the summation, the index is passed as parameter + */ + public static float sigma(int n, int k, IntToFloatFunction f) { + float r = 0.0F; + for (int i = k, _n = n + 1; i < _n; ++i) r += f.applyAsFloat(i); + return r; + } + + /** + * @param a base + * @param n value + * @return the base-a logarithm of n + */ + public static double log(double a, double n) { + return Math.log(n) / Math.log(a); + } + + /** + * @param n value + * @return the binary logarithm of n + */ + public static double log2(double n) { + return log(2.0D, n); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumberUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumberUtils.java index bc375c3a..f2b8ba8e 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumberUtils.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumberUtils.java @@ -1,48 +1,49 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.math; - -public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils { - - public static String toBinaryString(int i, int s) { - return String.format("0b%" + s + "s", Integer.toBinaryString(i)).replace(" ", "0"); - } - - public static String toOctalString(int i, int s) { - return String.format("0o%" + s + "s", Integer.toOctalString(i)).replace(" ", "0"); - } - - public static String toHexString(int i, int s) { - return String.format("0x%" + s + "s", Integer.toHexString(i)).replace(" ", "0"); - } - - public static String toBinaryString(long i, int s) { - return String.format("0b%" + s + "s", Long.toBinaryString(i)).replace(" ", "0"); - } - - public static String toOctalString(long i, int s) { - return String.format("0o%" + s + "s", Long.toOctalString(i)).replace(" ", "0"); - } - - public static String toHexString(long i, int s) { - return String.format("0x%" + s + "s", Long.toHexString(i)).replace(" ", "0"); - } - -} +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.base.math; + +@SuppressWarnings("deprecation") +public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils { + + public static String toBinaryString(int i, int s) { + return String.format("0b%" + s + "s", Integer.toBinaryString(i)).replace(" ", "0"); + } + + public static String toOctalString(int i, int s) { + return String.format("0o%" + s + "s", Integer.toOctalString(i)).replace(" ", "0"); + } + + public static String toHexString(int i, int s) { + return String.format("0x%" + s + "s", Integer.toHexString(i)).replace(" ", "0"); + } + + public static String toBinaryString(long i, int s) { + return String.format("0b%" + s + "s", Long.toBinaryString(i)).replace(" ", "0"); + } + + public static String toOctalString(long i, int s) { + return String.format("0o%" + s + "s", Long.toOctalString(i)).replace(" ", "0"); + } + + public static String toHexString(long i, int s) { + return String.format("0x%" + s + "s", Long.toHexString(i)).replace(" ", "0"); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumeralUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumeralConverter.java similarity index 81% rename from src/main/java/org/auioc/mcmod/arnicalib/base/math/NumeralUtils.java rename to src/main/java/org/auioc/mcmod/arnicalib/base/math/NumeralConverter.java index a45a110e..da264ea8 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumeralUtils.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/math/NumeralConverter.java @@ -1,144 +1,150 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.math; - -import java.util.ArrayList; -import java.util.List; - -public class NumeralUtils { - - private static final int[] ROMAN_VALUES = { - /* */ 1000000000, - 900000000, 500000000, 400000000, 100000000, - 90000000, 50000000, 40000000, 10000000, - 9000000, 5000000, 4000000, 1000000, - 900000, 500000, 400000, 100000, - 90000, 50000, 40000, 10000, - 9000, 5000, 4000, 1000, - 900, 500, 400, 100, - 90, 50, 40, 10, - 9, 5, 4, 1 - }; - private static final String[] ROMAN_SYMBOLS = { - /* */ "M\u033F", - "C\u033FM\u033F", "D\u033F", "C\u033FD\u033F", "C\u033F", - "X\u033FC\u033F", "L\u033F", "X\u033FL\u033F", "X\u033F", - "MX\u033F", "V\u033F", "MV\u033F", "M\u0305", - "C\u0305M\u0305", "D\u0305", "C\u0305D\u0305", "C\u0305", - "X\u0305C\u0305", "L\u0305", "X\u0305L\u0305", "X\u0305", - "MX\u0305", "V\u0305", "MV\u0305", "M", - "CM", "D", "CD", "C", - "XC", "L", "XL", "X", - "IX", "V", "IV", "I" - }; - private static final String[] ROMAN_SYMBOLS_NO_OVERLINE = { - /* */ "M:", - "C:M:", "D:", "C:D:", "C:", - "X:C:", "L:", "X:L:", "X:", - "MX:", "V:", "MV:", "M.", - "C.M.", "D.", "C.D.", "C.", - "X.C.", "L.", "X.L.", "X.", - "MX.", "V.", "MV.", "M", - "CM", "D", "CD", "C", - "XC", "L", "XL", "X", - "IX", "V", "IV", "I" - }; - - public static String toRoman(int n, boolean noOverline) { - if (n == 0) return "N"; - n = Math.abs(n); - var sb = new StringBuilder(); - int i = 0; - while (i < ROMAN_VALUES.length) { - while (n >= ROMAN_VALUES[i]) { - sb.append(noOverline ? ROMAN_SYMBOLS_NO_OVERLINE[i] : ROMAN_SYMBOLS[i]); - n -= ROMAN_VALUES[i]; - } - i++; - } - return sb.toString(); - } - - // ============================================================================================================== // - - private static final String[] CHINESE_NUMBERS_SMALL = {"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; - private static final String[] CHINESE_NUMBERS_BIG = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; - private static final String[] CHINESE_UNITS_SMALL = {"", "十", "百", "千", "万", "亿"}; - private static final String[] CHINESE_UNITS_BIG = {"", "拾", "佰", "仟", "萬", "億"}; - private static final String CHINESE_NEGATIVE_PREFIX = "负"; - - private static List toChinese(int n) { - var a = new ArrayList(); - int i = 0; - while (n > 0) { - int s = n % 10000; - n /= 10000; - if (i > 0) { - a.add(i + 10 + 3); - } - a.addAll(sectionToChinese(s)); - if (n > 0 && s < 1000) { - a.add(0); - } - i++; - } - return a; - } - - private static List sectionToChinese(int n) { - var a = new ArrayList(); - boolean f = true; - int i = 0; - while (n > 0) { - int v = n % 10; - n /= 10; - if (v == 0) { - if (!f) { - a.add(v); - f = true; - } - } else { - a.add(i + 10); - a.add(v); - f = false; - } - i++; - } - return a; - } - - public static String toChinese(int n, boolean big) { - var sb = new StringBuilder(); - if (n < 0) { - sb.append(CHINESE_NEGATIVE_PREFIX); - } - var a = toChinese(Math.absExact(n)); - for (int i = a.size() - 1; i >= 0; --i) { - int v = a.get(i); - if (v > 9) { - sb.append(big ? CHINESE_UNITS_BIG[v - 10] : CHINESE_UNITS_SMALL[v - 10]); - } else { - sb.append(big ? CHINESE_NUMBERS_BIG[v] : CHINESE_NUMBERS_SMALL[v]); - } - } - return sb.toString(); - } - -} +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.base.math; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author WakelessSloth56 + * @version 1.0.1 + * @see Gist: RomanNumberConverter.java + * @see Gist: ChineseNumberConverter.java + */ +public class NumeralConverter { + + private static final int[] ROMAN_VALUES = { + /* */ 1000000000, + 900000000, 500000000, 400000000, 100000000, + 90000000, 50000000, 40000000, 10000000, + 9000000, 5000000, 4000000, 1000000, + 900000, 500000, 400000, 100000, + 90000, 50000, 40000, 10000, + 9000, 5000, 4000, 1000, + 900, 500, 400, 100, + 90, 50, 40, 10, + 9, 5, 4, 1 + }; + private static final String[] ROMAN_SYMBOLS = { + /* */ "M\u033F", + "C\u033FM\u033F", "D\u033F", "C\u033FD\u033F", "C\u033F", + "X\u033FC\u033F", "L\u033F", "X\u033FL\u033F", "X\u033F", + "MX\u033F", "V\u033F", "MV\u033F", "M\u0305", + "C\u0305M\u0305", "D\u0305", "C\u0305D\u0305", "C\u0305", + "X\u0305C\u0305", "L\u0305", "X\u0305L\u0305", "X\u0305", + "MX\u0305", "V\u0305", "MV\u0305", "M", + "CM", "D", "CD", "C", + "XC", "L", "XL", "X", + "IX", "V", "IV", "I" + }; + private static final String[] ROMAN_SYMBOLS_NO_OVERLINE = { + /* */ "M:", + "C:M:", "D:", "C:D:", "C:", + "X:C:", "L:", "X:L:", "X:", + "MX:", "V:", "MV:", "M.", + "C.M.", "D.", "C.D.", "C.", + "X.C.", "L.", "X.L.", "X.", + "MX.", "V.", "MV.", "M", + "CM", "D", "CD", "C", + "XC", "L", "XL", "X", + "IX", "V", "IV", "I" + }; + + public static String toRoman(int n, boolean noOverline) { + if (n == 0) return "N"; + n = Math.abs(n); + var sb = new StringBuilder(); + int i = 0; + while (i < ROMAN_VALUES.length) { + while (n >= ROMAN_VALUES[i]) { + sb.append(noOverline ? ROMAN_SYMBOLS_NO_OVERLINE[i] : ROMAN_SYMBOLS[i]); + n -= ROMAN_VALUES[i]; + } + i++; + } + return sb.toString(); + } + + // ============================================================================================================== // + + private static final String[] CHINESE_NUMBERS_SMALL = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" }; + private static final String[] CHINESE_NUMBERS_BIG = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; + private static final String[] CHINESE_UNITS_SMALL = { "", "十", "百", "千", "万", "亿" }; + private static final String[] CHINESE_UNITS_BIG = { "", "拾", "佰", "仟", "萬", "億" }; + private static final String CHINESE_NEGATIVE_PREFIX = "负"; + + private static List toChinese(int n) { + var a = new ArrayList(); + int i = 0; + while (n > 0) { + int s = n % 10000; + n /= 10000; + if (i > 0) { + a.add(i + 10 + 3); + } + a.addAll(sectionToChinese(s)); + if (n > 0 && s < 1000) { + a.add(0); + } + i++; + } + return a; + } + + private static List sectionToChinese(int n) { + var a = new ArrayList(); + boolean f = true; + int i = 0; + while (n > 0) { + int v = n % 10; + n /= 10; + if (v == 0) { + if (!f) { + a.add(v); + f = true; + } + } else { + a.add(i + 10); + a.add(v); + f = false; + } + i++; + } + return a; + } + + public static String toChinese(int n, boolean big) { + var sb = new StringBuilder(); + if (n < 0) { + sb.append(CHINESE_NEGATIVE_PREFIX); + } + var a = toChinese(Math.absExact(n)); + for (int i = a.size() - 1; i >= 0; --i) { + int v = a.get(i); + if (v > 9) { + sb.append(big ? CHINESE_UNITS_BIG[v - 10] : CHINESE_UNITS_SMALL[v - 10]); + } else { + sb.append(big ? CHINESE_NUMBERS_BIG[v] : CHINESE_NUMBERS_SMALL[v]); + } + } + return sb.toString(); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/holder/LazyObjectHolder.java b/src/main/java/org/auioc/mcmod/arnicalib/base/math/RandomUtils.java similarity index 53% rename from src/main/java/org/auioc/mcmod/arnicalib/base/holder/LazyObjectHolder.java rename to src/main/java/org/auioc/mcmod/arnicalib/base/math/RandomUtils.java index 3a60b151..0546b9b6 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/holder/LazyObjectHolder.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/math/RandomUtils.java @@ -1,49 +1,42 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.holder; - -import java.util.function.Supplier; -import javax.annotation.Nullable; - -public class LazyObjectHolder implements IObjectHolder { - - private final Supplier supplier; - @Nullable - private T resolved; - - public LazyObjectHolder(Supplier supplier) { - this.supplier = supplier; - } - - @Override - @Nullable - public T get() { - if (this.resolved == null) { - this.resolved = this.supplier.get(); - } - return this.resolved; - } - - @Override - public void set(T value) { - throw new UnsupportedOperationException(); - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.base.math; + +import java.util.concurrent.atomic.AtomicLong; + +public class RandomUtils { + + private static final AtomicLong seedUniquifier = new AtomicLong(9311145141919810L); + + private static long seedUniquifier() { + for (; ; ) { + long current = seedUniquifier.get(); + long next = current * 1181783497276652981L; + if (seedUniquifier.compareAndSet(current, next)) { + return next; + } + } + } + + public static long uniqueSeed() { + return seedUniquifier() ^ System.nanoTime(); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/network/AddressUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/network/AddressUtils.java deleted file mode 100644 index e1b1d980..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/network/AddressUtils.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.network; - -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; - -import javax.annotation.Nullable; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public interface AddressUtils { - - Marker MARKER = LogUtil.getMarker(AddressUtils.class); - - @Nullable - static InetAddress toInetAddress(String addr) { - try { - return InetAddress.getByName(addr); - } catch (UnknownHostException e) { - LOGGER.error(MARKER, "", e); - return null; - } - } - - static boolean isLocalAddress(InetAddress addr) { - return addr.isLoopbackAddress() || addr.isAnyLocalAddress() || addr.isLinkLocalAddress(); - } - - static boolean isLocalAddress(String addr) { - if (addr.contains("local:E:")) { - return true; - } - return isLocalAddress(toInetAddress(addr)); - - } - - static boolean isLanAddress(InetAddress addr) { - return addr.isSiteLocalAddress(); - } - - static boolean isLanAddress(String addr) { - if (addr.contains("local:E:")) { - return true; - } - return isLanAddress(toInetAddress(addr)); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/network/HttpUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/network/HttpUtils.java deleted file mode 100644 index 304aae4d..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/network/HttpUtils.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.network; - -import java.io.IOException; - -import org.apache.http.HttpEntity; -import org.apache.http.ParseException; -import org.apache.http.StatusLine; -import org.apache.http.client.HttpResponseException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; - -public interface HttpUtils { - - static String get(String url) throws IOException, ParseException { - String result; - - CloseableHttpClient client = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet(url); - CloseableHttpResponse response = null; - - try { - response = client.execute(httpGet); - StatusLine statusLine = response.getStatusLine(); - - if (statusLine.getStatusCode() != 200) { - throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); - } - HttpEntity httpEntity = response.getEntity(); - result = EntityUtils.toString(httpEntity); - } catch (Exception e) { - throw e; - } finally { - try { - if (response != null) { - response.close(); - } - if (client != null) { - client.close(); - } - } catch (IOException e) { - throw e; - } - } - - return result; - } - - static JsonElement getJson(String url) throws JsonSyntaxException, ParseException, IOException { - return JsonParser.parseString(get(url)); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/phys/PlaneAlignment.java b/src/main/java/org/auioc/mcmod/arnicalib/base/phys/PlaneAlignment.java deleted file mode 100644 index 79978902..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/phys/PlaneAlignment.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.phys; - -public enum PlaneAlignment { - - TOP_LEFT, TOP_CENTER, TOP_RIGHT, - CENTER_LEFT, CENTER, CENTER_RIGHT, - BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/phys/Shape.java b/src/main/java/org/auioc/mcmod/arnicalib/base/phys/Shape.java deleted file mode 100644 index 9570c96b..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/phys/Shape.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.phys; - -public enum Shape { - LINE, // - POLYGON, CIRCLE, // - CUBOID, SPHERE, // - - START_POLYGON -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/random/RandomUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/random/RandomUtils.java deleted file mode 100644 index 27495991..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/random/RandomUtils.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.random; - -import org.auioc.mcmod.arnicalib.base.validate.Validate; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; - -public class RandomUtils { - - private static final AtomicLong seedUniquifier = new AtomicLong(9311145141919810L); - - private static long seedUniquifier() { - for (; ; ) { - long current = seedUniquifier.get(); - long next = current * 1181783497276652981L; - if (seedUniquifier.compareAndSet(current, next)) { - return next; - } - } - } - - public static long uniqueSeed() { - return seedUniquifier() ^ System.nanoTime(); - } - - // ============================================================================================================== // - - public static final Random RANDOM = new Random(); - - // ============================================================================================================== // - // #region PickFromCollection - - public static T pickOneFromCollection(Collection collection) { - Validate.notEmpty(collection, "The collection must be not empty"); - - int size = collection.size(); - int target = RANDOM.nextInt(size); - Iterator iterator = collection.iterator(); - for (int i = 0; i < target; i++) { - iterator.next(); - } - T result = iterator.next(); - - return result; - } - - public static List pickFromList(List list, int N, boolean allowRepetitions) { - Validate.notEmpty(list, "The list must be not empty"); - - int size = list.size(); - - Validate.isPositive(N, "The number of needed elements must be positive"); - Validate.isTrue(size > N, "The number of needed elements must be smaller or equal to the list size"); - - if (size == N) { - return list; - } - - List newList = new ArrayList(); - - if (N == 1) { - newList.add(pickOneFromList(list, size)); - } else { - if (allowRepetitions) { - for (int i = 0; i < N; i++) { - newList.add(pickOneFromList(list, size)); - } - } else { - List targets = new ArrayList(); - for (int i = 0; i < N; i++) { - int target; - while (true) { - target = RANDOM.nextInt(size); - if (!targets.contains(target)) { - targets.add(target); - break; - } - } - newList.add(list.get(target)); - } - } - } - - return newList; - } - - public static List pickFromList(List list, int N) { - return pickFromList(list, N, false); - } - - public static T pickOneFromList(List list) { - Validate.notEmpty(list, "The list must be not empty"); - return list.get(RANDOM.nextInt(list.size())); - } - - private static T pickOneFromList(List list, int size) { - return list.get(RANDOM.nextInt(size)); - } - - // #endregion PickFromCollection - - // ============================================================================================================== // - // #region Chance - - public static boolean percentageChance(int chance) { - Validate.isInCloseInterval(0, 100, chance); - return RANDOM.nextInt(100) < chance; - } - - public static boolean percentageChance(int chance, Random random) { - Validate.isInCloseInterval(0, 100, chance); - return random.nextInt(100) < chance; - } - - public static boolean fractionChance(int denominator) { - Validate.isPositive(denominator); - return RANDOM.nextInt(denominator) == 0; - } - - public static boolean fractionChance(int denominator, Random random) { - Validate.isPositive(denominator); - return random.nextInt(denominator) == 0; - } - - public static boolean fractionChance(int numerator, int denominator) { - Validate.isFractionChance(numerator, denominator); - return RANDOM.nextInt(denominator) < numerator; - } - - public static boolean fractionChance(int numerator, int denominator, Random random) { - Validate.isFractionChance(numerator, denominator); - return random.nextInt(denominator) < numerator; - } - - // #endregion Chance - - // ============================================================================================================== // - // #region Signum - - public static int nextSignum() { - return RANDOM.nextBoolean() ? 1 : -1; - } - - public static int nextSignum(Random random) { - return random.nextBoolean() ? 1 : -1; - } - - // #endregion Signum - - // ============================================================================================================== // - // #region Offset - - public static int offset(int bound, Random random) { - return random.nextInt(bound) * nextSignum(random); - } - - public static long offset(long bound, Random random) { - return random.nextLong(bound) * nextSignum(random); - } - - public static float offset(float bound, Random random) { - return random.nextFloat(bound) * nextSignum(random); - } - - public static double offset(double bound, Random random) { - return random.nextDouble(bound) * nextSignum(random); - } - - public static int offset(int bound) { - return RANDOM.nextInt(bound) * nextSignum(); - } - - public static long offset(long bound) { - return RANDOM.nextLong(bound) * nextSignum(); - } - - public static float offset(float bound) { - return RANDOM.nextFloat(bound) * nextSignum(); - } - - public static double offset(double bound) { - return RANDOM.nextDouble(bound) * nextSignum(); - } - - // #endregion Offset - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/reflection/ReflectionUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/reflection/ReflectionUtils.java index f29d2906..9dd2f8c2 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/reflection/ReflectionUtils.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/reflection/ReflectionUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2023-2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * @@ -27,6 +27,9 @@ import java.util.Map; import java.util.Optional; +/** + * @since 5.7.3 + */ public class ReflectionUtils { public static Optional getFieldValue(Object object, Field field, Class type) { diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/word/WordUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/base/text/WordUtils.java similarity index 90% rename from src/main/java/org/auioc/mcmod/arnicalib/base/word/WordUtils.java rename to src/main/java/org/auioc/mcmod/arnicalib/base/text/WordUtils.java index e18342b0..69353f7a 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/word/WordUtils.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/base/text/WordUtils.java @@ -1,35 +1,35 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.word; - -import java.util.regex.Pattern; - -@SuppressWarnings("deprecation") -public class WordUtils extends org.apache.commons.lang3.text.WordUtils { - - public static String toSnakeCase(String str) { - return str.replaceAll("[A-Z]", "_$0").toLowerCase(); - } - - public static String toCamelCase(String str) { - return Pattern.compile("_([a-z])").matcher(str).replaceAll(m -> m.group(1).toUpperCase()); - } - -} +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.base.text; + +import java.util.regex.Pattern; + +@SuppressWarnings("deprecation") +public class WordUtils extends org.apache.commons.lang3.text.WordUtils { + + public static String toSnakeCase(String str) { + return str.replaceAll("[A-Z]", "_$0").toLowerCase(); + } + + public static String toCamelCase(String str) { + return Pattern.compile("_([a-z])").matcher(str).replaceAll(m -> m.group(1).toUpperCase()); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/tuple/IntPair.java b/src/main/java/org/auioc/mcmod/arnicalib/base/tuple/IntPair.java deleted file mode 100644 index 87002d84..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/tuple/IntPair.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.tuple; - -public record IntPair(int x, int y) { - - // TODO mutable - - @Override - public String toString() { - return "(" + x + "," + y + ")"; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj instanceof IntPair other) { - return (x == other.x()) && (y == other.y()); - } - return false; - } - - @Override - public int hashCode() { return (x * 17) + y; } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/tuple/IntTriple.java b/src/main/java/org/auioc/mcmod/arnicalib/base/tuple/IntTriple.java deleted file mode 100644 index 267d7de8..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/tuple/IntTriple.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.tuple; - -public record IntTriple(int x, int y, int z) { - - // TODO mutable - - @Override - public String toString() { - return "(" + x + "," + y + "," + z + ")"; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj instanceof IntTriple other) { - return (x == other.x()) && (y == other.y()) && (z == other.z()); - } - return false; - } - - @Override - public int hashCode() { return (x * 17) + (y * 17) + z; } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/validate/Validate.java b/src/main/java/org/auioc/mcmod/arnicalib/base/validate/Validate.java deleted file mode 100644 index 72706f5a..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/validate/Validate.java +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.base.validate; - -import com.google.common.collect.Range; - -public class Validate extends org.apache.commons.lang3.Validate { - - // ============================================================================================================== // - // #region ThrowException - - public static void throwException(String message) { - throw new IllegalArgumentException(message); - } - - public static void throwException(String message, Object... objects) { - throw new IllegalArgumentException(String.format(message, objects)); - } - - // #endregion ThrowException - - // ============================================================================================================== // - // #region CompareToZero - - private static final String NOT_POSITIVE_MESSAGE = "The value must be positive: %s"; - private static final String NOT_NEGATIVE_MESSAGE = "The value must be negative: %s"; - private static final String NOT_NON_NEGATIVE_MESSAGE = "The value must be non-negative: %s"; - private static final String NOT_NON_POSITIVE_MESSAGE = "The value must be non-positive: %s"; - - public static void isPositive(long value, String message) { - isTrue(value > 0, message); - } - - public static void isNonNegative(long value, String message) { - isTrue(value >= 0, message); - } - - public static void isNegative(long value, String message) { - isTrue(value < 0, message); - } - - public static void isNonPositive(long value, String message) { - isTrue(value <= 0, message); - } - - /*========================================================================*/ - - public static void isPositive(double value, String message) { - isTrue(value > 0, message); - } - - public static void isNonNegative(double value, String message) { - isTrue(value >= 0, message); - } - - public static void isNegative(double value, String message) { - isTrue(value < 0, message); - } - - public static void isNonPositive(double value, String message) { - isTrue(value <= 0, message); - } - - /*========================================================================*/ - - public static void isPositive(long value) { - isTrue(value > 0, NOT_POSITIVE_MESSAGE, value); - } - - public static void isNonNegative(long value) { - isTrue(value >= 0, NOT_NON_NEGATIVE_MESSAGE, value); - } - - public static void isNegative(long value) { - isTrue(value < 0, NOT_NEGATIVE_MESSAGE, value); - } - - public static void isNonPositive(long value) { - isTrue(value <= 0, NOT_NON_POSITIVE_MESSAGE, value); - } - - /*========================================================================*/ - - public static void isPositive(double value) { - isTrue(value > 0, NOT_POSITIVE_MESSAGE, value); - } - - public static void isNonNegative(double value) { - isTrue(value >= 0, NOT_NON_NEGATIVE_MESSAGE, value); - } - - public static void isNegative(double value) { - isTrue(value < 0, NOT_NEGATIVE_MESSAGE, value); - } - - public static void isNonPositive(double value) { - isTrue(value <= 0, NOT_NON_POSITIVE_MESSAGE, value); - } - - // #endregion CompareToZero - - // ============================================================================================================== // - // #region Interval - - private static final String INVALID_INTERVAL_MESSAGE = "The left bound must be less than the right bound"; - private static final String NOT_IN_INTERVAL_MESSAGE = "The value %s is not in the interval %s"; - private static final String NOT_IN_OPEN_INTERVAL_MESSAGE = "The value %s is not in the interval (%s, %s)"; - private static final String NOT_IN_CLOSED_INTERVAL_MESSAGE = "The value %s is not in the interval [%s, %s]"; - private static final String NOT_IN_OPEN_CLOSED_INTERVAL_MESSAGE = "The value %s is not in the interval (%s, %s]"; - private static final String NOT_IN_CLOSED_OPEN_INTERVAL_MESSAGE = "The value %s is not in the interval [%s, %s)"; - private static final String NOT_IN_LEFT_OPEN_INTERVAL_MESSAGE = "The value %s is not in the interval (%s, +∞)"; - private static final String NOT_IN_LEFT_CLOSED_INTERVAL_MESSAGE = "The value %s is not in the interval [%s, +∞)"; - private static final String NOT_IN_RIGHT_OPEN_INTERVAL_MESSAGE = "The value %s is not in the interval (-∞, %s)"; - private static final String NOT_IN_RIGHT_CLOSED_INTERVAL_MESSAGE = "The value %s is not in the interval (-∞, %s]"; - - /** - * Validate that the specified primitive value is in the specified interval; otherwise, throws an exception. - * - * @param interval - * @param value the value to validate - * @param message the exception message if invalid - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInInterval(Range, double, String) - */ - public static void isInInterval(Range interval, long value, String message) { - isTrue(interval.contains(value), message + String.format(NOT_IN_INTERVAL_MESSAGE, value, interval)); - } - - /** - * @see #isInInterval(Range, long, String) - */ - public static void isInInterval(Range interval, double value, String message) { - isTrue(interval.contains(value), message + String.format(NOT_IN_INTERVAL_MESSAGE, value, interval)); - } - - /*========================================================================*/ - - /** - * Validate that the specified bounds are valid the interval bounds; otherwise, throws an exception. - * - * @param left the interval left bound - * @param right the interval right bound - */ - public static void isBoundedInterval(long left, long right) { - isTrue(left < right, INVALID_INTERVAL_MESSAGE); - } - - - /** - * @see #isBoundedInterval(long, long) - */ - public static void isBoundedInterval(double left, double right) { - isTrue(left < right, INVALID_INTERVAL_MESSAGE); - } - - - /*========================================================================*/ - - /** - * Validate that the specified primitive value is in the interval (left, right); otherwise, throws an exception. - * - * @param left the interval left bound - * @param right the interval right bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInOpenInterval(double, double, double) - */ - public static void isInOpenInterval(long left, long right, long value) { - isBoundedInterval(left, right); - isTrue(value > left && value < right, NOT_IN_OPEN_INTERVAL_MESSAGE, value, left, right); - } - - /** - * Validate that the specified primitive value is in the interval [left, right]; otherwise, throws an exception. - * - * @param left the interval left bound - * @param right the interval right bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInCloseInterval(double, double, double) - */ - public static void isInCloseInterval(long left, long right, long value) { - isBoundedInterval(left, right); - isTrue(value >= left && value <= right, NOT_IN_CLOSED_INTERVAL_MESSAGE, value, left, right); - } - - /** - * Validate that the specified primitive value is in the interval (left, right]; otherwise, throws an exception. - * - * @param left the interval left bound - * @param right the interval right bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInOpenCloseInterval(double, double, double) - */ - public static void isInOpenCloseInterval(long left, long right, long value) { - isBoundedInterval(left, right); - isTrue(value > left && value <= right, NOT_IN_OPEN_CLOSED_INTERVAL_MESSAGE, value, left, right); - } - - /** - * Validate that the specified primitive value is in the interval [left, right); otherwise, throws an exception. - * - * @param left the interval left bound - * @param right the interval right bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInCloseOpenInterval(double, double, double) - */ - public static void isInCloseOpenInterval(long left, long right, long value) { - isBoundedInterval(left, right); - isTrue(value >= left && value < right, NOT_IN_CLOSED_OPEN_INTERVAL_MESSAGE, value, left, right); - } - - /** - * Validate that the specified primitive value is in the interval (left, +∞); otherwise, throws an exception. - * - * @param left the interval left bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInLeftOpenInterval(double, double) - */ - public static void isInLeftOpenInterval(long left, long value) { - isTrue(value > left, NOT_IN_LEFT_OPEN_INTERVAL_MESSAGE, value, left); - } - - /** - * Validate that the specified primitive value is in the interval [left, +∞); otherwise, throws an exception. - * - * @param left the interval left bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInLeftClosedInterval(double, double) - */ - public static void isInLeftClosedInterval(long left, long value) { - isTrue(value >= left, NOT_IN_LEFT_CLOSED_INTERVAL_MESSAGE, value, left); - } - - /** - * Validate that the specified primitive value is in the interval (-∞, right); otherwise, throws an exception. - * - * @param right the interval left bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInRightOpenInterval(double, double) - */ - public static void isInRightOpenInterval(long right, long value) { - isTrue(value < right, NOT_IN_RIGHT_OPEN_INTERVAL_MESSAGE, value, right); - } - - /** - * Validate that the specified primitive value is in the interval (-∞, right]; otherwise, throws an exception. - * - * @param right the interval left bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInRightClosedInterval(double, double) - */ - public static void isInRightClosedInterval(long right, long value) { - isTrue(value <= right, NOT_IN_RIGHT_CLOSED_INTERVAL_MESSAGE, value, right); - } - - /** - * Validate that the specified primitive value is in the interval (right, left); it always throws an exception. - * - * @param left the interval left bound - * @param right the interval right bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInEmptyInterval(double, double, double) - */ - public static void isInEmptyInterval(long left, long right, long value) { - isBoundedInterval(left, right); - isTrue(false, NOT_IN_OPEN_INTERVAL_MESSAGE, value, right, left); - } - - /** - * Validate that the specified primitive value is in the interval [bound, bound]; otherwise, throws an exception. - * - * @param bound the interval bound - * @param value the value to validate - * @throws IllegalArgumentException if the value is not in the interval - * @see #isInDegenerateInterval(double, double) - */ - public static void isInDegenerateInterval(long bound, long value) { - isTrue(value == bound, NOT_IN_CLOSED_INTERVAL_MESSAGE, value, bound, bound); - } - - - /** - * Validate that the specified primitive value is in the interval (-∞, +∞); it never throws an exception. - * - * @param value the value to validate - * @see #isInUnboundedInterval(double) - */ - public static void isInUnboundedInterval(long value) { } - - /*========================================================================*/ - - /** - * @see #isInOpenInterval(long, long, long) - */ - public static void isInOpenInterval(double left, double right, double value) { - isBoundedInterval(left, right); - isTrue(value > left && value < right, NOT_IN_OPEN_INTERVAL_MESSAGE, value, left, right); - } - - /** - * @see #isInCloseInterval(long, long, long) - */ - public static void isInCloseInterval(double left, double right, double value) { - isBoundedInterval(left, right); - isTrue(value >= left && value <= right, NOT_IN_CLOSED_INTERVAL_MESSAGE, value, left, right); - } - - /** - * @see #isInOpenCloseInterval(long, long, long) - */ - public static void isInOpenCloseInterval(double left, double right, double value) { - isBoundedInterval(left, right); - isTrue(value > left && value <= right, NOT_IN_OPEN_CLOSED_INTERVAL_MESSAGE, value, left, right); - } - - /** - * @see #isInCloseOpenInterval(long, long, long) - */ - public static void isInCloseOpenInterval(double left, double right, double value) { - isBoundedInterval(left, right); - isTrue(value >= left && value < right, NOT_IN_CLOSED_OPEN_INTERVAL_MESSAGE, value, left, right); - } - - /** - * @see #isInLeftOpenInterval(long, long) - */ - public static void isInLeftOpenInterval(double left, double value) { - isTrue(value > left, NOT_IN_LEFT_OPEN_INTERVAL_MESSAGE, value, left); - } - - /** - * @see #isInLeftClosedInterval(long, long) - */ - public static void isInLeftClosedInterval(double left, double value) { - isTrue(value >= left, NOT_IN_LEFT_CLOSED_INTERVAL_MESSAGE, value, left); - } - - /** - * @see #isInRightOpenInterval(long, long) - */ - public static void isInRightOpenInterval(double right, double value) { - isTrue(value < right, NOT_IN_RIGHT_OPEN_INTERVAL_MESSAGE, value, right); - } - - /** - * @see #isInRightClosedInterval(long, long) - */ - public static void isInRightClosedInterval(double right, double value) { - isTrue(value <= right, NOT_IN_RIGHT_CLOSED_INTERVAL_MESSAGE, value, right); - } - - /** - * @see #isInEmptyInterval(long, long, long) - */ - public static void isInEmptyInterval(double left, double right, double value) { - isBoundedInterval(left, right); - isTrue(false, NOT_IN_OPEN_INTERVAL_MESSAGE, value, right, left); - } - - /** - * @see #isInDegenerateInterval(long, long) - */ - public static void isInDegenerateInterval(double bound, double value) { - isTrue(value == bound, NOT_IN_CLOSED_INTERVAL_MESSAGE, value, bound, bound); - } - - - /** - * @see #isInUnboundedInterval(long) - */ - public static void isInUnboundedInterval(double value) { } - - // #endregion Interval - - // ============================================================================================================== // - // #region Fraction - - private static final String INVALID_FRACTION_MESSAGE = "The denominator must not be zero"; - private static final String NOT_A_PROPER_FRACTION_MESSAGE = "%s/%s is not a proper fraction"; - private static final String NOT_A_IMPROPER_FRACTION_MESSAGE = "%s/%s is not a improper fraction"; - private static final String NOT_A_UNIT_FRACTION_MESSAGE = "%s/%s is not a unit fraction"; - private static final String INVALID_FRACTION_CHANCE = "%s/%s is not a valid fraction chance value"; - - public static void isFraction(long numerator, long denominator) { - isTrue(denominator != 0, INVALID_FRACTION_MESSAGE); - } - - public static void isProperFraction(long numerator, long denominator) { - isFraction(numerator, denominator); - isTrue(numerator > 0 && denominator > 0, NOT_A_PROPER_FRACTION_MESSAGE, numerator, denominator); - isTrue(numerator < denominator, NOT_A_PROPER_FRACTION_MESSAGE, numerator, denominator); - } - - public static void isImproperFraction(long numerator, long denominator) { - isFraction(numerator, denominator); - isTrue(Math.abs(numerator / denominator) >= 1, NOT_A_IMPROPER_FRACTION_MESSAGE, numerator, denominator); - } - - public static void isUnitFraction(long numerator, long denominator) { - isProperFraction(numerator, denominator); - isTrue(numerator == 1, NOT_A_UNIT_FRACTION_MESSAGE, numerator, denominator); - } - - public static void isFractionChance(long numerator, long denominator) { - isFraction(numerator, denominator); - isTrue(numerator >= 0 && denominator > 0 && numerator <= denominator, INVALID_FRACTION_CHANCE, numerator, denominator); - } - - // #endregion ProperFraction - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/advancement/DisplayInfoBuilder.java b/src/main/java/org/auioc/mcmod/arnicalib/game/advancement/DisplayInfoBuilder.java index ff52e07a..fe2678a8 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/advancement/DisplayInfoBuilder.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/advancement/DisplayInfoBuilder.java @@ -1,131 +1,132 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.advancement; - -import net.minecraft.advancements.AdvancementType; -import net.minecraft.advancements.DisplayInfo; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.ItemLike; - -import javax.annotation.Nullable; -import java.util.Optional; - -public class DisplayInfoBuilder { - - private Component title = Component.literal("advancement"); - private Component description = Component.literal("advancement.description"); - private ItemStack icon = ItemStack.EMPTY; - @Nullable - private ResourceLocation background = null; - private AdvancementType frame = AdvancementType.TASK; - private boolean showToast = false; - private boolean announceChat = false; - private boolean hidden = false; - - public DisplayInfoBuilder() { } - - public DisplayInfo build() { - return new DisplayInfo(icon, title, description, Optional.ofNullable(background), frame, showToast, hidden, announceChat); - } - - public DisplayInfoBuilder title(Component title) { - this.title = title; - return this; - } - - public DisplayInfoBuilder title(String key) { - title(Component.translatable(key)); - return this; - } - - public DisplayInfoBuilder description(Component description) { - this.description = description; - return this; - } - - public DisplayInfoBuilder description(String key) { - description(Component.translatable(key)); - return this; - } - - public DisplayInfoBuilder titleAndDescription(String key) { - title(key); - description(key + ".description"); - return this; - } - - public DisplayInfoBuilder icon(ItemStack icon) { - this.icon = icon; - return this; - } - - public DisplayInfoBuilder icon(ItemLike icon) { - icon(new ItemStack(icon.asItem())); - return this; - } - - public DisplayInfoBuilder background(ResourceLocation background) { - this.background = background; - return this; - } - - public DisplayInfoBuilder background(String background) { - background(new ResourceLocation(background)); - return this; - } - - public DisplayInfoBuilder frame(AdvancementType frame) { - this.frame = frame; - return this; - } - - public DisplayInfoBuilder taskFrame() { - frame(AdvancementType.TASK); - return this; - } - - public DisplayInfoBuilder challengeFrame() { - frame(AdvancementType.CHALLENGE); - return this; - } - - public DisplayInfoBuilder goalFrame() { - frame(AdvancementType.GOAL); - return this; - } - - public DisplayInfoBuilder showToast() { - this.showToast = true; - return this; - } - - public DisplayInfoBuilder announceChat() { - this.announceChat = true; - return this; - } - - public DisplayInfoBuilder hidden() { - this.hidden = true; - return this; - } - -} +/* + * Copyright (C) 2022-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.advancement; + + +import net.minecraft.advancements.AdvancementType; +import net.minecraft.advancements.DisplayInfo; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ItemLike; + +import javax.annotation.Nullable; +import java.util.Optional; + +public class DisplayInfoBuilder { + + private Component title = Component.literal("advancement"); + private Component description = Component.literal("advancement.description"); + private ItemStack icon = ItemStack.EMPTY; + @Nullable + private ResourceLocation background = null; + private AdvancementType frame = AdvancementType.TASK; + private boolean showToast = false; + private boolean announceChat = false; + private boolean hidden = false; + + public DisplayInfoBuilder() { } + + public DisplayInfo build() { + return new DisplayInfo(icon, title, description, Optional.ofNullable(background), frame, showToast, hidden, announceChat); + } + + public DisplayInfoBuilder title(Component title) { + this.title = title; + return this; + } + + public DisplayInfoBuilder title(String key) { + title(Component.translatable(key)); + return this; + } + + public DisplayInfoBuilder description(Component description) { + this.description = description; + return this; + } + + public DisplayInfoBuilder description(String key) { + description(Component.translatable(key)); + return this; + } + + public DisplayInfoBuilder titleAndDescription(String key) { + title(key); + description(key + ".description"); + return this; + } + + public DisplayInfoBuilder icon(ItemStack icon) { + this.icon = icon; + return this; + } + + public DisplayInfoBuilder icon(ItemLike icon) { + icon(new ItemStack(icon.asItem())); + return this; + } + + public DisplayInfoBuilder background(ResourceLocation background) { + this.background = background; + return this; + } + + public DisplayInfoBuilder background(String background) { + background(ResourceLocation.parse(background)); + return this; + } + + public DisplayInfoBuilder frame(AdvancementType frame) { + this.frame = frame; + return this; + } + + public DisplayInfoBuilder taskFrame() { + frame(AdvancementType.TASK); + return this; + } + + public DisplayInfoBuilder challengeFrame() { + frame(AdvancementType.CHALLENGE); + return this; + } + + public DisplayInfoBuilder goalFrame() { + frame(AdvancementType.GOAL); + return this; + } + + public DisplayInfoBuilder showToast() { + this.showToast = true; + return this; + } + + public DisplayInfoBuilder announceChat() { + this.announceChat = true; + return this; + } + + public DisplayInfoBuilder hidden() { + this.hidden = true; + return this; + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/block/BlockUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/block/BlockUtils.java deleted file mode 100644 index e39b56d3..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/block/BlockUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.block; - -import net.minecraft.world.level.block.state.BlockState; - -public class BlockUtils { - - @SuppressWarnings("deprecation") - public static boolean canStandOn(BlockState blockStats) { - return blockStats.blocksMotion(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/chat/MessageHelper.java b/src/main/java/org/auioc/mcmod/arnicalib/game/chat/MessageHelper.java deleted file mode 100644 index 1cda7339..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/chat/MessageHelper.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.chat; - -import org.auioc.mcmod.arnicalib.base.function.StringUnaryOperator; -import net.minecraft.ChatFormatting; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; - -public class MessageHelper { - - private final Component prefix; - private final StringUnaryOperator i18n; - - public MessageHelper(Component prefix, StringUnaryOperator i18n) { - this.prefix = prefix; - this.i18n = i18n; - } - - public MessageHelper(String modName, StringUnaryOperator i18n) { - this(Component.literal("[" + modName + "] ").withStyle(ChatFormatting.AQUA), i18n); - } - - - public MessageHelper(StringUnaryOperator i18n) { - this(Component.empty(), i18n); - } - - - public MutableComponent create(Component message, boolean withPrefix) { - return withPrefix ? (Component.empty()).append(this.prefix).append(message) : (Component.empty()).append(message); - } - - public MutableComponent create(String key, Object[] args, boolean withPrefix) { - return create(Component.translatable(this.i18n.apply(key), args), withPrefix); - } - - public MutableComponent create(String key, boolean withPrefix) { - return create(key, TextUtils.NO_ARGS, withPrefix); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/chat/TextUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/chat/TextUtils.java deleted file mode 100644 index 568e5529..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/chat/TextUtils.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.chat; - -import com.google.gson.JsonElement; -import com.mojang.serialization.Dynamic; -import com.mojang.serialization.JsonOps; -import net.minecraft.network.chat.*; -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; - -import javax.annotation.Nullable; -import java.util.List; - -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public class TextUtils { - - private static final Marker MARKER = LogUtil.getMarker(TextUtils.class); - - public static final Object[] NO_ARGS = new Object[0]; - - /** - * @deprecated Use {@link net.minecraft.network.chat.Component#empty()} instead - */ - @Deprecated(since = "6.0.0", forRemoval = true) - public static MutableComponent empty() { - return Component.empty(); - - } - - /** - * @deprecated Use {@link net.minecraft.network.chat.Component#literal(String)} instead - */ - @Deprecated(since = "6.0.0", forRemoval = true) - public static MutableComponent literal(String text) { - return Component.literal(text); - } - - /** - * @deprecated Use {@link net.minecraft.network.chat.Component#translatable(String)} instead - */ - @Deprecated(since = "6.0.0", forRemoval = true) - public static MutableComponent translatable(String key) { - return Component.translatable(key); - } - - /** - * @deprecated Use {@link net.minecraft.network.chat.Component#translatable(String, Object...)} instead - */ - @Deprecated(since = "6.0.0", forRemoval = true) - public static MutableComponent translatable(String key, Object... arguments) { - return Component.translatable(key, arguments); - } - - - public static Style copyable(Style style, String c) { - return style.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, c)).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, translatable("chat.copy.click"))); - } - - public static MutableComponent copyable(Component c) { - return TextUtils.empty().append(c).withStyle((s) -> copyable(s, c.getString())); - } - - public static MutableComponent copyable(String c) { - return copyable(TextUtils.literal(c)); - } - - - public static MutableComponent join(List texts, Component separator) { - var r = empty(); - if (texts.isEmpty()) return r; - - int s = texts.size(); - for (int i = 0, l = s - 1; i < l; ++i) { - r.append(texts.get(i)).append(separator); - } - r.append(texts.get(s - 1)); - - return r; - } - - public static MutableComponent join(List texts) { - return join(texts, literal(", ")); - } - - @Nullable - public static Style deserializeStyle(JsonElement json) { - return Style.Serializer.CODEC - .parse(new Dynamic<>(JsonOps.INSTANCE, json)) - .getOrThrow(false, (error) -> LOGGER.error(MARKER, error)); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/codec/EnumCodec.java b/src/main/java/org/auioc/mcmod/arnicalib/game/codec/EnumCodec.java index a59f8162..8ed10ad4 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/codec/EnumCodec.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/codec/EnumCodec.java @@ -1,105 +1,106 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.codec; - -import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Codec; -import com.mojang.serialization.DataResult; -import com.mojang.serialization.DynamicOps; -import net.minecraft.util.ExtraCodecs; -import org.auioc.mcmod.arnicalib.base.function.StringFunction; -import org.auioc.mcmod.arnicalib.base.function.ToStringFunction; - -import java.util.Arrays; -import java.util.function.IntFunction; -import java.util.stream.Collectors; - -public class EnumCodec> implements Codec { - - private final Codec codec; - - private EnumCodec(Codec codec) { - this.codec = codec; - } - - @Override - public DataResult encode(E input, DynamicOps ops, T prefix) { - return this.codec.encode(input, ops, prefix); - } - - @Override - public DataResult> decode(DynamicOps ops, T input) { - return this.codec.decode(ops, input); - } - - // ============================================================================================================== // - - private static > EnumCodec of(IntFunction decoder) { - return new EnumCodec<>(ExtraCodecs.idResolverCodec(Enum::ordinal, decoder, -1)); - } - - private static > EnumCodec of(ToStringFunction encoder, StringFunction decoder) { - return new EnumCodec<>(ExtraCodecs.stringResolverCodec(encoder, (s) -> (s != null) ? decoder.apply(s) : null)); - } - - private static > EnumCodec of(E[] values, ToStringFunction encoder, int threshold) { - if (values.length > threshold) { - var map = Arrays.stream(values) - .collect(Collectors.toMap(encoder, (e) -> e)); - return of(encoder, map::get); - } - return of(encoder, (s) -> { - for (E e : values) if (encoder.apply(e).equals(s)) return e; - return null; - }); - } - - private static final int THRESHOLD = 8; - - // ====================================================================== // - - public static > EnumCodec byString(Class enumClass, ToStringFunction encoder, int threshold) { - return of(enumClass.getEnumConstants(), encoder, threshold); - } - - public static > EnumCodec byString(Class enumClass, ToStringFunction encoder) { - return byString(enumClass, encoder, THRESHOLD); - } - - public static > EnumCodec byName(Class enumClass) { - return byString(enumClass, E::name, THRESHOLD); - } - - public static > EnumCodec byNameLowerCase(Class enumClass) { - return byString(enumClass, (e) -> e.name().toLowerCase(), THRESHOLD); - } - - public static > EnumCodec byNameUpperCase(Class enumClass) { - return byString(enumClass, (e) -> e.name().toUpperCase(), THRESHOLD); - } - - // ====================================================================== // - - public static > EnumCodec byOrdinal(Class enumClass) { - var values = enumClass.getEnumConstants(); - return of((i) -> (i >= 0 && i < values.length) ? values[i] : null); - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.codec; + + +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.DynamicOps; +import net.minecraft.util.ExtraCodecs; +import org.auioc.mcmod.arnicalib.base.function.StringFunction; +import org.auioc.mcmod.arnicalib.base.function.ToStringFunction; + +import java.util.Arrays; +import java.util.function.IntFunction; +import java.util.stream.Collectors; + +public class EnumCodec> implements Codec { + + private final Codec codec; + + private EnumCodec(Codec codec) { + this.codec = codec; + } + + @Override + public DataResult encode(E input, DynamicOps ops, T prefix) { + return this.codec.encode(input, ops, prefix); + } + + @Override + public DataResult> decode(DynamicOps ops, T input) { + return this.codec.decode(ops, input); + } + + // ============================================================================================================== // + + private static > EnumCodec of(IntFunction decoder) { + return new EnumCodec<>(ExtraCodecs.idResolverCodec(Enum::ordinal, decoder, -1)); + } + + private static > EnumCodec of(ToStringFunction encoder, StringFunction decoder) { + return new EnumCodec<>(Codec.stringResolver(encoder, (s) -> (s != null) ? decoder.apply(s) : null)); + } + + private static > EnumCodec of(E[] values, ToStringFunction encoder, int threshold) { + if (values.length > threshold) { + var map = Arrays.stream(values) + .collect(Collectors.toMap(encoder, (e) -> e)); + return of(encoder, map::get); + } + return of(encoder, (s) -> { + for (E e : values) if (encoder.apply(e).equals(s)) return e; + return null; + }); + } + + private static final int THRESHOLD = 8; + + // ====================================================================== // + + public static > EnumCodec byString(Class enumClass, ToStringFunction encoder, int threshold) { + return of(enumClass.getEnumConstants(), encoder, threshold); + } + + public static > EnumCodec byString(Class enumClass, ToStringFunction encoder) { + return byString(enumClass, encoder, THRESHOLD); + } + + public static > EnumCodec byName(Class enumClass) { + return byString(enumClass, E::name, THRESHOLD); + } + + public static > EnumCodec byNameLowerCase(Class enumClass) { + return byString(enumClass, (e) -> e.name().toLowerCase(), THRESHOLD); + } + + public static > EnumCodec byNameUpperCase(Class enumClass) { + return byString(enumClass, (e) -> e.name().toUpperCase(), THRESHOLD); + } + + // ====================================================================== // + + public static > EnumCodec byOrdinal(Class enumClass) { + var values = enumClass.getEnumConstants(); + return of((i) -> (i >= 0 && i < values.length) ? values[i] : null); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/AHCommands.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/AHCommands.java deleted file mode 100644 index af7a9851..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/AHCommands.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command; - -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.tree.CommandNode; -import net.minecraft.commands.CommandSourceStack; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import org.auioc.mcmod.arnicalib.mod.client.command.AHClientCommands; -import org.auioc.mcmod.arnicalib.mod.server.command.AHServerCommands; - -public final class AHCommands { - - public static CommandNode getServerNode(CommandDispatcher dispatcher) { - return AHServerCommands.getAHNode(dispatcher); - } - - @OnlyIn(Dist.CLIENT) - public static CommandNode getClientNode(CommandDispatcher dispatcher) { - return AHClientCommands.getAHNode(dispatcher); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandExceptions.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandExceptions.java deleted file mode 100644 index 68d82d13..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandExceptions.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command; - -import com.mojang.brigadier.exceptions.BuiltInExceptionProvider; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import net.minecraft.network.chat.Component; -import org.auioc.mcmod.arnicalib.ArnicaLib; - -public class CommandExceptions { - - public static final BuiltInExceptionProvider BUILT_IN_EXCEPTIONS = CommandSyntaxException.BUILT_IN_EXCEPTIONS; - - public static final SimpleCommandExceptionType INTERNAL_ERROR = simple("command.failure.internal"); - public static final SimpleCommandExceptionType LOGGABLE_INTERNAL_ERROR = simple("command.failure.internal.loggable"); - public static final SimpleCommandExceptionType NOT_SERVER_ERROR = simple("command.failure.not_server"); - public static final SimpleCommandExceptionType NOT_DEDICATED_SERVER_ERROR = simple("command.failure.not_dedicated_server"); - - private static SimpleCommandExceptionType simple(String key) { - return new SimpleCommandExceptionType(Component.translatable(ArnicaLib.i18n("command.failure.internal"))); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandHandlers.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandHandlers.java deleted file mode 100644 index e3f57356..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandHandlers.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command; - -import com.mojang.brigadier.Command; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.item.ItemStack; -import org.auioc.mcmod.arnicalib.game.command.action.BiCommandAction; -import org.auioc.mcmod.arnicalib.game.command.action.CommandAction; - -public class CommandHandlers { - - public static int playerSelf(CommandContext ctx, CommandAction.SingleSuccess action) throws CommandSyntaxException { - action.accept(ctx.getSource().getPlayerOrException()); - return Command.SINGLE_SUCCESS; - } - - public static int playerSelfWithMainHand(CommandContext ctx, BiCommandAction.SingleSuccess action) throws CommandSyntaxException { - return playerSelf(ctx, (player) -> { - if (!player.getMainHandItem().isEmpty()) action.accept(player, player.getMainHandItem()); - }); - } - - - public static class MultiSuccess { - - public static int playerSelf(CommandContext ctx, CommandAction.MultiSuccess action) throws CommandSyntaxException { - return action.applyAsInt(ctx.getSource().getPlayerOrException()); - } - - public static int playerSelfWithMainHand(CommandContext ctx, BiCommandAction.MultiSuccess action) throws CommandSyntaxException { - return playerSelf(ctx, (player) -> (player.getMainHandItem().isEmpty()) ? 0 : action.applyAsInt(player, player.getMainHandItem())); - } - - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandNodeUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandNodeUtils.java deleted file mode 100644 index 48a1babc..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandNodeUtils.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command; - -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.context.ParsedCommandNode; -import com.mojang.brigadier.tree.LiteralCommandNode; -import net.minecraft.commands.CommandSourceStack; - -import java.util.List; -import java.util.stream.Collectors; - -public class CommandNodeUtils { - - public static String getLastLiteral(List> nodeList) { - for (int i = nodeList.size(); i-- > 0; ) { - if (nodeList.get(i).getNode() instanceof LiteralCommandNode) { - return ((LiteralCommandNode) nodeList.get(i).getNode()).getLiteral(); - } - } - return null; - } - - /** - * @param nodeList List of {@link ParsedCommandNode}s, from {@link CommandContext#getNodes()} - * @param fromIndex - * @param toIndex - * @return String that concatenates the literals (or in its snake case) of all (or some of) {@link LiteralCommandNode}s in the {@link ParsedCommandNode} list, separated by dots - * @since 5.1.1 - */ - public static String joinLiteralNodes(List> nodeList, int fromIndex, int toIndex) { - return nodeList - .subList(fromIndex, toIndex) - .stream() - .map(ParsedCommandNode::getNode) - .filter(LiteralCommandNode.class::isInstance) - .map((node) -> (LiteralCommandNode) node) - .map(LiteralCommandNode::getLiteral) - .collect(Collectors.joining(".")); - } - - /** - * @see #joinLiteralNodes(List, int, int) - */ - public static String joinLiteralNodes(List> nodes, int fromIndex) { - return joinLiteralNodes(nodes, fromIndex, nodes.size()); - } - - /** - * @see #joinLiteralNodes(List, int, int) - */ - public static String joinLiteralNodes(List> nodes) { - return joinLiteralNodes(nodes, 0, nodes.size()); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandSourceUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandSourceUtils.java deleted file mode 100644 index ac841e36..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/CommandSourceUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command; - -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.client.player.LocalPlayer; -import net.minecraft.commands.CommandSource; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.server.dedicated.DedicatedServer; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.BaseCommandBlock; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; - -import java.util.function.Predicate; - -public class CommandSourceUtils { - - public static final Predicate PERMISSION_LEVEL_0 = (sourceStack) -> sourceStack.hasPermission(0); - public static final Predicate PERMISSION_LEVEL_1 = (sourceStack) -> sourceStack.hasPermission(1); - public static final Predicate PERMISSION_LEVEL_2 = (sourceStack) -> sourceStack.hasPermission(2); - public static final Predicate PERMISSION_LEVEL_3 = (sourceStack) -> sourceStack.hasPermission(3); - public static final Predicate PERMISSION_LEVEL_4 = (sourceStack) -> sourceStack.hasPermission(4); - - public static final Predicate IS_PLAYER = (sourceStack) -> sourceStack.getEntity() instanceof Player; - public static final Predicate IS_COMMAND_BLOCK = (sourceStack) -> sourceStack.source instanceof BaseCommandBlock; - public static final Predicate IS_DEDICATED_SERVER = (sourceStack) -> sourceStack.source instanceof DedicatedServer; - - /** - * @deprecated The field {@link CommandSourceStack#source} is now public. - */ - @Deprecated(since = "6.0.0") - public static CommandSource getRealSource(CommandSourceStack sourceStack) { - return sourceStack.source; - } - - @OnlyIn(Dist.CLIENT) - public static LocalPlayer getLocalPlayerOrException(CommandSourceStack sourceStack) throws CommandSyntaxException { - var entity = sourceStack.getEntity(); - if (entity instanceof LocalPlayer) return (LocalPlayer) entity; - throw CommandSourceStack.ERROR_NOT_PLAYER.create(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/DynamicCommandHandler.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/DynamicCommandHandler.java deleted file mode 100644 index 13122413..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/DynamicCommandHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command; - -import com.mojang.brigadier.Command; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.commands.CommandSourceStack; -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; -import org.auioc.mcmod.arnicalib.game.mod.EnvironmentUtils; - -import java.lang.reflect.InvocationTargetException; - -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public class DynamicCommandHandler { - - private static final Marker MARKER = LogUtil.getMarker(DynamicCommandHandler.class); - - @SuppressWarnings("unchecked") - public static LiteralArgumentBuilder createBuilder(String className, String methodName, LiteralArgumentBuilder builder) { - try { - var method = Class.forName(className).getMethod(methodName, LiteralArgumentBuilder.class); - return (LiteralArgumentBuilder) method.invoke(null, builder); - } catch (Exception e) { - if (EnvironmentUtils.IS_DEV && e instanceof ClassNotFoundException) { - LOGGER.debug(MARKER, "ClassNotFoundException: {}", e.getMessage()); - } - LOGGER.error(MARKER, "Failed to create builder", e); - } - return builder; - } - - // ============================================================================================================== // - - public static int run(String className, String methodName, CommandContext ctx) throws CommandSyntaxException { - try { - _run(className, methodName, ctx); - } catch (Throwable e) { - if (e instanceof CommandSyntaxException cse) { - LOGGER.warn(MARKER, "Command handler " + className + " throws a CommandSyntaxException"); - throw cse; - } - throw CommandExceptions.LOGGABLE_INTERNAL_ERROR.create(); - } - return Command.SINGLE_SUCCESS; - } - - private static void _run(String className, String methodName, CommandContext ctx) throws Throwable { - try { - Class.forName(className) - .getMethod(methodName, CommandContext.class) - .invoke(null, ctx); - } catch (ClassNotFoundException e) { - rethrow(e, "Cannot load class"); - } catch (NoSuchMethodException | SecurityException e) { - rethrow(e, "Cannot get method"); - } catch (IllegalAccessException | IllegalArgumentException e) { - rethrow(e, "Cannot invoke method"); - } catch (InvocationTargetException e) { - if (e.getTargetException() instanceof CommandSyntaxException cse) { - throw cse; - } - rethrow(e.getTargetException(), "Command handler throws an exception that is not a CommandSyntaxException"); - } - } - - // ============================================================================================================== // - - private static void rethrow(Throwable throwable, String message) throws Throwable { - LOGGER.error(MARKER, message, throwable); - throw throwable; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/action/BiCommandAction.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/action/BiCommandAction.java deleted file mode 100644 index ed1ca3bb..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/action/BiCommandAction.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.action; - -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import org.apache.commons.lang3.function.FailableBiConsumer; -import org.apache.commons.lang3.function.FailableToIntBiFunction; - -public class BiCommandAction { - - public interface SingleSuccess extends FailableBiConsumer { - - } - - - public interface MultiSuccess extends FailableToIntBiFunction { - - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/action/CommandAction.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/action/CommandAction.java deleted file mode 100644 index 41d83ce9..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/action/CommandAction.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.action; - -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import org.apache.commons.lang3.function.FailableConsumer; -import org.apache.commons.lang3.function.FailableToIntFunction; - -public class CommandAction { - - public interface SingleSuccess extends FailableConsumer { - - } - - - public interface MultiSuccess extends FailableToIntFunction { - - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/CreativeModeTabArgument.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/CreativeModeTabArgument.java deleted file mode 100644 index cd9d212a..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/CreativeModeTabArgument.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.argument; - -import com.mojang.brigadier.builder.RequiredArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import com.mojang.brigadier.suggestion.SuggestionProvider; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.commands.SharedSuggestionProvider; -import net.minecraft.commands.arguments.ResourceLocationArgument; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.CreativeModeTab; -import org.auioc.mcmod.arnicalib.ArnicaLib; - -public class CreativeModeTabArgument { - - private static final DynamicCommandExceptionType ERROR_UNKNOWN = new DynamicCommandExceptionType( - (langId) -> Component.translatable(ArnicaLib.i18n("argument.creative_mode_tab.unknown"), langId) - ); - - public static final SuggestionProvider SUGGESTIONS = (ctx, builder) -> SharedSuggestionProvider.suggest( - BuiltInRegistries.CREATIVE_MODE_TAB.keySet().stream().map(ResourceLocation::toString), - builder - ); - - public static RequiredArgumentBuilder create(String name) { - return Commands.argument(name, ResourceLocationArgument.id()).suggests(SUGGESTIONS); - } - - public static CreativeModeTab get(CommandContext ctx, String name) throws CommandSyntaxException { - var id = ResourceLocationArgument.getId(ctx, name); - return BuiltInRegistries.CREATIVE_MODE_TAB - .getOptional(id) - .orElseThrow(() -> ERROR_UNKNOWN.create(id)); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/LanguageArgument.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/LanguageArgument.java deleted file mode 100644 index 307e09c8..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/LanguageArgument.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.argument; - -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import net.minecraft.client.resources.language.LanguageInfo; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.SharedSuggestionProvider; -import net.minecraft.network.chat.Component; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import org.auioc.mcmod.arnicalib.ArnicaLib; -import org.auioc.mcmod.arnicalib.game.language.LanguageUtils; - -import java.util.concurrent.CompletableFuture; - -@OnlyIn(Dist.CLIENT) -public class LanguageArgument implements ArgumentType { - - private static final DynamicCommandExceptionType ERROR_UNKNOWN_LANGUAGE = new DynamicCommandExceptionType( - (code) -> Component.translatable(ArnicaLib.i18n("argument.language.unknown"), code) - ); - - public static LanguageArgument create() { - return new LanguageArgument(); - } - - public static LanguageInfo get(CommandContext ctx, String argument) { - return ctx.getArgument(argument, LanguageInfo.class); - } - - @Override - public LanguageInfo parse(StringReader reader) throws CommandSyntaxException { - String code = reader.readString(); - return LanguageUtils.get(code).orElseThrow(() -> ERROR_UNKNOWN_LANGUAGE.create(code)); - } - - @Override - public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { - return SharedSuggestionProvider.suggest(LanguageUtils.codes(), builder); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/OverlayArgument.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/OverlayArgument.java deleted file mode 100644 index 1576c775..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/argument/OverlayArgument.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.argument; - -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.arguments.ArgumentType; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import com.mojang.brigadier.suggestion.Suggestions; -import com.mojang.brigadier.suggestion.SuggestionsBuilder; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.SharedSuggestionProvider; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.neoforge.client.gui.overlay.GuiOverlayManager; -import net.neoforged.neoforge.client.gui.overlay.NamedGuiOverlay; -import org.auioc.mcmod.arnicalib.ArnicaLib; - -import java.util.concurrent.CompletableFuture; -import java.util.stream.Stream; - -@OnlyIn(Dist.CLIENT) -public class OverlayArgument implements ArgumentType { - - private static final DynamicCommandExceptionType ERROR_UNKNOWN_OVERLAY = new DynamicCommandExceptionType( - (id) -> Component.translatable(ArnicaLib.i18n("argument.overlay.unknown"), id) - ); - - public static OverlayArgument create() { - return new OverlayArgument(); - } - - public static NamedGuiOverlay get(CommandContext ctx, String argument) { - return ctx.getArgument(argument, NamedGuiOverlay.class); - } - - @Override - public NamedGuiOverlay parse(StringReader reader) throws CommandSyntaxException { - var id = new ResourceLocation(reader.readString()); - var overlay = GuiOverlayManager.findOverlay(id); - if (overlay != null) return overlay; - throw ERROR_UNKNOWN_OVERLAY.create(id); - } - - @Override - public CompletableFuture listSuggestions(CommandContext context, SuggestionsBuilder builder) { - return SharedSuggestionProvider.suggest(getOverlays().map(NamedGuiOverlay::id).map(ResourceLocation::toString), builder); - } - - private static Stream getOverlays() { - return GuiOverlayManager.getOverlays().stream(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/exception/ExceptionCommandExceptionType.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/exception/ExceptionCommandExceptionType.java deleted file mode 100644 index bd70c39e..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/exception/ExceptionCommandExceptionType.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.exception; - -import com.mojang.brigadier.Message; -import com.mojang.brigadier.exceptions.CommandExceptionType; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; - -import java.util.function.Function; - - -public class ExceptionCommandExceptionType implements CommandExceptionType { - - private final Function messageBuilder; - private final Logger logger; - private final Marker marker; - - public ExceptionCommandExceptionType(Function messageBuilder, Logger logger, Marker marker) { - this.messageBuilder = messageBuilder; - this.logger = logger; - this.marker = marker; - } - - public ExceptionCommandExceptionType(Function messageBuilder) { - this(messageBuilder, null, null); - } - - public CommandSyntaxException create(Exception e, String logMessage) { - if (this.logger != null) { - if (this.marker != null) { - this.logger.error(this.marker, logMessage, e); - } else { - this.logger.error(logMessage, e); - } - } - return new CommandSyntaxException(this, messageBuilder.apply(e)); - } - - public CommandSyntaxException create(Exception e) { - return create(e, ""); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/command/node/VersionCommand.java b/src/main/java/org/auioc/mcmod/arnicalib/game/command/node/VersionCommand.java deleted file mode 100644 index 22e22ca9..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/command/node/VersionCommand.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.command.node; - -import com.mojang.brigadier.Command; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import com.mojang.brigadier.tree.CommandNode; -import net.minecraft.ChatFormatting; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.ArnicaLib; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; -import org.auioc.mcmod.arnicalib.game.chat.TextUtils; -import org.auioc.mcmod.arnicalib.game.mod.BuildInfo; - -import java.util.function.Function; - -import static net.minecraft.commands.Commands.literal; -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public class VersionCommand { - - private static final Marker MARKER = LogUtil.getMarker(VersionCommand.class); - - private static final SimpleCommandExceptionType GET_VERSION_REFLECTION_ERROR = new SimpleCommandExceptionType(i18n("failure", TextUtils.NO_ARGS)); - - public static final Function, Command> HANDLER_BUILDER = (modClass) -> (ctx) -> getModVersion(ctx, modClass); - - public static final Function, CommandNode> NODE_BUILDER = (modClass) -> literal("version").executes(HANDLER_BUILDER.apply(modClass)).build(); - - public static void addVersionNode(CommandNode node, Class modClass) { - node.addChild(NODE_BUILDER.apply(modClass)); - } - - public static int getModVersion(CommandContext ctx, Class modClazz) throws CommandSyntaxException { - BuildInfo buildInfo; - String modName; - try { - buildInfo = (BuildInfo) modClazz.getField("BUILD_INFO").get(modClazz); - modName = (String) modClazz.getField("MOD_NAME").get(modClazz); - } catch (Exception e) { - var commandException = GET_VERSION_REFLECTION_ERROR.create(); - LOGGER.error(MARKER, commandException.getMessage(), e); - throw commandException; - } - var message = Component.empty(); - message.append(Component.literal("[" + modName + "] ").withStyle(ChatFormatting.AQUA)); - message.append(i18n("success", buildInfo.version(), buildInfo)); - ctx.getSource().sendSuccess(() -> message, false); - return Command.SINGLE_SUCCESS; - } - - // ============================================================================================================== // - - private static MutableComponent i18n(String key, Object... args) { - return Component.translatable(ArnicaLib.i18n("command.version." + key), args); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/compat/ModCompatUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/compat/ModCompatUtils.java deleted file mode 100644 index fddf6a57..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/compat/ModCompatUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.compat; - -import net.neoforged.fml.ModList; - -public class ModCompatUtils { - - public static boolean isModLoaded(String modId) { - return ModList.get().isLoaded(modId); - } - - public static boolean isClass(String clazz, boolean safe) { - try { - if (safe) { - Class.forName(clazz, false, ModCompatUtils.class.getClassLoader()); - } else { - Class.forName(clazz); - } - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - public static boolean isClass(String clazz) { - return isClass(clazz, true); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/config/CodecConfigValue.java b/src/main/java/org/auioc/mcmod/arnicalib/game/config/CodecConfigValue.java new file mode 100644 index 00000000..63678849 --- /dev/null +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/config/CodecConfigValue.java @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.config; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import net.neoforged.neoforge.common.ModConfigSpec; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +import javax.annotation.Nonnull; +import java.util.Objects; +import java.util.function.Supplier; + +import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; + +/** + * @author LainIO24 + * @since 7.0.0 + */ +public class CodecConfigValue implements Supplier { + + private static final Marker MARKER = MarkerFactory.getMarker(CodecConfigValue.class.getName()); + + public static CodecConfigValue define(ModConfigSpec.Builder builder, String name, Codec codec, T defaultValue) { + var encodedDefaultValue = codec + .encodeStart(ModConfigOps.INSTANCE, defaultValue) + .getOrThrow(s -> new IllegalArgumentException(String.format("Failed to encode default value %s: %s", defaultValue, s))); + var configValue = builder.define(name, encodedDefaultValue); + return new CodecConfigValue<>(configValue, codec, defaultValue, encodedDefaultValue); + } + + private final @Nonnull ModConfigSpec.ConfigValue configValue; + private final @Nonnull Codec codec; + private @Nonnull Object cached; + private @Nonnull T parsed; + private final @Nonnull T default_; + + private CodecConfigValue(@NotNull ModConfigSpec.ConfigValue configValue, @NotNull Codec codec, @NotNull T defaultValue, @NotNull Object encodedDefaultValue) { + this.configValue = configValue; + this.codec = codec; + this.default_ = defaultValue; + this.parsed = defaultValue; + this.cached = encodedDefaultValue; + } + + @Override + @Nonnull + public T get() { + Object freshObject = this.configValue.get(); + if (!Objects.equals(this.cached, freshObject)) { + this.cached = freshObject; + this.parsed = this.decode(freshObject); + } + return this.parsed; + } + + public void set(T value) { + this.codec.encodeStart(ModConfigOps.INSTANCE, value) + .resultOrPartial((e) -> LOGGER.error(MARKER, "Could not save value {} due to encoding error: {}", value, e)) + .ifPresent((result) -> { + this.configValue.set(result); + this.configValue.save(); + this.parsed = value; + this.cached = result; + }); + } + + private T decode(Object obj) { + DataResult parseResult = this.codec.parse(ModConfigOps.INSTANCE, obj); + return parseResult.mapOrElse( + (result) -> result, + (failure) -> { + LOGGER.error(MARKER, "Rollback to default value due to decoding error: {}", failure.message()); + return this.default_; + } + ); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/config/ConfigUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/config/ConfigUtils.java index 4fec7866..aba09ffe 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/config/ConfigUtils.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/config/ConfigUtils.java @@ -1,116 +1,117 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.config; - -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; -import net.neoforged.neoforge.common.ModConfigSpec.Builder; -import net.neoforged.neoforge.common.ModConfigSpec.ConfigValue; - -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; - -public class ConfigUtils { - - public static final Joiner LINE_JOINER = Joiner.on("\n"); - public static final Joiner DOT_JOINER = Joiner.on("."); - public static final Splitter DOT_SPLITTER = Splitter.on("."); - - public static List split(String path) { - return Lists.newArrayList(DOT_SPLITTER.split(path)); - } - - - public static void pushWithoutPop(Builder specBuilder, String path, Consumer subBuilder) { - specBuilder.push(path); - subBuilder.accept(specBuilder); - } - - public static void push(Builder specBuilder, String path, Consumer subBuilder) { - specBuilder.push(path); - subBuilder.accept(specBuilder); - specBuilder.pop(); - } - - - public static ConfigValue> defineList(Builder specBuilder, String path, Supplier> defaultSupplier, Predicate elementValidator) { - return specBuilder.defineListAllowEmpty(split(path), defaultSupplier, elementValidator); - } - - public static ConfigValue> defineList(Builder specBuilder, String path, Predicate elementValidator) { - return defineList(specBuilder, path, List::of, elementValidator); - } - - public static ConfigValue> defineStringList(Builder specBuilder, String path) { - return defineList(specBuilder, path, (o) -> o instanceof String); - } - - public static ConfigValue> defineStringList(Builder specBuilder, String path, List allowedValues) { - return defineList(specBuilder, path, (o) -> o instanceof String && allowedValues.contains(o)); - } - - public static ConfigValue> defineStringList(Builder specBuilder, String path, Supplier> defaultSupplier, Predicate stringValidator) { - return defineList(specBuilder, path, defaultSupplier, (o) -> (o instanceof String) && stringValidator.test((String) o)); - } - - public static ConfigValue> defineStringList(Builder specBuilder, String path, Supplier> defaultSupplier) { - return defineStringList(specBuilder, path, defaultSupplier, (o) -> true); - } - - - public static boolean validateListSize(Object o, int size) { - if (o instanceof List l) { - return l.size() == size; - } - return false; - } - - public static boolean validateListElements(Object o, Class type) { - if (o instanceof List l) { - for (var e : l) { - if (!type.isInstance(e)) return false; - } - return true; - } - return false; - } - - public static boolean validateListElements(Object o, Class type, List allowed) { - if (o instanceof List l) { - for (var e : l) { - if (type.isInstance(e) && allowed.contains(type.cast(o))) { - continue; - } else { - return false; - } - } - return true; - } - return false; - } - - public static boolean validateStringList(Object o, List allowed) { - return validateListElements(o, String.class, allowed); - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.config; + + +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; +import net.neoforged.neoforge.common.ModConfigSpec.Builder; +import net.neoforged.neoforge.common.ModConfigSpec.ConfigValue; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public class ConfigUtils { + + public static final Joiner LINE_JOINER = Joiner.on("\n"); + public static final Joiner DOT_JOINER = Joiner.on("."); + public static final Splitter DOT_SPLITTER = Splitter.on("."); + + public static List split(String path) { + return Lists.newArrayList(DOT_SPLITTER.split(path)); + } + + + public static void pushWithoutPop(Builder specBuilder, String path, Consumer subBuilder) { + specBuilder.push(path); + subBuilder.accept(specBuilder); + } + + public static void push(Builder specBuilder, String path, Consumer subBuilder) { + specBuilder.push(path); + subBuilder.accept(specBuilder); + specBuilder.pop(); + } + + + public static ConfigValue> defineList(Builder specBuilder, String path, Supplier> defaultSupplier, Predicate elementValidator) { + return specBuilder.defineListAllowEmpty(split(path), defaultSupplier, elementValidator); + } + + public static ConfigValue> defineList(Builder specBuilder, String path, Predicate elementValidator) { + return defineList(specBuilder, path, List::of, elementValidator); + } + + public static ConfigValue> defineStringList(Builder specBuilder, String path) { + return defineList(specBuilder, path, String.class::isInstance); + } + + public static ConfigValue> defineStringList(Builder specBuilder, String path, List allowedValues) { + return defineList(specBuilder, path, (o) -> o instanceof String && allowedValues.contains(o)); + } + + public static ConfigValue> defineStringList(Builder specBuilder, String path, Supplier> defaultSupplier, Predicate stringValidator) { + return defineList(specBuilder, path, defaultSupplier, (o) -> (o instanceof String) && stringValidator.test((String) o)); + } + + public static ConfigValue> defineStringList(Builder specBuilder, String path, Supplier> defaultSupplier) { + return defineStringList(specBuilder, path, defaultSupplier, (o) -> true); + } + + + public static boolean validateListSize(Object o, int size) { + if (o instanceof List l) { + return l.size() == size; + } + return false; + } + + public static boolean validateListElements(Object o, Class type) { + if (o instanceof List l) { + for (var e : l) { + if (!type.isInstance(e)) return false; + } + return true; + } + return false; + } + + public static boolean validateListElements(Object o, Class type, List allowed) { + if (o instanceof List l) { + for (var e : l) { + if (type.isInstance(e) && allowed.contains(type.cast(o))) { + continue; + } else { + return false; + } + } + return true; + } + return false; + } + + public static boolean validateStringList(Object o, List allowed) { + return validateListElements(o, String.class, allowed); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/config/ModConfigOps.java b/src/main/java/org/auioc/mcmod/arnicalib/game/config/ModConfigOps.java new file mode 100644 index 00000000..8a422e67 --- /dev/null +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/config/ModConfigOps.java @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.config; + +import com.electronwill.nightconfig.core.Config; +import com.electronwill.nightconfig.core.NullObject; +import com.electronwill.nightconfig.toml.TomlFormat; +import com.mojang.datafixers.util.Pair; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.DynamicOps; + +import java.time.temporal.Temporal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * @author LainIO24 + * @since 7.0.0 + */ +public class ModConfigOps implements DynamicOps { + + public static final ModConfigOps INSTANCE = new ModConfigOps(); + + @Override + public Object empty() { + return NullObject.NULL_OBJECT; + } + + @Override + public U convertTo(DynamicOps ops, Object input) { + if (input instanceof Config) { + return this.convertMap(ops, input); + } + if (input instanceof Collection) { + return this.convertList(ops, input); + } + if (input == null || input instanceof NullObject) { + return ops.empty(); + } + if (input instanceof Enum) { + return ops.createString(((Enum) input).name()); + } + if (input instanceof Temporal) { + return ops.createString(input.toString()); + } + if (input instanceof String s) { + return ops.createString(s); + } + if (input instanceof Boolean b) { + return ops.createBoolean(b); + } + if (input instanceof Number n) { + return ops.createNumeric(n); + } + throw new UnsupportedOperationException("Unsupported value: " + input); + } + + @Override + public DataResult getNumberValue(Object input) { + return input instanceof Number n + ? DataResult.success(n) + : DataResult.error(() -> "Not a number: " + input); + } + + @Override + public DataResult getBooleanValue(Object input) { + if (input instanceof Boolean b) { + return DataResult.success(b); + } else if (input instanceof Number n) { + return DataResult.success(n.intValue() > 0); + } else { + return DataResult.error(() -> "Not a boolean: " + input); + } + } + + @Override + public Object createBoolean(boolean value) { + return Boolean.valueOf(value); + } + + @Override + public boolean compressMaps() { + return false; + } + + @Override + public Object createNumeric(Number i) { + return i; + } + + @Override + public DataResult getStringValue(Object input) { + if (input instanceof Config || input instanceof Collection) { + return DataResult.error(() -> "Not a string: " + input); + } else { + return DataResult.success(String.valueOf(input)); + } + } + + @Override + public Object createString(String value) { + return value; + } + + @Override + public DataResult mergeToList(Object list, List values) { + return DynamicOps.super.mergeToList(list, values) + .map(o -> this.empty() == o ? new ArrayList<>() : o); + } + + @Override + @SuppressWarnings("unchecked") + public DataResult mergeToList(Object list, Object value) { + if (!(list instanceof Collection) && this.empty() != list) { + return DataResult.error(() -> "mergeToList called with not a list: " + list, list); + } + var result = new ArrayList<>(); + if (this.empty() != list && list instanceof Collection) { + result.addAll((Collection) list); + } + result.add(value); + return DataResult.success(result); + } + + @Override + public DataResult mergeToMap(Object map, Object key, Object value) { + if (!(map instanceof Config) && this.empty() != map) { + return DataResult.error(() -> "mergeToMap called with not a map: " + map, map); + } + var keyResult = this.getStringValue(key); + if (keyResult.error().isPresent()) { + return DataResult.error(() -> "key is not a string: " + key, map); + } + return keyResult.flatMap(s -> { + var result = TomlFormat.newConfig(); + if (this.empty() != map && map instanceof Config) { + result.addAll((Config) map); + } + result.add(s, value); + return DataResult.success(result); + }); + } + + @Override + public DataResult>> getMapValues(Object input) { + return input instanceof Config config + ? DataResult.success(config.entrySet().stream().map(entry -> Pair.of(entry.getKey(), entry.getValue()))) + : DataResult.error(() -> "Not a Config: " + input); + } + + @Override + public Object createMap(Stream> map) { + var result = TomlFormat.newConfig(); + map.forEach(pair -> result.add( + this.getStringValue(pair.getFirst()).getOrThrow(), + pair.getSecond() + )); + return result; + } + + @Override + @SuppressWarnings("unchecked") + public DataResult> getStream(Object input) { + return input instanceof Collection + ? DataResult.success(((Collection) input).stream()) + : DataResult.error(() -> "Not a collection: " + input); + } + + @Override + public Object createList(Stream input) { + return input.toList(); + } + + @Override + public Object remove(Object input, String key) { + if (input instanceof Config config) { + var result = TomlFormat.newConfig(); + for (var entry : config.entrySet()) { + if (!Objects.equals(entry.getKey(), key)) { + result.add(entry.getKey(), entry.getValue()); + } + } + return result; + } + return input; + } + + @Override + public String toString() { + return "ModConfig"; + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/critereon/BiomePredicate.java b/src/main/java/org/auioc/mcmod/arnicalib/game/critereon/BiomePredicate.java new file mode 100644 index 00000000..7ae79672 --- /dev/null +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/critereon/BiomePredicate.java @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.critereon; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.advancements.critereon.MinMaxBounds; +import net.minecraft.core.Holder; +import net.minecraft.world.level.biome.Biome; +import org.auioc.mcmod.arnicalib.game.codec.EnumCodec; + +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * @since 7.0.0 + */ +public record BiomePredicate(Optional climate) implements Predicate { + + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + ClimatePredicate.CODEC.optionalFieldOf("climate").forGetter(o -> o.climate) + ).apply(instance, BiomePredicate::new)); + + + public boolean matches(Biome biome) { + if (climate.isPresent() && !climate.get().matches(biome.getModifiedClimateSettings())) { + return false; + } + return true; + } + + public boolean matches(Holder biome) { + return matches(biome.value()); + } + + @Override + public boolean test(Biome biome) { return matches(biome); } + + // ============================================================================================================== // + + public static BiomePredicate withClimate(Consumer consumer) { + var climate = ClimatePredicate.builder(); + consumer.accept(climate); + return new BiomePredicate(Optional.of(climate.build())); + } + + // ============================================================================================================== // + + public record ClimatePredicate( + Optional hasPrecipitation, + MinMaxBounds.Doubles temperature, + Optional temperatureModifier, + MinMaxBounds.Doubles downfall + ) { + + public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( + Codec.BOOL.optionalFieldOf("has_precipitation").forGetter(o -> o.hasPrecipitation), + MinMaxBounds.Doubles.CODEC.optionalFieldOf("temperature", MinMaxBounds.Doubles.ANY).forGetter(o -> o.temperature), + EnumCodec.byString(Biome.TemperatureModifier.class, e -> e.getName()).optionalFieldOf("temperature_modifier").forGetter(o -> o.temperatureModifier), + MinMaxBounds.Doubles.CODEC.optionalFieldOf("downfall", MinMaxBounds.Doubles.ANY).forGetter(o -> o.downfall) + ).apply(instance, ClimatePredicate::new)); + + public boolean matches(Biome.ClimateSettings climate) { + if (hasPrecipitation.isPresent() && hasPrecipitation.get() != climate.hasPrecipitation()) { + return false; + } + if (!temperature.matches(climate.temperature())) { + return false; + } + if (temperatureModifier.isPresent() && temperatureModifier.get() != climate.temperatureModifier()) { + return false; + } + if (!downfall.matches(climate.downfall())) { + return false; + } + return true; + } + + public static Builder builder() { + return new Builder(); + } + + // ========================================================================================================== // + + public static class Builder { + + private Optional hasPrecipitation = Optional.empty(); + private MinMaxBounds.Doubles temperature = MinMaxBounds.Doubles.ANY; + private Optional temperatureModifier = Optional.empty(); + private MinMaxBounds.Doubles downfall = MinMaxBounds.Doubles.ANY; + + private Builder() { } + + public Builder hasPrecipitation() { + this.hasPrecipitation = Optional.of(true); + return this; + } + + public Builder noPrecipitation() { + this.hasPrecipitation = Optional.of(false); + return this; + } + + public Builder withTemperatureModifier(Biome.TemperatureModifier modifier) { + this.temperatureModifier = Optional.of(modifier); + return this; + } + + public Builder temperature(MinMaxBounds.Doubles temperature) { + this.temperature = temperature; + return this; + } + + public Builder downfall(MinMaxBounds.Doubles downfall) { + this.temperature = downfall; + return this; + } + + public ClimatePredicate build() { + return new ClimatePredicate(hasPrecipitation, temperature, temperatureModifier, downfall); + } + + } + + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/data/GsonHelper.java b/src/main/java/org/auioc/mcmod/arnicalib/game/data/GsonHelper.java deleted file mode 100644 index ef581851..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/data/GsonHelper.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.data; - -import java.util.function.Function; -import java.util.function.IntFunction; -import java.util.function.Supplier; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -public class GsonHelper extends net.minecraft.util.GsonHelper { - - public static T[] convertToArray(JsonArray json, IntFunction generator, Function converter) { - final var array = generator.apply(json.size()); - int i = 0; - for (var jsonElement : json) { - array[i] = converter.apply(jsonElement); - i++; - } - return array; - } - - public static T[] getAsArray(JsonObject json, String key, IntFunction generator, Function converter) { - return convertToArray(getAsJsonArray(json, key), generator, converter); - } - - public static T[] getAsArray(JsonObject json, String key, IntFunction generator, Function converter, Supplier fallback) { - return (json.has(key)) ? getAsArray(json, key, generator, converter) : fallback.get(); - } - - public static T[] getAsArray(JsonObject json, String key, IntFunction generator, Function converter, T[] fallback) { - return getAsArray(json, key, generator, converter, () -> fallback); - } - - public static T[] getAsArray(JsonObject json, String key, IntFunction generator, Function converter, boolean fallback) { - return (fallback) ? getAsArray(json, key, generator, converter, () -> generator.apply(0)) : getAsArray(json, key, generator, converter); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadFunction.java b/src/main/java/org/auioc/mcmod/arnicalib/game/data/TagRecord.java similarity index 63% rename from src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadFunction.java rename to src/main/java/org/auioc/mcmod/arnicalib/game/data/TagRecord.java index 8d706f97..ae9f7198 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/base/function/QuadFunction.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/data/TagRecord.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 AUIOC.ORG + * Copyright (C) 2025 AUIOC.ORG * * This file is part of ArnicaLib, a mod made for Minecraft. * @@ -17,19 +17,21 @@ * this program. If not, see . */ -package org.auioc.mcmod.arnicalib.base.function; +package org.auioc.mcmod.arnicalib.game.data; -import java.util.Objects; -import java.util.function.Function; +import net.minecraft.data.tags.TagsProvider; +import net.minecraft.tags.TagKey; -@FunctionalInterface -public interface QuadFunction { +import java.util.function.Consumer; +import java.util.function.Function; - R apply(T t, U u, V v, W w); +/** + * @since 7.0.0 + */ +public record TagRecord(TagKey tag, Consumer> appender) { - default QuadFunction andThen(Function after) { - Objects.requireNonNull(after); - return (t, u, v, w) -> after.apply(apply(t, u, v, w)); + public void build(Function, TagsProvider.TagAppender> builder) { + appender.accept(builder.apply(tag)); } } diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/datagen/advancement/DataGenAdvancementEntry.java b/src/main/java/org/auioc/mcmod/arnicalib/game/datagen/advancement/DataGenAdvancementEntry.java deleted file mode 100644 index 944a6ef8..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/datagen/advancement/DataGenAdvancementEntry.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.datagen.advancement; - -import net.minecraft.advancements.Advancement; -import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.neoforge.common.data.ExistingFileHelper; - -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.UnaryOperator; - -public record DataGenAdvancementEntry(ResourceLocation id, Advancement.Builder builder) { - - public DataGenAdvancementEntry(ResourceLocation id, UnaryOperator builder) { - this(id, builder.apply(Advancement.Builder.advancement())); - } - - public DataGenAdvancementEntry(ResourceLocation id, BiFunction builder) { - this(id, builder.apply(id, Advancement.Builder.advancement())); - } - - public void accept(Consumer saver, ExistingFileHelper fileHelper) { - builder.save(saver, id, fileHelper); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/datagen/tag/IHTagsProvider.java b/src/main/java/org/auioc/mcmod/arnicalib/game/datagen/tag/IHTagsProvider.java deleted file mode 100644 index 094b7de2..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/datagen/tag/IHTagsProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.datagen.tag; - -import net.minecraft.core.Registry; -import net.minecraft.data.tags.IntrinsicHolderTagsProvider.IntrinsicTagAppender; -import net.minecraft.data.tags.TagsProvider.TagAppender; - -import javax.annotation.Nullable; -import java.util.function.Predicate; - -public interface IHTagsProvider { - - @Nullable - default Registry getRegistry() { - return null; - } - - default TagAppender addFromRegistry(IntrinsicTagAppender appender, Predicate predicate) { - var registry = this.getRegistry(); - if (registry == null) { - throw new UnsupportedOperationException("'addFromRegistry' method should not be called unless a registry is specified"); - } - registry.stream().filter(predicate).forEachOrdered(appender::add); - return appender; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/IHMobEffectInstance.java b/src/main/java/org/auioc/mcmod/arnicalib/game/effect/IHMobEffectInstance.java deleted file mode 100644 index 2170e705..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/IHMobEffectInstance.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.effect; - -import net.minecraft.world.effect.MobEffectInstance; - -public interface IHMobEffectInstance { - - MobEffectInstance getHiddenEffect(); - - void setDuration(int duration); - - void setAmplifier(int amplifier); - - void setAmbient(boolean ambient); - - void setVisible(boolean visible); - - void setShowIcon(boolean showIcon); - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectInstanceSerializer.java b/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectInstanceSerializer.java deleted file mode 100644 index 69ae44b4..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectInstanceSerializer.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.effect; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import com.mojang.serialization.Codec; -import com.mojang.serialization.Dynamic; -import com.mojang.serialization.JsonOps; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.util.GsonHelper; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; -import net.neoforged.neoforge.common.EffectCure; -import org.apache.logging.log4j.Marker; -import org.auioc.mcmod.arnicalib.base.log.LogUtil; -import org.auioc.mcmod.arnicalib.base.validate.Validate; -import org.auioc.mcmod.arnicalib.game.registry.RegistryUtils; - -import java.util.List; -import java.util.Optional; - -import static org.auioc.mcmod.arnicalib.ArnicaLib.LOGGER; - -public class MobEffectInstanceSerializer { - - private static final Marker MARKER = LogUtil.getMarker(MobEffectInstanceSerializer.class); - - public static final Codec CODEC = // TODO Test - ExtraCodecs.lazyInitializedCodec( - () -> RecordCodecBuilder.create( - instance -> instance.group( - BuiltInRegistries.MOB_EFFECT.byNameCodec().fieldOf("id").forGetter(MobEffectInstance::getEffect), - ExtraCodecs.intRange(0, Integer.MAX_VALUE).fieldOf("duration").forGetter(MobEffectInstance::getDuration), - ExtraCodecs.intRange(0, 255).fieldOf("amplifier").forGetter(MobEffectInstance::getAmplifier), - Codec.BOOL.optionalFieldOf("ambient", false).forGetter(MobEffectInstance::isAmbient), - Codec.BOOL.optionalFieldOf("show_particles", true).forGetter(MobEffectInstance::isVisible), - Codec.BOOL.optionalFieldOf("show_icon", true).forGetter(MobEffectInstance::showIcon), - MobEffectInstanceSerializer.CODEC.optionalFieldOf("hidden_effect").forGetter((e) -> Optional.ofNullable(((IHMobEffectInstance) e).getHiddenEffect())), - MobEffectInstance.FactorData.CODEC.optionalFieldOf("factor_calculation_data").forGetter(MobEffectInstance::getFactorData), - EffectCure.CODEC.listOf().optionalFieldOf("cures").forGetter((o) -> { - var cures = o.getCures(); - return cures.isEmpty() ? Optional.empty() : Optional.of(List.copyOf(cures)); - }) - ).apply(instance, MobEffectInstanceSerializer::createInstance) - ) - ); - - public static JsonObject toJson(MobEffectInstance instance) { - return GsonHelper.convertToJsonObject( - MobEffectInstanceSerializer.CODEC - .encodeStart(JsonOps.INSTANCE, instance) - .getOrThrow(false, (error) -> LOGGER.error(MARKER, error)), - "MobEffectInstance" - ); - } - - public static MobEffectInstance fromJson(JsonElement json) { - return MobEffectInstanceSerializer.CODEC - .parse(new Dynamic<>(JsonOps.INSTANCE, json)) - .getOrThrow(false, (error) -> LOGGER.error(MARKER, error)); - } - - // ====================================================================== // - - private static MobEffectInstance createInstance( - MobEffect effect, int duration, int amplifier, boolean ambient, boolean visible, boolean showIcon, - Optional hiddenEffect, Optional factorData, - Optional> cures - ) { - var instance = new MobEffectInstance(effect, duration, amplifier, ambient, visible, showIcon, hiddenEffect.orElse(null), Optional.empty()); - instance.getCures().clear(); - cures.ifPresent(effectCures -> instance.getCures().addAll(effectCures)); - return instance; - } - - // ============================================================================================================== // - - - /** - * @deprecated Use {@link MobEffectInstanceSerializer#fromJson(JsonElement)} instead. - */ - @Deprecated(since = "6.0.0", forRemoval = true) - public static MobEffectInstance fromJson(JsonObject json) { - String id = GsonHelper.getAsString(json, "id"); - MobEffect effect = MobEffectRegistry.getOrElseThrow(id); - - int duration = GsonHelper.getAsInt(json, "duration", 1); - - int amplifier = GsonHelper.getAsInt(json, "amplifier", 0); - Validate.isInCloseInterval(0, 255, amplifier); - - boolean ambient = GsonHelper.getAsBoolean(json, "ambient", false); - boolean visible = GsonHelper.getAsBoolean(json, "visible", true); - boolean showIcon = GsonHelper.getAsBoolean(json, "show_icon", true); - - MobEffectInstance hiddenEffect = (MobEffectInstance) null; - if (json.has("hidden_effect")) { - JsonObject hiddenEffectJson = GsonHelper.getAsJsonObject(json, "hidden_effect"); - if (hiddenEffectJson.has("id") && !GsonHelper.getAsString(hiddenEffectJson, "id").equals(id)) throw new JsonSyntaxException("The id of the hidden effect must be unset or equal to the parent effect"); - else hiddenEffectJson.addProperty("id", id); - if (GsonHelper.getAsInt(hiddenEffectJson, "duration", 1) <= duration) throw new JsonSyntaxException("The duration of the hidden effect must be greater than the parent effect"); - hiddenEffect = fromJson(hiddenEffectJson); - } - - Optional factorData = - (json.has("FactorCalculationData")) - ? MobEffectInstance.FactorData.CODEC.parse(new Dynamic<>(JsonOps.INSTANCE, json.get("FactorCalculationData"))).resultOrPartial((error) -> LOGGER.error(MARKER, error)) - : Optional.empty(); - - MobEffectInstance instance = new MobEffectInstance(effect, duration, amplifier, ambient, visible, showIcon, hiddenEffect, factorData); - - // if (json.has("curative_items")) { - // JsonArray curativeItemsJson = GsonHelper.getAsJsonArray(json, "curative_items"); - // List curativeItems = new ArrayList(); - // for (var element : curativeItemsJson) { - // var curativeItemId = GsonHelper.convertToString(element, "curative_item"); - // curativeItems.add(new ItemStack(ItemRegistry.getOrElseThrow(curativeItemId))); - // } - // instance.setCurativeItems(curativeItems); - // } - - return instance; - } - - /** - * @deprecated Use {@link MobEffectInstanceSerializer#toJson} instead. - */ - @Deprecated(since = "6.0.0", forRemoval = true) - public static void toJson(MobEffectInstance instance, JsonObject json) { - json.addProperty("id", RegistryUtils.id(instance.getEffect()).toString()); - json.addProperty("duration", instance.getDuration()); - json.addProperty("amplifier", instance.getAmplifier()); - json.addProperty("ambient", instance.isAmbient()); - json.addProperty("visible", instance.isVisible()); - json.addProperty("show_icon", instance.showIcon()); - - // JsonArray curativeItems = new JsonArray(); - // for (ItemStack itemStack : instance.getCurativeItems()) { - // curativeItems.add(RegistryUtils.id(itemStack.getItem()).toString()); - // } - // json.add("curative_items", curativeItems); - - if (((IHMobEffectInstance) instance).getHiddenEffect() != null) { - JsonObject hiddenEffect = new JsonObject(); - toJson(((IHMobEffectInstance) instance).getHiddenEffect(), hiddenEffect); - json.add("hidden_effect", hiddenEffect); - } - - instance.getFactorData().ifPresent((data) -> { - MobEffectInstance.FactorData.CODEC.encodeStart(JsonOps.INSTANCE, data) - .resultOrPartial((error) -> LOGGER.error(MARKER, error)) - .ifPresent((d) -> json.add("FactorCalculationData", d)); - }); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectPredicates.java b/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectPredicates.java deleted file mode 100644 index 3efc782a..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectPredicates.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.effect; - -import java.util.function.Predicate; - -import net.minecraft.world.effect.MobEffectCategory; -import net.minecraft.world.effect.MobEffectInstance; - -public class MobEffectPredicates { - - public static final Predicate IS_BENEFICIAL = (e) -> e.getEffect().isBeneficial(); - public static final Predicate IS_NOT_BENEFICIAL = (e) -> !e.getEffect().isBeneficial(); - public static final Predicate IS_HARMFUL = (e) -> e.getEffect().getCategory() == MobEffectCategory.HARMFUL; - public static final Predicate IS_NEUTRAL = (e) -> e.getEffect().getCategory() == MobEffectCategory.NEUTRAL; - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectRegistry.java b/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectRegistry.java deleted file mode 100644 index 678e0105..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectRegistry.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.effect; - -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectCategory; -import org.auioc.mcmod.arnicalib.game.registry.RegistryEntryException; -import org.auioc.mcmod.arnicalib.game.registry.RegistryUtils; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.List; -import java.util.Optional; - -public class MobEffectRegistry { - - @Nonnull - public static Optional get(ResourceLocation id) { - return Optional.ofNullable(BuiltInRegistries.MOB_EFFECT.containsKey(id) ? BuiltInRegistries.MOB_EFFECT.get(id) : null); - } - - @Nonnull - public static Optional get(String id) { - return get(new ResourceLocation(id)); - } - - @Nonnull - public static MobEffect getOrElseThrow(ResourceLocation id) { - return get(id).orElseThrow(RegistryEntryException.UNKNOWN_MOB_EFFECT.create(id.toString())); - } - - @Nonnull - public static MobEffect getOrElseThrow(String id) { - return get(id).orElseThrow(RegistryEntryException.UNKNOWN_MOB_EFFECT.create(id)); - } - - public static List all(@Nullable MobEffectCategory type) { - var s = BuiltInRegistries.MOB_EFFECT.stream(); - return type == null ? s.toList() : s.filter((e) -> e.getCategory() == type).toList(); - } - - public static List getHarmfulEffects() { - return all(MobEffectCategory.HARMFUL); - } - - public static List getBeneficialEffects() { - return all(MobEffectCategory.BENEFICIAL); - } - - public static List getNeutralEffects() { - return all(MobEffectCategory.NEUTRAL); - } - - public static List all() { - return all(null); - } - - public static MobEffect random(RandomSource random) { - return RegistryUtils.random(BuiltInRegistries.MOB_EFFECT, random); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectUtils.java deleted file mode 100644 index 96052dd9..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/effect/MobEffectUtils.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.effect; - -import net.minecraft.network.chat.Component; -import net.minecraft.util.StringUtil; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.entity.LivingEntity; - -import java.util.ArrayList; -import java.util.function.Predicate; - -public class MobEffectUtils { - - public static void remove(LivingEntity entity, Predicate predicate) { - var toRemove = new ArrayList(); - - entity.getActiveEffects().forEach( - (instance) -> { - if (predicate.test(instance)) { - toRemove.add(instance.getEffect()); - } - } - ); - - toRemove.forEach(entity::removeEffect); - } - - public static int getLevel(LivingEntity entity, MobEffect effect) { - var instance = entity.getEffect(effect); - return (instance == null) ? 0 : instance.getAmplifier() + 1; - } - - public static MobEffectInstance makeIncurable(MobEffectInstance instance) { - instance.getCures().clear(); - return instance; - } - - - public static void setDuration(MobEffectInstance instance, int duration) { - ((IHMobEffectInstance) instance).setDuration(duration); - } - - public static void setAmplifier(MobEffectInstance instance, int amplifier) { - ((IHMobEffectInstance) instance).setAmplifier(amplifier); - } - - public static Component getDisplayString(MobEffect effect, int amplifier, int duration, float tickrate) { - return Component.empty() - .append(effect.getDisplayName()) - .append(" ") - .append(Component.translatable("enchantment.level." + (amplifier + 1))) - .append(" ") - .append(duration > -1 ? Component.literal(StringUtil.formatTickDuration(duration, tickrate)) : Component.translatable("effect.duration.infinite")); - } - - public static Component getDisplayString(MobEffectInstance instance) { - return getDisplayString(instance.getEffect(), instance.getAmplifier(), instance.getDuration(), 20); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentIterator.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentIterator.java deleted file mode 100644 index dc25ce0d..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentIterator.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import org.auioc.mcmod.arnicalib.game.enchantment.visitor.BiEnchantmentVisitor; -import org.auioc.mcmod.arnicalib.game.enchantment.visitor.QuadEnchantmentVisitor; -import org.auioc.mcmod.arnicalib.game.enchantment.visitor.TriEnchantmentVisitor; - -import java.util.Map; -import java.util.function.Predicate; - -public class EnchantmentIterator { - - public static void run(BiEnchantmentVisitor visitor, Map enchMap) { - for (var enchEntry : enchMap.entrySet()) visitor.accept(enchEntry.getKey(), enchEntry.getValue()); - } - - // ====================================================================== // - - public static void runOnItem(BiEnchantmentVisitor visitor, ItemStack itemStack) { - if (!itemStack.isEmpty()) run(visitor, EnchantmentHelper.getEnchantments(itemStack)); - } - - // ====================================================================== // - - public static void runOnItems(TriEnchantmentVisitor visitor, Iterable itemStacks, Predicate predicate) { - for (var itemStack : itemStacks) { - if (!itemStack.isEmpty() && predicate.test(itemStack)) { - runOnItem((ench, lvl) -> visitor.accept(itemStack, ench, lvl), itemStack); - } - } - } - - public static void runOnItems(TriEnchantmentVisitor visitor, Iterable itemStacks) { - runOnItems(visitor, itemStacks, (o) -> true); - } - - // ====================================================================== // - - public static void runOnLiving(QuadEnchantmentVisitor visitor, LivingEntity living, EquipmentSlot[] slots) { - for (EquipmentSlot slot : slots) { - var itemStack = living.getItemBySlot(slot); - runOnItem((ench, lvl) -> { - if (ench instanceof IValidSlotsVisibleEnchantment _ench) { - if (_ench.isValidSlot(slot)) { - visitor.accept(slot, itemStack, ench, lvl); - } - } else { - visitor.accept(slot, itemStack, ench, lvl); - } - }, itemStack); - } - } - - public static void runOnLiving(QuadEnchantmentVisitor visitor, LivingEntity living) { - runOnLiving(visitor, living, EquipmentSlot.values()); - } - - // ====================================================================== // - - public static void runOnInventory(TriEnchantmentVisitor visitor, Inventory inventory) { - runOnItems(visitor, inventory.items); - runOnItems(visitor, inventory.offhand); - runOnItems(visitor, inventory.armor); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentPredicates.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentPredicates.java deleted file mode 100644 index 438b4afe..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentPredicates.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.Enchantment.Rarity; -import org.auioc.mcmod.arnicalib.game.registry.RegistryUtils; -import org.auioc.mcmod.arnicalib.game.registry.VanillaPredicates; - -import java.util.function.Predicate; - -public class EnchantmentPredicates { - - public static final Predicate IS_VANILLA = (e) -> VanillaPredicates.ID.test(RegistryUtils.id(e)); - - public static final Predicate IS_TREASURE_ONLY = Enchantment::isTreasureOnly; - public static final Predicate IS_CURSE = Enchantment::isCurse; - public static final Predicate IS_TRADEABLE = Enchantment::isTradeable; - public static final Predicate IS_DISCOVERABLE = Enchantment::isDiscoverable; - - public static final Predicate IS_COMMON = (e) -> e.getRarity() == Rarity.COMMON; - public static final Predicate IS_UNCOMMON = (e) -> e.getRarity() == Rarity.UNCOMMON; - public static final Predicate IS_RARE = (e) -> e.getRarity() == Rarity.RARE; - public static final Predicate IS_VERY_RARE = (e) -> e.getRarity() == Rarity.VERY_RARE; - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentRegistry.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentRegistry.java deleted file mode 100644 index 10b4aa2f..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentRegistry.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.enchantment.Enchantment; -import org.auioc.mcmod.arnicalib.game.registry.RegistryEntryException; - -import javax.annotation.Nonnull; -import java.util.Optional; - -public class EnchantmentRegistry { - - @Nonnull - public static Optional get(ResourceLocation id) { - return Optional.ofNullable(BuiltInRegistries.ENCHANTMENT.containsKey(id) ? BuiltInRegistries.ENCHANTMENT.get(id) : null); - } - - @Nonnull - public static Optional get(String id) { - return get(new ResourceLocation(id)); - } - - @Nonnull - public static Enchantment getOrElseThrow(ResourceLocation id) { - return get(id).orElseThrow(RegistryEntryException.UNKNOWN_ENCHANTMENT.create(id.toString())); - } - - @Nonnull - public static Enchantment getOrElseThrow(String id) { - return get(id).orElseThrow(RegistryEntryException.UNKNOWN_ENCHANTMENT.create(id)); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentTagUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentTagUtils.java deleted file mode 100644 index 30d2a783..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentTagUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.Tag; - -public class EnchantmentTagUtils { - - public static void increaseLevel(ListTag tag, int index, int level) { - CompoundTag nbt = tag.getCompound(index); - nbt.putShort("lvl", (short) (nbt.getShort("lvl") + level)); - } - - public static void increaseLevel(ListTag tag, int level) { - for (int i = 0; i < tag.size(); i++) increaseLevel(tag.getCompound(i), level); - } - - public static void increaseLevel(CompoundTag tag, int level) { - tag.putShort("lvl", (short) (tag.getShort("lvl") + level)); - } - - // ====================================================================== // - - public static CompoundTag getHighest(ListTag tag) { - int index = 0; - short highestLevel = 0; - for (int i = 0, l = tag.size(); i < l; i++) { - short lvl = tag.getCompound(i).getShort("lvl"); - if (lvl > highestLevel) { - index = i; - highestLevel = lvl; - } - } - return tag.getCompound(index); - } - - // ====================================================================== // - - public static boolean hasOverLimitEnchantment(ListTag tag) { - for (int i = 0, l = tag.size(); i < l; i++) { - CompoundTag ench = tag.getCompound(i); - if (ench.getShort("lvl") > (EnchantmentRegistry.getOrElseThrow(ench.getString("id"))).getMaxLevel()) { - return true; - } - } - return false; - } - - // ====================================================================== // - - public static int calcTotalLevel(ListTag tag) { - int totalLvl = 0; - for (var enchEntry : tag) { - if (enchEntry.getId() == Tag.TAG_COMPOUND) { - totalLvl += ((CompoundTag) enchEntry).getInt("lvl"); - } - } - return totalLvl; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentUtils.java deleted file mode 100644 index 7ca1fd26..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/EnchantmentUtils.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.nbt.ListTag; -import net.minecraft.world.item.EnchantedBookItem; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.EnchantmentInstance; -import org.apache.commons.lang3.Validate; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -public class EnchantmentUtils { - - public static List> sortByLevel(Map enchantmentMap) { - Validate.notEmpty(enchantmentMap); - return enchantmentMap.entrySet().stream().sorted(Entry.comparingByValue()).toList(); - } - - // ====================================================================== // - - public static Entry getHighest(Map enchantmentMap) { - return sortByLevel(enchantmentMap).get(0); - } - - public static Entry getLowest(Map enchantmentMap) { - var sorted = sortByLevel(enchantmentMap); - return sorted.get(sorted.size() - 1); - } - - public static Entry getHighest(ListTag enchantmentsTag) { - return getHighest(EnchantmentHelper.deserializeEnchantments(enchantmentsTag)); - } - - public static Entry getLowest(ListTag enchantmentsTag) { - return getLowest(EnchantmentHelper.deserializeEnchantments(enchantmentsTag)); - } - - // ============================================================================================================== // - - public static boolean isOverLimit(Enchantment enchantment, int level) { - return level > enchantment.getMaxLevel(); - } - - public static boolean isOverLimit(Entry enchantmentEntry) { - return isOverLimit(enchantmentEntry.getKey(), enchantmentEntry.getValue()); - } - - // ====================================================================== // - - public static boolean hasOverLimitEnchantment(Map enchantmentMap) { - for (var enchantmentEntry : enchantmentMap.entrySet()) { - if (isOverLimit(enchantmentEntry)) return true; - } - return false; - } - - public static boolean hasOverLimitEnchantment(ListTag enchantmentsTag) { - return hasOverLimitEnchantment(EnchantmentHelper.deserializeEnchantments(enchantmentsTag)); - } - - // ====================================================================== // - - public static LinkedHashMap getOverLimitEnchantments(Map enchantmentMap) { - var map = new LinkedHashMap(); - for (var enchantmentEntry : enchantmentMap.entrySet()) { - if (isOverLimit(enchantmentEntry)) { - map.put(enchantmentEntry.getKey(), enchantmentEntry.getValue()); - } - } - return map; - } - - public static LinkedHashMap getOverLimitEnchantments(ListTag enchantmentsTag) { - return getOverLimitEnchantments(EnchantmentHelper.deserializeEnchantments(enchantmentsTag)); - } - - // ============================================================================================================== // - - public static ItemStack createBook(Enchantment enchantment, int lvl) { - return EnchantedBookItem.createForEnchantment(new EnchantmentInstance(enchantment, lvl)); - } - - public static List createBooks(Enchantment enchantment) { - int maxLevel = enchantment.getMaxLevel(); - var list = new ArrayList(maxLevel); - for (int lvl = 1; lvl <= maxLevel; ++lvl) { - list.add(createBook(enchantment, lvl)); - } - return list; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentCategory.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentCategory.java deleted file mode 100644 index 72a256e7..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentCategory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.world.item.AxeItem; -import net.minecraft.world.item.ElytraItem; -import net.minecraft.world.item.FlintAndSteelItem; -import net.minecraft.world.item.FoodOnAStickItem; -import net.minecraft.world.item.HoeItem; -import net.minecraft.world.item.PickaxeItem; -import net.minecraft.world.item.ShieldItem; -import net.minecraft.world.item.ShovelItem; -import net.minecraft.world.item.SpyglassItem; -import net.minecraft.world.item.enchantment.EnchantmentCategory; - -public class HEnchantmentCategory { - - public static final EnchantmentCategory HOE = EnchantmentCategory.create("HOE", HoeItem.class::isInstance); - public static final EnchantmentCategory AXE = EnchantmentCategory.create("AXE", AxeItem.class::isInstance); - public static final EnchantmentCategory SHOVEL = EnchantmentCategory.create("SHOVEL", ShovelItem.class::isInstance); - public static final EnchantmentCategory PICKAXE = EnchantmentCategory.create("PICKAXE", PickaxeItem.class::isInstance); - - public static final EnchantmentCategory SHIELD = EnchantmentCategory.create("SHIELD", ShieldItem.class::isInstance); - - public static final EnchantmentCategory ELYTRA = EnchantmentCategory.create("ELYTRA", ElytraItem.class::isInstance); - - public static final EnchantmentCategory FOOD_ON_A_STACK = EnchantmentCategory.create("FOOD_ON_A_STACK", FoodOnAStickItem.class::isInstance); - - public static final EnchantmentCategory FLINT_AND_STEEL = EnchantmentCategory.create("FLINT_AND_STEEL", FlintAndSteelItem.class::isInstance); - - public static final EnchantmentCategory SPYGLASS = EnchantmentCategory.create("SPYGLASS", SpyglassItem.class::isInstance); - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentPredicate.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentPredicate.java deleted file mode 100644 index 4a468a89..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentPredicate.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.advancements.critereon.MinMaxBounds; -import net.minecraft.core.HolderSet; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.world.item.enchantment.Enchantment; - -import java.util.Map; -import java.util.Optional; - -public record HEnchantmentPredicate( - Optional> enchantments, - MinMaxBounds.Ints level, - Optional properties -) { - - @SuppressWarnings("deprecation") - public boolean test(Enchantment ench, int lvl) { - if (level != MinMaxBounds.Ints.ANY && !level.matches(lvl)) { - return false; - } - if (enchantments.isPresent() && enchantments.get().contains(ench.builtInRegistryHolder())) { - return true; - } - if (properties.isPresent() && !properties.get().test(ench)) { - return false; - } - return true; - } - - public boolean test(Map.Entry enchEntry) { - return test(enchEntry.getKey(), enchEntry.getValue()); - } - - // ============================================================================================================== // - - private static final Codec> ENCHANTMENT_CODEC = BuiltInRegistries.ENCHANTMENT - .holderByNameCodec() - .listOf() - .xmap(HolderSet::direct, holderSet -> holderSet.stream().toList()); - - public static final Codec CODEC = RecordCodecBuilder.create( - instance -> instance.group( - ExtraCodecs.strictOptionalField(ENCHANTMENT_CODEC, "enchantments").forGetter(HEnchantmentPredicate::enchantments), - ExtraCodecs.strictOptionalField(MinMaxBounds.Ints.CODEC, "level", MinMaxBounds.Ints.ANY).forGetter(HEnchantmentPredicate::level), - ExtraCodecs.strictOptionalField(HEnchantmentPropertiesPredicate.CODEC, "properties").forGetter(HEnchantmentPredicate::properties) - ) - .apply(instance, HEnchantmentPredicate::new) - ); - - // ============================================================================================================== // - - public static HEnchantmentPredicate.Builder builder() { - return new Builder(); - } - - public static class Builder { - - private Optional> enchantments = Optional.empty(); - private MinMaxBounds.Ints level = MinMaxBounds.Ints.ANY; - private Optional properties = Optional.empty(); - - private Builder() { } - - @SuppressWarnings("deprecation") - public Builder enchantments(Enchantment... enchantments) { - this.enchantments = Optional.of(HolderSet.direct(Enchantment::builtInRegistryHolder, enchantments)); - return this; - } - - public Builder level(MinMaxBounds.Ints level) { - this.level = level; - return this; - } - - public Builder properties(HEnchantmentPropertiesPredicate properties) { - this.properties = Optional.of(properties); - return this; - } - - public HEnchantmentPredicate build() { - return new HEnchantmentPredicate(enchantments, level, properties); - } - - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentPropertiesPredicate.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentPropertiesPredicate.java deleted file mode 100644 index 9bd8f12b..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/HEnchantmentPropertiesPredicate.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.world.item.enchantment.Enchantment; -import org.auioc.mcmod.arnicalib.game.codec.EnumCodec; - -import java.util.Optional; -import java.util.function.Predicate; - -public record HEnchantmentPropertiesPredicate( - Optional rarity, - Optional curse, - Optional treasureOnly, - Optional tradeable, - Optional discoverable, - Optional allowedOnBooks -) implements Predicate { - - @Override - public boolean test(Enchantment ench) { - if (rarity.isPresent() && !rarity.get().equals(ench.getRarity())) { - return false; - } - if (curse.isPresent() && !curse.get().equals(ench.isCurse())) { - return false; - } - if (treasureOnly.isPresent() && !treasureOnly.get().equals(ench.isTreasureOnly())) { - return false; - } - if (tradeable.isPresent() && !tradeable.get().equals(ench.isTradeable())) { - return false; - } - if (discoverable.isPresent() && !discoverable.get().equals(ench.isDiscoverable())) { - return false; - } - if (allowedOnBooks.isPresent() && !allowedOnBooks.get().equals(ench.isAllowedOnBooks())) { - return false; - } - return true; - } - - // ============================================================================================================== // - - public static final Codec CODEC = RecordCodecBuilder.create( - instance -> instance.group( - ExtraCodecs.strictOptionalField(EnumCodec.byNameLowerCase(Enchantment.Rarity.class), "rarity").forGetter(HEnchantmentPropertiesPredicate::rarity), - ExtraCodecs.strictOptionalField(Codec.BOOL, "curse").forGetter(HEnchantmentPropertiesPredicate::curse), - ExtraCodecs.strictOptionalField(Codec.BOOL, "treasure_only").forGetter(HEnchantmentPropertiesPredicate::treasureOnly), - ExtraCodecs.strictOptionalField(Codec.BOOL, "tradeable").forGetter(HEnchantmentPropertiesPredicate::tradeable), - ExtraCodecs.strictOptionalField(Codec.BOOL, "discoverable").forGetter(HEnchantmentPropertiesPredicate::discoverable), - ExtraCodecs.strictOptionalField(Codec.BOOL, "allowed_on_books").forGetter(HEnchantmentPropertiesPredicate::allowedOnBooks) - ) - .apply(instance, HEnchantmentPropertiesPredicate::new) - ); - - // ============================================================================================================== // - - public static HEnchantmentPropertiesPredicate.Builder builder() { - return new Builder(); - } - - public static class Builder { - - private Optional rarity = Optional.empty(); - private Optional curse = Optional.empty(); - private Optional treasureOnly = Optional.empty(); - private Optional tradeable = Optional.empty(); - private Optional discoverable = Optional.empty(); - private Optional allowedOnBooks = Optional.empty(); - - private Builder() { } - - public Builder rarity(Enchantment.Rarity rarity) { - this.rarity = Optional.of(rarity); - return this; - } - - public Builder curse(boolean curse) { - this.curse = Optional.of(curse); - return this; - } - - public Builder treasureOnly(boolean treasureOnly) { - this.treasureOnly = Optional.of(treasureOnly); - return this; - } - - public Builder tradeable(boolean tradeable) { - this.tradeable = Optional.of(tradeable); - return this; - } - - public Builder discoverable(boolean discoverable) { - this.discoverable = Optional.of(discoverable); - return this; - } - - public Builder allowedOnBooks(boolean allowedOnBooks) { - this.allowedOnBooks = Optional.of(allowedOnBooks); - return this; - } - - public HEnchantmentPropertiesPredicate build() { - return new HEnchantmentPropertiesPredicate(rarity, curse, treasureOnly, tradeable, discoverable, allowedOnBooks); - } - - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/IEnchantmentAttachableObject.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/IEnchantmentAttachableObject.java deleted file mode 100644 index f8ccd683..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/IEnchantmentAttachableObject.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.world.item.enchantment.Enchantment; - -import javax.annotation.Nullable; -import java.util.Map; - -public interface IEnchantmentAttachableObject { - - @Nullable - default Map getEnchantments() { - return null; - } - - default void addEnchantment(Enchantment ench, int lvl) { - throw new UnsupportedOperationException("Adding enchantment is not supported by default"); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/IValidSlotsVisibleEnchantment.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/IValidSlotsVisibleEnchantment.java deleted file mode 100644 index 6b628c5e..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/IValidSlotsVisibleEnchantment.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment; - -import net.minecraft.world.entity.EquipmentSlot; -import org.apache.commons.lang3.ArrayUtils; - -public interface IValidSlotsVisibleEnchantment { - - default EquipmentSlot[] getValidSlots() { - return new EquipmentSlot[] {}; - } - - default boolean isValidSlot(EquipmentSlot slot) { - return ArrayUtils.contains(getValidSlots(), slot); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/BiEnchantmentVisitor.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/BiEnchantmentVisitor.java deleted file mode 100644 index 060dcf31..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/BiEnchantmentVisitor.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment.visitor; - -import net.minecraft.world.item.enchantment.Enchantment; - -import java.util.function.BiConsumer; - -public interface BiEnchantmentVisitor extends BiConsumer { - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/QuadEnchantmentVisitor.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/QuadEnchantmentVisitor.java deleted file mode 100644 index 1d08520d..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/QuadEnchantmentVisitor.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment.visitor; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import org.auioc.mcmod.arnicalib.base.function.QuadConsumer; - -public interface QuadEnchantmentVisitor extends QuadConsumer { - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/TriEnchantmentVisitor.java b/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/TriEnchantmentVisitor.java deleted file mode 100644 index 4bde8c94..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/enchantment/visitor/TriEnchantmentVisitor.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.enchantment.visitor; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; -import org.auioc.mcmod.arnicalib.base.function.TriConsumer; - -public interface TriEnchantmentVisitor extends TriConsumer { - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityCasters.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityCasters.java deleted file mode 100644 index 46edebe9..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityCasters.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity; - -import java.util.function.Function; - -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.Player; - -public class EntityCasters { - - public static final Function TO_LIVING = (entity) -> (LivingEntity) entity; - public static final Function TO_SERVER_PLAYER = (player) -> (ServerPlayer) player; - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityPredicates.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityPredicates.java deleted file mode 100644 index f2d2052c..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityPredicates.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity; - -import net.minecraft.client.player.LocalPlayer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.entity.MobType; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.entity.projectile.Projectile; -import net.neoforged.neoforge.common.util.FakePlayer; - -import java.util.function.Predicate; - -public class EntityPredicates { - - public static final Predicate IS_LIVING = LivingEntity.class::isInstance; - public static final Predicate IS_PLAYER = Player.class::isInstance; - public static final Predicate IS_LOCAL_PLAYER = LocalPlayer.class::isInstance; - public static final Predicate IS_SERVER_PLAYER = ServerPlayer.class::isInstance; - public static final Predicate IS_FAKE_PLAYER = FakePlayer.class::isInstance; - public static final Predicate IS_PROJECTILE = Projectile.class::isInstance; - - public static final Predicate IS_FRIENDLY = (entity) -> getCategory(entity).isFriendly(); - public static final Predicate IS_PERSISTENT = (entity) -> getCategory(entity).isPersistent(); - public static final Predicate IS_MISC = (entity) -> getCategory(entity) == MobCategory.MISC; - public static final Predicate IS_MONSTER = (entity) -> getCategory(entity) == MobCategory.MONSTER; - public static final Predicate IS_CREATURE = (entity) -> getCategory(entity) == MobCategory.CREATURE; - public static final Predicate IS_AMBIENT = (entity) -> getCategory(entity) == MobCategory.AMBIENT; - public static final Predicate IS_AXOLOTLS = (entity) -> getCategory(entity) == MobCategory.AXOLOTLS; - public static final Predicate IS_UNDERGROUND_WATER_CREATURE = (entity) -> getCategory(entity) == MobCategory.UNDERGROUND_WATER_CREATURE; - public static final Predicate IS_WATER_CREATURE = (entity) -> getCategory(entity) == MobCategory.WATER_CREATURE; - public static final Predicate IS_WATER_AMBIENT = (entity) -> getCategory(entity) == MobCategory.WATER_AMBIENT; - - public static final Predicate IS_UNDEFINED = (living) -> living.getMobType() == MobType.UNDEFINED; - public static final Predicate IS_DEFINED = (living) -> living.getMobType() != MobType.UNDEFINED; - public static final Predicate IS_UNDEAD = (living) -> living.getMobType() == MobType.UNDEAD; - public static final Predicate IS_ARTHROPOD = (living) -> living.getMobType() == MobType.ARTHROPOD; - public static final Predicate IS_ILLAGER = (living) -> living.getMobType() == MobType.ILLAGER; - public static final Predicate IS_WATER = (living) -> living.getMobType() == MobType.WATER; - - private static MobCategory getCategory(Entity entity) { - return entity.getType().getCategory(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityTypePredicates.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityTypePredicates.java deleted file mode 100644 index 1577def9..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityTypePredicates.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity; - -import java.util.function.Predicate; - -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.MobCategory; - -public class EntityTypePredicates { - - public static final Predicate> IS_FRIENDLY = (type) -> getCategory(type).isFriendly(); - public static final Predicate> IS_PERSISTENT = (type) -> getCategory(type).isPersistent(); - - public static final Predicate> IS_MISC = (type) -> getCategory(type) == MobCategory.MISC; - public static final Predicate> IS_MONSTER = (type) -> getCategory(type) == MobCategory.MONSTER; - public static final Predicate> IS_CREATURE = (type) -> getCategory(type) == MobCategory.CREATURE; - public static final Predicate> IS_AMBIENT = (type) -> getCategory(type) == MobCategory.AMBIENT; - public static final Predicate> IS_AXOLOTLS = (type) -> getCategory(type) == MobCategory.AXOLOTLS; - public static final Predicate> IS_UNDERGROUND_WATER_CREATURE = (type) -> getCategory(type) == MobCategory.UNDERGROUND_WATER_CREATURE; - public static final Predicate> IS_WATER_CREATURE = (type) -> getCategory(type) == MobCategory.WATER_CREATURE; - public static final Predicate> IS_WATER_AMBIENT = (type) -> getCategory(type) == MobCategory.WATER_AMBIENT; - - private static MobCategory getCategory(EntityType entityType) { - return entityType.getCategory(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityUtils.java deleted file mode 100644 index 2632608c..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/EntityUtils.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity; - -import org.auioc.mcmod.arnicalib.game.world.LevelUtils; -import net.minecraft.core.Vec3i; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceKey; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.animal.axolotl.Axolotl; -import net.minecraft.world.level.Level; -import net.minecraft.world.phys.Vec3; - -public class EntityUtils { - - public static void teleportTo(Entity entity, Vec3i pos) { - entity.teleportTo(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 0.5D); - } - - public static void teleportTo(Entity entity, Vec3 pos) { - entity.teleportTo(pos.x, pos.y, pos.z); - } - - public static void teleportTo(Entity entity, ResourceKey dim, Vec3 pos) { - entity.changeDimension(LevelUtils.getLevel(dim), LevelUtils.createSimpleTeleporter(pos)); - } - - public static void teleportTo(Entity entity, ResourceKey dim, Vec3i pos) { - entity.changeDimension(LevelUtils.getLevel(dim), LevelUtils.createSimpleTeleporter(pos)); - } - - - public static Vec3 calcVelocity(Entity entity) { - double vX = entity.getX() - entity.xOld; - double vY = entity.getY() - entity.yOld; - double vZ = entity.getZ() - entity.zOld; - return new Vec3(vX, vY, vZ); - } - - public static double calcSpeed(Entity entity) { - return calcVelocity(entity).length(); - } - - - public static Component getFacing8WindDirection(Entity entity) { - float yaw = Mth.wrapDegrees(entity.getYRot()); - int d8 = (int) Math.floor((yaw - 180.0F) / 45.0F + 0.5F) & 7; - return Component.translatable("direction.8wind." + d8); - } - - - public static Component getAxolotlVariantName(Axolotl.Variant variant) { - return Component.translatable("entity.minecraft.axolotl.variant." + variant.getName()); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/MobStance.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/MobStance.java deleted file mode 100644 index 77e5b3c8..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/MobStance.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity; - -public enum MobStance { - NEUTRAL, HOSTILE, DEFAULT -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/player/AddrUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/player/AddrUtils.java deleted file mode 100644 index aadf00de..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/player/AddrUtils.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity.player; - -import io.netty.channel.local.LocalAddress; -import net.minecraft.network.Connection; -import net.minecraft.server.level.ServerPlayer; - -import javax.annotation.Nullable; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -public class AddrUtils { - - @Nullable - public static String getIp(Connection connection) { - SocketAddress addr = connection.getRemoteAddress(); - if (addr instanceof InetSocketAddress) { - return ((InetSocketAddress) addr).getAddress().getHostAddress(); - } else if (addr instanceof LocalAddress) { - return addr.toString(); - } - return null; - } - - @Nullable - public static String getPlayerIp(ServerPlayer player) { - return getIp(player.connection.connection); - } - - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/player/PlayerUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/player/PlayerUtils.java deleted file mode 100644 index 3ecc17b4..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/player/PlayerUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity.player; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import org.auioc.mcmod.arnicalib.game.item.ItemUtils; - -import javax.annotation.Nullable; - -public class PlayerUtils { - - - /** - * Gives the specified item to the specified player. If the player's inventory can not hold it, the itemstack(s) will be dropped in the world at the player's position. - * - * @param player the player to give the item to - * @param item the item to give - * @param count the count of the item - * @param nbt the nbt of the item - * @param fakeItem if {@code true}, will generate a fake {@link ItemEntity} at the player's position on success - * @param playSound if {@code true}, will play the {@link SoundEvents#ITEM_PICKUP} at the player's position on success - * @since 5.1.4 - */ - public static void giveItem(ServerPlayer player, Item item, int count, @Nullable CompoundTag nbt, boolean fakeItem, boolean playSound) { - int maxStackSize = ItemUtils.getMaxStackSize(item); - int remainingCount = count; - while (remainingCount > 0) { - int stackSize = Math.min(maxStackSize, remainingCount); - remainingCount -= stackSize; - var itemStack = ItemUtils.createItemStack(item, stackSize, nbt); - if (player.getInventory().add(itemStack) && itemStack.isEmpty()) { - if (fakeItem) { - itemStack.setCount(1); - var itemEntity = player.drop(itemStack, false); - if (itemEntity != null) itemEntity.makeFakeItem(); - } - if (playSound) { - player.level().playSound( - (Player) null, player.getX(), player.getY(), player.getZ(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, 0.2F, - ((player.getRandom().nextFloat() - player.getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F - ); - } - player.inventoryMenu.broadcastChanges(); - } else { - var itemEntity = player.drop(itemStack, false); - if (itemEntity != null) { - itemEntity.setNoPickUpDelay(); - itemEntity.setTarget(player.getUUID()); - } - } - } - } - - public static void giveItem(ServerPlayer player, Item item) { - giveItem(player, item, 1, null, true, true); - } - - public static void giveItem(ServerPlayer player, ItemStack itemStack) { - giveItem(player, itemStack.getItem(), itemStack.getCount(), itemStack.getTag(), true, true); - } - - public static String toString(Player player) { - return String.format( - "%s(%s) at %s in %s", - player.getName().getString(), - player.getStringUUID(), - player.position(), - (player.level() == null) ? "~NULL~" : player.level().toString() - ); - } - - public static boolean isOp(ServerPlayer player) { - return player.getServer().getPlayerList().isOp(player.getGameProfile()); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/ITippedArrow.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/ITippedArrow.java deleted file mode 100644 index 1a982729..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/ITippedArrow.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity.projectile; - -import java.util.Set; - -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.item.alchemy.Potion; - -public interface ITippedArrow { - - Set getEffects(); - - Potion getPotion(); - - void setPotion(Potion potion); - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/ProjectileUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/ProjectileUtils.java deleted file mode 100644 index edc3cc88..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/entity/projectile/ProjectileUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.entity.projectile; - -import javax.annotation.Nullable; - -import net.minecraft.world.entity.projectile.Projectile; -import net.minecraft.world.phys.Vec3; - -public class ProjectileUtils { - - @Nullable - public static Vec3 getShootingPosition(Projectile projectile) { - return ((IHProjectile) projectile).getShootingPosition(); - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/FishingRodCastEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/FishingRodCastEvent.java similarity index 60% rename from src/main/java/org/auioc/mcmod/arnicalib/game/event/server/FishingRodCastEvent.java rename to src/main/java/org/auioc/mcmod/arnicalib/game/event/FishingRodCastEvent.java index b600f180..66daddef 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/FishingRodCastEvent.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/FishingRodCastEvent.java @@ -1,58 +1,67 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.server; - -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.item.ItemStack; - -public class FishingRodCastEvent extends ServerPlayerEvent { - - private final ItemStack fishingRod; - private int speedBonus; - private int luckBonus; - - public FishingRodCastEvent(ServerPlayer serverPlayer, ItemStack fishingRod, int speedBonus, int luckBonus) { - super(serverPlayer); - this.fishingRod = fishingRod; - this.speedBonus = speedBonus; - this.luckBonus = luckBonus; - } - - public ItemStack getFishingRod() { - return fishingRod; - } - - public int getSpeedBonus() { - return speedBonus; - } - - public void setSpeedBonus(int speedBonus) { - this.speedBonus = speedBonus; - } - - public int getLuckBonus() { - return luckBonus; - } - - public void setLuckBonus(int luckBonus) { - this.luckBonus = luckBonus; - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.item.FishingRodItem; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.common.NeoForge; +import org.auioc.mcmod.arnicalib.mod.event.AHEventHooks; + +/** + * Fired on the {@link NeoForge#EVENT_BUS} on SERVER side only. + * + * @see FishingRodItem#use + * @see AHEventHooks#preFishingRodCast + */ +public class FishingRodCastEvent extends ServerPlayerEvent { + + private final ItemStack fishingRod; + private int timeReduction; + private int luckBonus; + + public FishingRodCastEvent(ServerPlayer player, ItemStack fishingRod, int timeReduction, int luckBonus) { + super(player); + this.fishingRod = fishingRod; + this.timeReduction = timeReduction; + this.luckBonus = luckBonus; + } + + public ItemStack getFishingRod() { + return fishingRod; + } + + public int getTimeReduction() { + return timeReduction; + } + + public void setTimeReduction(int timeReduction) { + this.timeReduction = timeReduction; + } + + public int getLuckBonus() { + return luckBonus; + } + + public void setLuckBonus(int luckBonus) { + this.luckBonus = luckBonus; + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/ItemAbilityCheckEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ItemAbilityCheckEvent.java new file mode 100644 index 00000000..2dd4fe69 --- /dev/null +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ItemAbilityCheckEvent.java @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + +import net.minecraft.world.item.ItemStack; +import net.neoforged.bus.api.Event; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.neoforge.common.ItemAbility; +import org.auioc.mcmod.arnicalib.base.event.EventResult; + +/** + * @since 7.0.0 + */ +public class ItemAbilityCheckEvent extends Event implements ICancellableEvent { + + private final ItemStack item; + private final ItemAbility ability; + private EventResult result = EventResult.DEFAULT; + + public ItemAbilityCheckEvent(ItemStack item, ItemAbility ability) { + this.item = item; + this.ability = ability; + } + + public ItemStack getItem() { + return item; + } + + public ItemAbility getAbility() { + return ability; + } + + public void setResult(EventResult result) { + this.result = result; + } + + public boolean canPerformAction() { + if (this.isCanceled()) { + return false; + } + if (result == EventResult.DEFAULT) { + return item.getItem().canPerformAction(item, ability); + } else if (result == EventResult.ALLOW) { + return true; + } else if (result == EventResult.DENY) { + return false; + } + throw new IllegalStateException(); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/ItemDamageEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ItemDamageEvent.java new file mode 100644 index 00000000..731617c0 --- /dev/null +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ItemDamageEvent.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import net.neoforged.bus.api.Event; +import net.neoforged.neoforge.common.NeoForge; +import org.auioc.mcmod.arnicalib.mod.event.AHEventHooks; + +import javax.annotation.Nullable; +import java.util.function.Consumer; + +/** + * Fired on the {@link NeoForge#EVENT_BUS} on SERVER side only. + * + * @see ItemStack#applyDamage(int, LivingEntity, Consumer) + * @see AHEventHooks#onApplyItemDamage + * @since 7.0.0 + */ +public class ItemDamageEvent extends Event { + + private final ItemStack item; + private final int originalDamage; + private int newDamage; + @Nullable + private final LivingEntity living; + + public ItemDamageEvent(ItemStack item, int newDamage, @Nullable LivingEntity living) { + this.item = item; + this.originalDamage = item.getDamageValue(); + this.newDamage = newDamage; + this.living = living; + } + + public ItemStack getItem() { + return item; + } + + public int getOriginalDamage() { + return originalDamage; + } + + public int getNewDamage() { + return newDamage; + } + + public void setNewDamage(int newDamage) { + this.newDamage = newDamage; + } + + @Nullable + public LivingEntity getEntity() { + return living; + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/PistonPushableEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/PistonPushableEvent.java similarity index 78% rename from src/main/java/org/auioc/mcmod/arnicalib/game/event/common/PistonPushableEvent.java rename to src/main/java/org/auioc/mcmod/arnicalib/game/event/PistonPushableEvent.java index b961b03d..14c039db 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/PistonPushableEvent.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/PistonPushableEvent.java @@ -1,54 +1,63 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.common; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.bus.api.ICancellableEvent; -import net.neoforged.neoforge.event.level.BlockEvent; - -public class PistonPushableEvent extends BlockEvent implements ICancellableEvent { - - private final Direction movement; - private final boolean allowDestroy; - private final Direction facing; - - public PistonPushableEvent(BlockState blockState, Level level, BlockPos blockPos, Direction movement, boolean allowDestroy, Direction facing) { - super(level, blockPos, blockState); - this.movement = movement; - this.allowDestroy = allowDestroy; - this.facing = facing; - } - - public Direction getMovement() { - return movement; - } - - public boolean isAllowDestroy() { - return allowDestroy; - } - - public Direction getFacing() { - return facing; - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.level.BlockEvent; +import org.auioc.mcmod.arnicalib.mod.event.AHEventHooks; + +/** + * Fired on the {@link NeoForge#EVENT_BUS} on BOTH logical sides. + * + * @see PistonBaseBlock#isPushable + * @see AHEventHooks#onPistonCheckPushable + */ +public class PistonPushableEvent extends BlockEvent implements ICancellableEvent { + + private final Direction movement; + private final boolean allowDestroy; + private final Direction facing; + + public PistonPushableEvent(BlockState blockState, Level level, BlockPos blockPos, Direction movement, boolean allowDestroy, Direction facing) { + super(level, blockPos, blockState); + this.movement = movement; + this.allowDestroy = allowDestroy; + this.facing = facing; + } + + public Direction getMovement() { + return movement; + } + + public boolean isAllowDestroy() { + return allowDestroy; + } + + public Direction getFacing() { + return facing; + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/PlayerEatEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/PlayerEatEvent.java similarity index 61% rename from src/main/java/org/auioc/mcmod/arnicalib/game/event/common/PlayerEatEvent.java rename to src/main/java/org/auioc/mcmod/arnicalib/game/event/PlayerEatEvent.java index df272587..46f38381 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/PlayerEatEvent.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/PlayerEatEvent.java @@ -1,72 +1,70 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.common; - -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.food.FoodData; -import net.minecraft.world.item.ItemStack; -import net.neoforged.bus.api.ICancellableEvent; -import net.neoforged.neoforge.event.entity.player.PlayerEvent; - -public class PlayerEatEvent extends PlayerEvent implements ICancellableEvent { - - private final ItemStack food; - private final FoodData foodData; - private int nutrition = 0; - private float saturationModifier = 0.0F; - - public PlayerEatEvent(Player player, ItemStack food, FoodData foodData) { - super(player); - this.food = food; - this.foodData = foodData; - if (food.isEdible()) { - var p = food.getFoodProperties(player); - if (p != null) { - this.nutrition = p.getNutrition(); - this.saturationModifier = p.getSaturationModifier(); - } - } - } - - public ItemStack getFood() { - return food; - } - - public FoodData getFoodData() { - return foodData; - } - - public int getNutrition() { - return this.nutrition; - } - - public float getSaturationModifier() { - return this.saturationModifier; - } - - public void setNutrition(int nutrition) { - this.nutrition = nutrition; - } - - public void setSaturationModifier(float saturationModifier) { - this.saturationModifier = saturationModifier; - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.food.FoodProperties; +import net.minecraft.world.item.ItemStack; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import org.auioc.mcmod.arnicalib.mod.event.AHEventHooks; + +/** + * Fired on the {@link NeoForge#EVENT_BUS} on BOTH logical sides. + * + * @see FoodProperties#onConsume + * @see AHEventHooks#onPlayerEat + */ +public class PlayerEatEvent extends PlayerEvent implements ICancellableEvent { + + private final ItemStack food; + private int nutrition = 0; + private float saturation = 0.0F; + + public PlayerEatEvent(Player player, ItemStack food, int nutrition, float saturation) { + super(player); + this.food = food; + this.nutrition = nutrition; + this.saturation = saturation; + } + + public ItemStack getFood() { + return food; + } + + public int getNutrition() { + return this.nutrition; + } + + public float getSaturation() { + return this.saturation; + } + + public void setNutrition(int nutrition) { + this.nutrition = nutrition; + } + + public void setSaturation(float saturation) { + this.saturation = saturation; + } + + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ServerLoginEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ServerLoginEvent.java similarity index 50% rename from src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ServerLoginEvent.java rename to src/main/java/org/auioc/mcmod/arnicalib/game/event/ServerLoginEvent.java index d8e69846..9cd11623 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ServerLoginEvent.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ServerLoginEvent.java @@ -1,61 +1,79 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.server; - -import net.minecraft.network.Connection; -import net.minecraft.network.protocol.handshake.ClientIntentionPacket; -import net.neoforged.bus.api.Event; -import net.neoforged.bus.api.ICancellableEvent; - -public class ServerLoginEvent extends Event implements ICancellableEvent { - - private final ClientIntentionPacket packet; - private final Connection manager; - private String message; - - public ServerLoginEvent(ClientIntentionPacket packet, Connection manager) { - super(); - this.packet = packet; - this.manager = manager; - } - - public ClientIntentionPacket getPacket() { - return this.packet; - } - - public Connection getNetworkManager() { - return this.manager; - } - - public String getMessage() { - return this.message; - } - - public void cancel() { - this.message = "Disconnected because the ServerLoginEvent was cancelled."; - this.setCanceled(true); - } - - public void cancel(String message) { - this.message = message; - this.setCanceled(true); - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + + +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.handshake.ClientIntentionPacket; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.network.ServerHandshakePacketListenerImpl; +import net.neoforged.bus.api.Event; +import net.neoforged.bus.api.ICancellableEvent; +import net.neoforged.neoforge.common.NeoForge; +import org.auioc.mcmod.arnicalib.mod.event.AHEventHooks; + +/** + * Fired on the {@link NeoForge#EVENT_BUS} on SERVER side only. + * + * @see ServerHandshakePacketListenerImpl#handleIntention + * @see AHEventHooks#onServerLogin + */ +public class ServerLoginEvent extends Event implements ICancellableEvent { + + private final ClientIntentionPacket packet; + private final MinecraftServer server; + private final Connection connection; + private Component message; + + public ServerLoginEvent(ClientIntentionPacket packet, MinecraftServer server, Connection connection) { + super(); + this.packet = packet; + this.server = server; + this.connection = connection; + } + + public ClientIntentionPacket getPacket() { + return packet; + } + + public MinecraftServer getServer() { + return server; + } + + public Connection getConnection() { + return connection; + } + + public Component getMessage() { + return message; + } + + public void cancel() { + this.message = Component.literal("Disconnected because the ServerLoginEvent was cancelled."); + this.setCanceled(true); + } + + public void cancel(Component message) { + this.message = message; + this.setCanceled(true); + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ServerPlayerEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ServerPlayerEvent.java similarity index 74% rename from src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ServerPlayerEvent.java rename to src/main/java/org/auioc/mcmod/arnicalib/game/event/ServerPlayerEvent.java index ec7139ea..c20622d4 100644 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ServerPlayerEvent.java +++ b/src/main/java/org/auioc/mcmod/arnicalib/game/event/ServerPlayerEvent.java @@ -1,38 +1,39 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.server; - -import net.minecraft.server.level.ServerPlayer; -import net.neoforged.neoforge.event.entity.player.PlayerEvent; - -public abstract class ServerPlayerEvent extends PlayerEvent { - - private final ServerPlayer serverPlayer; - - public ServerPlayerEvent(ServerPlayer serverPlayer) { - super(serverPlayer); - this.serverPlayer = serverPlayer; - } - - public ServerPlayer getServerPlayer() { - return serverPlayer; - } - -} +/* + * Copyright (C) 2024-2025 AUIOC.ORG + * + * This file is part of ArnicaLib, a mod made for Minecraft. + * + * ArnicaLib is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +package org.auioc.mcmod.arnicalib.game.event; + +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; + +public class ServerPlayerEvent extends PlayerEvent { + + private final ServerPlayer player; + + public ServerPlayerEvent(ServerPlayer serverPlayer) { + super(serverPlayer); + this.player = serverPlayer; + } + + @Override + public ServerPlayer getEntity() { + return player; + } + +} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientLanguageLoadEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientLanguageLoadEvent.java deleted file mode 100644 index bd1b531e..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientLanguageLoadEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.client; - -import net.minecraft.server.packs.resources.ResourceManager; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.bus.api.Event; -import net.neoforged.fml.event.IModBusEvent; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -@OnlyIn(Dist.CLIENT) -public class ClientLanguageLoadEvent extends Event implements IModBusEvent { - - private final ResourceManager resourceManager; - private final List languageCodes; - private final Map storage; - private final boolean defaultRightToLeft; - - public ClientLanguageLoadEvent(ResourceManager resourceManager, List languageCodes, Map storage, boolean defaultRightToLeft) { - this.resourceManager = resourceManager; - this.languageCodes = Collections.unmodifiableList(languageCodes); - this.storage = storage; - this.defaultRightToLeft = defaultRightToLeft; - } - - public ResourceManager getResourceManager() { - return this.resourceManager; - } - - public List getLanguageCodes() { - return this.languageCodes; - } - - public Map getStorage() { - return this.storage; - } - - public boolean isDefaultRightToLeft() { - return this.defaultRightToLeft; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientPermissionChangedEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientPermissionChangedEvent.java deleted file mode 100644 index 4c3b19ba..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientPermissionChangedEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.client; - -import net.minecraft.client.player.LocalPlayer; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; - -@OnlyIn(Dist.CLIENT) -public class ClientPermissionChangedEvent extends ClientPlayerEvent { - - private final int oldLevel; - private final int newLevel; - - public ClientPermissionChangedEvent(LocalPlayer player, int oldLevel, int newLevel) { - super(player); - this.oldLevel = oldLevel; - this.newLevel = newLevel; - } - - public int getOldLevel() { - return oldLevel; - } - - public int getNewLevel() { - return newLevel; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientPlayerEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientPlayerEvent.java deleted file mode 100644 index 592ee986..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/client/ClientPlayerEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.client; - -import net.minecraft.client.player.LocalPlayer; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.neoforge.event.entity.player.PlayerEvent; - -@OnlyIn(Dist.CLIENT) -public abstract class ClientPlayerEvent extends PlayerEvent { - - private final LocalPlayer clientPlayer; - - public ClientPlayerEvent(LocalPlayer clientPlayer) { - super(clientPlayer); - this.clientPlayer = clientPlayer; - } - - public LocalPlayer getClientPlayer() { - return clientPlayer; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/ItemInventoryTickEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/ItemInventoryTickEvent.java deleted file mode 100644 index 8886b65b..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/common/ItemInventoryTickEvent.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.common; - -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.neoforged.bus.api.ICancellableEvent; -import net.neoforged.neoforge.event.entity.player.PlayerEvent; - -public class ItemInventoryTickEvent extends PlayerEvent implements ICancellableEvent { - - private final Level level; - private final ItemStack itemStack; - private final int index; - private final boolean selected; - - public ItemInventoryTickEvent(Player player, Level level, ItemStack itemStack, int index, boolean selected) { - super(player); - this.level = level; - this.itemStack = itemStack; - this.index = index; - this.selected = selected; - } - - public Level getLevel() { - return this.level; - } - - public ItemStack getItemStack() { - return this.itemStack; - } - - public int getIndex() { - return this.index; - } - - public boolean isSelected() { - return this.selected; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ItemHurtEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ItemHurtEvent.java deleted file mode 100644 index f602a9a8..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ItemHurtEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.server; - -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nullable; - -public class ItemHurtEvent extends ServerPlayerEvent { - - private final ItemStack itemStack; - private final RandomSource random; - private int damage; - - public ItemHurtEvent(ItemStack itemStack, int damage, RandomSource random, @Nullable ServerPlayer player) { - super(player); - this.itemStack = itemStack; - this.damage = damage; - this.random = random; - } - - @Override - @Nullable - public ServerPlayer getServerPlayer() { - return super.getServerPlayer(); - } - - public ItemStack getItemStack() { - return this.itemStack; - } - - public RandomSource getRandom() { - return this.random; - } - - public int getDamage() { - return this.damage; - } - - public void setDamage(int damage) { - this.damage = damage; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/LivingFoodEffectEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/LivingFoodEffectEvent.java deleted file mode 100644 index 06a9e1cc..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/LivingFoodEffectEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.server; - -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.neoforged.bus.api.ICancellableEvent; -import net.neoforged.neoforge.event.entity.living.LivingEvent; - -import java.util.List; - -public class LivingFoodEffectEvent extends LivingEvent implements ICancellableEvent { - - private final ItemStack food; - private final List effects; - - public LivingFoodEffectEvent(LivingEntity living, ItemStack food, List effects) { - super(living); - this.food = food; - this.effects = effects; - } - - public ItemStack getFood() { - return food; - } - - public List getEffects() { - return effects; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ProjectileWeaponReleaseEvent.java b/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ProjectileWeaponReleaseEvent.java deleted file mode 100644 index 86bcf01b..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/event/server/ProjectileWeaponReleaseEvent.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.event.server; - -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.projectile.Projectile; -import net.minecraft.world.item.ItemStack; -import net.neoforged.neoforge.event.entity.living.LivingEvent; - -public class ProjectileWeaponReleaseEvent extends LivingEvent { - - private final ItemStack weapon; - private final Projectile projectile; - - public ProjectileWeaponReleaseEvent(LivingEntity living, ItemStack weapon, Projectile projectile) { - super(living); - this.weapon = weapon; - this.projectile = projectile; - } - - public ItemStack getWeapon() { - return weapon; - } - - public Projectile getProjectile() { - return projectile; - } - -} diff --git a/src/main/java/org/auioc/mcmod/arnicalib/game/gui/GuiUtils.java b/src/main/java/org/auioc/mcmod/arnicalib/game/gui/GuiUtils.java deleted file mode 100644 index c67caeaf..00000000 --- a/src/main/java/org/auioc/mcmod/arnicalib/game/gui/GuiUtils.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (C) 2022-2024 AUIOC.ORG - * - * This file is part of ArnicaLib, a mod made for Minecraft. - * - * ArnicaLib is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - */ - -package org.auioc.mcmod.arnicalib.game.gui; - -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.locale.Language; -import net.minecraft.network.chat.FormattedText; -import net.minecraft.network.chat.contents.PlainTextContents; -import net.minecraft.network.chat.contents.TranslatableContents; -import net.minecraft.util.FormattedCharSequence; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.api.distmarker.OnlyIn; -import net.neoforged.neoforge.client.event.ScreenEvent; - -import java.util.List; -import java.util.Optional; -import java.util.function.Predicate; - -@OnlyIn(Dist.CLIENT) -public class GuiUtils { - - public static List getEventListeners(List listeners, Class clazz) { - return listeners.stream().filter(clazz::isInstance).map(clazz::cast).toList(); - } - - public static List getEventListeners(ScreenEvent.Init event, Class clazz) { - return getEventListeners(event.getListenersList(), clazz); - } - - // ====================================================================== // - - public static List