├── .github └── workflows │ └── publish.yaml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main └── java └── net └── goldenstack └── loot ├── LootContext.java ├── LootEntry.java ├── LootFunction.java ├── LootGenerator.java ├── LootNBT.java ├── LootNumber.java ├── LootPool.java ├── LootPredicate.java ├── LootScore.java ├── LootTable.java ├── Trove.java └── util ├── EnchantmentUtils.java ├── ListOperation.java ├── LootNumberRange.java ├── RelevantEntity.java ├── RelevantTarget.java ├── Template.java ├── VanillaInterface.java ├── nbt ├── NBTPath.java ├── NBTReference.java └── NBTUtils.java └── predicate ├── DamageSourcePredicate.java ├── EntityPredicate.java ├── ItemPredicate.java └── LocationPredicate.java /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | # .github/workflows/publish.yml 2 | 3 | name: Publish 4 | on: 5 | release: 6 | types: [released, prereleased] 7 | jobs: 8 | publish: 9 | name: Release build and publish 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Check out code 13 | uses: actions/checkout@v4 14 | - name: Set up JDK 21 15 | uses: actions/setup-java@v4 16 | with: 17 | distribution: 'zulu' 18 | java-version: 21 19 | - name: Publish to MavenCentral 20 | run: ./gradlew publishToMavenCentral --no-configuration-cache 21 | env: 22 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} 23 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} 24 | ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }} 25 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }} 26 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY_CONTENTS }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.zip 3 | *.rar 4 | *.tar.gz 5 | 6 | .gradle/ 7 | .idea/ 8 | build/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021-2025 Trove contributor(s) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # trove 2 | 3 | Trove is a loot table library for [Minestom](https://github.com/Minestom/Minestom/). It implements 4 | [nearly every](#completeness) feature from vanilla Minecraft. 5 | 6 | --- 7 | 8 | ## Install 9 | 10 | To install, simply add the library via Maven Central: 11 | 12 | ``` kts 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | implementation 'net.minestom:minestom-snapshots:' 19 | 20 | implementation 'net.goldenstack:trove:' 21 | } 22 | ``` 23 | Make sure to include Minestom, or else Trove won't work. 24 | 25 | --- 26 | 27 | ## Usage 28 | 29 | ### Setup 30 | 31 | Trove is designed to be extremely simple to use. 32 | 33 | To obtain a `Map`, simply call `Trove.readTables(Path.of("path_to_loot_tables"))`. Trove will 34 | automatically parse out the loot table hierarchy and include it in the table IDs. 35 | 36 | ### Generation 37 | Loot generation is very simple as well. Calling `LootTable#generate(LootContext)` returns a list of items. 38 | 39 | If you're implementing block drops, just call `LootTable#blockDrop(LootContext, Instance, Point)`. If you're 40 | implementing entity drops, call `LootTable#drop(LootContext, Instance, Point)`. 41 | 42 | TODO: Improve the docs. For now, this might address some concerns: 43 | 44 | https://gist.github.com/RealMangorage/d295f217a988dc0f9a996064e54ce6c8 45 | 46 | --- 47 | 48 | ## Completeness 49 | 50 | TODO 51 | 52 | --- 53 | 54 | ## Contributing 55 | 56 | Feel free to open a PR or an issue. 57 | 58 | Before starting large PRs, make sure to check that it's actually needed; try asking a maintainer. 59 | 60 | By contributing to the Trove project you agree that the entirety of your contribution is licensed identically to Trove, 61 | which is currently under the MIT license. 62 | 63 | --- 64 | 65 | ## License 66 | 67 | This project is licensed under the [MIT](LICENSE) license. 68 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.vanniktech.maven.publish.SonatypeHost 2 | 3 | plugins { 4 | id("java-library") 5 | id("maven-publish") 6 | id("signing") 7 | id("com.vanniktech.maven.publish") version "0.30.0" 8 | } 9 | 10 | group = "net.goldenstack.trove" 11 | version = "3.0" 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | api("org.jetbrains:annotations:24.0.1") 19 | 20 | val minestom = "net.minestom:minestom-snapshots:1_21_5-69b9a5d844" 21 | 22 | compileOnly(minestom) 23 | 24 | testImplementation(minestom) 25 | 26 | testImplementation(platform("org.junit:junit-bom:5.10.0")) 27 | testImplementation("org.junit.jupiter:junit-jupiter") 28 | } 29 | 30 | tasks.test { 31 | useJUnitPlatform() 32 | } 33 | 34 | java { 35 | toolchain { 36 | languageVersion.set(JavaLanguageVersion.of(21)) 37 | } 38 | } 39 | 40 | mavenPublishing { 41 | publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) 42 | 43 | signAllPublications() 44 | 45 | coordinates("net.goldenstack", "trove", version.toString()) 46 | 47 | pom { 48 | name.set("trove") 49 | description.set("Loot table parser and evaluator for Minestom") 50 | url.set("https://github.com/goldenstack/trove") 51 | licenses { 52 | license { 53 | name.set("MIT") 54 | url.set("https://github.com/goldenstack/trove/blob/master/LICENSE") 55 | } 56 | } 57 | developers { 58 | developer { 59 | id.set("goldenstack") 60 | name.set("GoldenStack") 61 | email.set("git@goldenstack.net") 62 | } 63 | } 64 | scm { 65 | connection.set("scm:git:git://github.com/goldenstack/trove.git") 66 | developerConnection.set("scm:git:git@github.com:goldenstack/trove.git") 67 | url.set("https://github.com/goldenstack/trove") 68 | } 69 | } 70 | } 71 | 72 | signing { 73 | useGpgCmd() 74 | sign(publishing.publications) 75 | } 76 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoldenStack/trove/d8f329644c2025cd71802450c7c36a4a6a0c0410/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Aug 17 23:49:03 CDT 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "trove" 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootContext.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.VanillaInterface; 4 | import net.minestom.server.coordinate.Point; 5 | import net.minestom.server.entity.Entity; 6 | import net.minestom.server.entity.Player; 7 | import net.minestom.server.entity.damage.DamageType; 8 | import net.minestom.server.instance.Instance; 9 | import net.minestom.server.instance.block.Block; 10 | import net.minestom.server.item.ItemStack; 11 | import org.jetbrains.annotations.NotNull; 12 | import org.jetbrains.annotations.Nullable; 13 | 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | import java.util.NoSuchElementException; 17 | import java.util.Random; 18 | 19 | /** 20 | * Stores a dynamic amount of information that may be relevant during the generation of loot. 21 | */ 22 | public sealed interface LootContext permits LootContextImpl { 23 | 24 | @NotNull LootContext.Key RANDOM = LootContext.key("minecraft:random"); 25 | @NotNull LootContext.Key EXPLOSION_RADIUS = LootContext.key("minecraft:explosion_radius"); 26 | @NotNull LootContext.Key LAST_DAMAGE_PLAYER = LootContext.key("minecraft:last_damage_player"); 27 | @NotNull LootContext.Key WORLD = LootContext.key("minecraft:world"); 28 | @NotNull LootContext.Key TOOL = LootContext.key("minecraft:tool"); 29 | @NotNull LootContext.Key ENCHANTMENT_ACTIVE = LootContext.key("minecraft:enchantment_active"); 30 | @NotNull LootContext.Key BLOCK_STATE = LootContext.key("minecraft:block_state"); 31 | @NotNull LootContext.Key DAMAGE_SOURCE = LootContext.key("minecraft:damage_source"); 32 | @NotNull LootContext.Key ORIGIN = LootContext.key("minecraft:origin"); 33 | @NotNull LootContext.Key DIRECT_ATTACKING_ENTITY = LootContext.key("minecraft:direct_attacking_entity"); 34 | @NotNull LootContext.Key ATTACKING_ENTITY = LootContext.key("minecraft:attacking_entity"); 35 | @NotNull LootContext.Key THIS_ENTITY = LootContext.key("minecraft:this_entity"); 36 | @NotNull LootContext.Key LUCK = LootContext.key("minecraft:luck"); 37 | @NotNull LootContext.Key ENCHANTMENT_LEVEL = LootContext.key("minecraft:enchantment_level"); 38 | 39 | /** 40 | * Creates a loot context from the provided map of key -> object and vanilla interface. 41 | * @param vanilla this context's interface with vanilla features 42 | * @param data the values of the context 43 | * @return the new context instance 44 | */ 45 | static @NotNull LootContext from(@NotNull VanillaInterface vanilla, @NotNull Map, Object> data) { 46 | return LootContextImpl.from(vanilla, data); 47 | } 48 | 49 | /** 50 | * Creates a key from the provided key. 51 | */ 52 | static LootContext.@NotNull Key key(@NotNull String key) { 53 | return new LootContext.Key<>(key); 54 | } 55 | 56 | /** 57 | * Represents a key that stores information in a loot context. 58 | * @param id the string id of the key 59 | * @param the type parameter of the key 60 | */ 61 | @SuppressWarnings("unused") 62 | record Key(@NotNull String id) {} 63 | 64 | /** 65 | * Returns whether or not this context has the provided key. 66 | * @param key the key to search for 67 | * @return true if this context has the key, false if not 68 | */ 69 | boolean has(@NotNull Key key); 70 | 71 | /** 72 | * Gets the object associated with the provided key, returning null if not. 73 | * @param key the key to search for 74 | * @return the optional value 75 | * @param the type of object desired 76 | */ 77 | @Nullable T get(@NotNull Key key); 78 | 79 | /** 80 | * Gets the object associated with the provided key, returning the default value if not. 81 | * @param key the key to search for 82 | * @param defaultValue the default value to use 83 | * @return the optional value 84 | * @param the type of object desired 85 | */ 86 | @NotNull T get(@NotNull Key key, @NotNull T defaultValue); 87 | 88 | /** 89 | * Gets the object associated with the provided key, throwing an exception if not. 90 | * @param key the key to search for 91 | * @return the object associated with the provided key 92 | * @param the type of object desired 93 | */ 94 | @NotNull T require(@NotNull Key key); 95 | 96 | /** 97 | * Returns this context's vanilla interface. This is not part of normal Minecraft loot contexts, but it's required 98 | * here for integration with other potential Minestom features. 99 | */ 100 | @NotNull VanillaInterface vanilla(); 101 | 102 | } 103 | 104 | record LootContextImpl(@NotNull VanillaInterface vanilla, @NotNull Map data) implements LootContext { 105 | 106 | LootContextImpl { 107 | data = Map.copyOf(data); 108 | } 109 | 110 | static @NotNull LootContext from(@NotNull VanillaInterface vanilla, @NotNull Map, Object> data) { 111 | Map mapped = new HashMap<>(); 112 | for (Map.Entry, Object> entry : data.entrySet()) { 113 | mapped.put(entry.getKey().id(), entry.getValue()); 114 | } 115 | 116 | return new LootContextImpl(vanilla, mapped); 117 | } 118 | 119 | @Override 120 | public boolean has(@NotNull Key key) { 121 | return data.containsKey(key.id()); 122 | } 123 | 124 | @SuppressWarnings("unchecked") 125 | @Override 126 | public @Nullable T get(@NotNull Key key) { 127 | return (T) data.get(key.id()); 128 | } 129 | 130 | @Override 131 | public @NotNull T get(@NotNull Key key, @NotNull T defaultValue) { 132 | T get = get(key); 133 | return get != null ? get : defaultValue; 134 | } 135 | 136 | @Override 137 | public @NotNull T require(@NotNull Key key) { 138 | T get = get(key); 139 | if (get != null) { 140 | return get; 141 | } 142 | 143 | throw new NoSuchElementException("No value for key '" + key + "'"); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootEntry.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.VanillaInterface; 4 | import net.kyori.adventure.key.Key; 5 | import net.minestom.server.MinecraftServer; 6 | import net.minestom.server.codec.Codec; 7 | import net.minestom.server.codec.StructCodec; 8 | import net.minestom.server.instance.block.Block; 9 | import net.minestom.server.item.ItemStack; 10 | import net.minestom.server.item.Material; 11 | import net.minestom.server.registry.DynamicRegistry; 12 | import org.jetbrains.annotations.NotNull; 13 | import org.jetbrains.annotations.Range; 14 | 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | import java.util.Set; 18 | 19 | /** 20 | * An entry in a loot table that can generate a list of {@link Choice choices} that each have their own loot and weight. 21 | */ 22 | @SuppressWarnings("UnstableApiUsage") 23 | public interface LootEntry { 24 | 25 | @NotNull StructCodec CODEC = Codec.RegistryTaggedUnion(registries -> { 26 | class Holder { 27 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 28 | } 29 | return Holder.CODEC; 30 | }, LootEntry::codec, "type"); 31 | 32 | static @NotNull DynamicRegistry> createDefaultRegistry() { 33 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:loot_entries"); 34 | registry.register("alternatives", Alternatives.CODEC); 35 | registry.register("dynamic", Dynamic.CODEC); 36 | registry.register("empty", Empty.CODEC); 37 | registry.register("group", Group.CODEC); 38 | registry.register("item", Item.CODEC); 39 | registry.register("loot_table", LootTable.CODEC); 40 | registry.register("sequence", Sequence.CODEC); 41 | registry.register("tag", Tag.CODEC); 42 | return registry; 43 | } 44 | 45 | /** 46 | * Generates any number of possible choices to choose from when generating loot. 47 | * @param context the context object, to use if required 48 | * @return a list, with undetermined mutability, containing the options that were generated 49 | */ 50 | @NotNull List requestChoices(@NotNull LootContext context); 51 | 52 | /** 53 | * @return the codec that can encode this entry 54 | */ 55 | @NotNull StructCodec codec(); 56 | 57 | /** 58 | * A choice, generated from an entry, that could potentially be chosen. 59 | */ 60 | interface Choice extends LootGenerator { 61 | 62 | /** 63 | * Calculates the weight of this choice, to be used when choosing which choices should be used. 64 | * This number should not be below 1.
65 | * When using the result of this method, be aware of the fact that it's valid for implementations of this method 66 | * to return different values even when the provided context is the identical. 67 | * @param context the context object, to use if required 68 | * @return the weight of this choice 69 | */ 70 | @Range(from = 1L, to = Long.MAX_VALUE) long getWeight(@NotNull LootContext context); 71 | 72 | 73 | /** 74 | * A choice that uses the standard method of generating weight - adding the {@link #weight()} to the {@link #quality()} 75 | * where the quality is multiplied by the provided context's luck ({@link LootContext#LUCK}). 76 | */ 77 | interface Standard extends Choice { 78 | 79 | /** 80 | * The weight of this choice. When calculating the final weight, this value is simply added to the result. 81 | * @return the base weight of this choice 82 | */ 83 | @Range(from = 1L, to = Long.MAX_VALUE) long weight(); 84 | 85 | /** 86 | * The quality of the choice. When calculating the final weight, this number is multiplied by the context's luck 87 | * value, which is stored at the key {@link LootContext#LUCK}. 88 | * @return the quality of the choice 89 | */ 90 | @Range(from = 0L, to = Long.MAX_VALUE) long quality(); 91 | 92 | @Override 93 | default @Range(from = 1L, to = Long.MAX_VALUE) long getWeight(@NotNull LootContext context) { 94 | return Math.max(1, (long) Math.floor(weight() + quality() * context.get(LootContext.LUCK, 0d))); 95 | } 96 | 97 | } 98 | 99 | /** 100 | * A standard single choice entry that only returns itself when its conditions all succeed. 101 | */ 102 | interface Single extends LootEntry, LootEntry.Choice, Standard { 103 | 104 | /** 105 | * @return this choice's predicates 106 | */ 107 | @NotNull List predicates(); 108 | 109 | /** 110 | * Requests choices, returning none if {@link #predicates()} are all true. 111 | * {@inheritDoc} 112 | */ 113 | @Override 114 | default @NotNull List requestChoices(@NotNull LootContext context) { 115 | return LootPredicate.all(predicates(), context) ? List.of(this) : List.of(); 116 | } 117 | 118 | } 119 | 120 | } 121 | 122 | record Alternatives(@NotNull List predicates, @NotNull List children) implements LootEntry { 123 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 124 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Alternatives::predicates, 125 | "children", LootEntry.CODEC.list().optional(List.of()), Alternatives::children, 126 | Alternatives::new 127 | ); 128 | 129 | @Override 130 | public @NotNull List requestChoices(@NotNull LootContext context) { 131 | if (!LootPredicate.all(predicates, context)) return List.of(); 132 | 133 | for (var entry : this.children()) { 134 | var options = entry.requestChoices(context); 135 | if (!options.isEmpty()) { 136 | return options; 137 | } 138 | } 139 | return List.of(); 140 | } 141 | 142 | @Override 143 | public @NotNull StructCodec codec() { 144 | return CODEC; 145 | } 146 | } 147 | 148 | record Dynamic(@NotNull List predicates, @NotNull List functions, 149 | long weight, long quality, @NotNull Key name) implements Choice.Single { 150 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 151 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Dynamic::predicates, 152 | "functions", LootFunction.CODEC.list().optional(List.of()), Dynamic::functions, 153 | "weight", Codec.LONG.optional(1L), Dynamic::weight, 154 | "quality", Codec.LONG.optional(0L), Dynamic::quality, 155 | "name", Codec.KEY, Dynamic::name, 156 | Dynamic::new 157 | ); 158 | 159 | @Override 160 | public @NotNull List generate(@NotNull LootContext context) { 161 | Block block = context.get(LootContext.BLOCK_STATE); 162 | if (block == null) return List.of(); 163 | 164 | return switch (name.asString()) { 165 | case "minecraft:sherds" -> { 166 | List items = new ArrayList<>(); 167 | for (Material material : block.getTag(VanillaInterface.DECORATED_POT_SHERDS)) { 168 | items.add(ItemStack.of(material)); 169 | } 170 | yield items; 171 | } 172 | case "minecraft:contents" -> block.getTag(VanillaInterface.CONTAINER_ITEMS); 173 | default -> List.of(); 174 | }; 175 | } 176 | 177 | @Override 178 | public @NotNull StructCodec codec() { 179 | return CODEC; 180 | } 181 | } 182 | 183 | record Empty(@NotNull List predicates, @NotNull List functions, 184 | long weight, long quality) implements Choice.Single { 185 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 186 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Empty::predicates, 187 | "functions", LootFunction.CODEC.list().optional(List.of()), Empty::functions, 188 | "weight", Codec.LONG.optional(1L), Empty::weight, 189 | "quality", Codec.LONG.optional(0L), Empty::quality, 190 | Empty::new 191 | ); 192 | 193 | @Override 194 | public @NotNull List generate(@NotNull LootContext context) { 195 | return List.of(); 196 | } 197 | 198 | @Override 199 | public @NotNull StructCodec codec() { 200 | return CODEC; 201 | } 202 | } 203 | 204 | record Group(@NotNull List predicates, @NotNull List children) implements LootEntry { 205 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 206 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Group::predicates, 207 | "children", LootEntry.CODEC.list().optional(List.of()), Group::children, 208 | Group::new 209 | ); 210 | 211 | @Override 212 | public @NotNull List requestChoices(@NotNull LootContext context) { 213 | if (!LootPredicate.all(predicates, context)) return List.of(); 214 | 215 | List choices = new ArrayList<>(); 216 | for (var entry : this.children()) { 217 | choices.addAll(entry.requestChoices(context)); 218 | } 219 | return choices; 220 | } 221 | 222 | @Override 223 | public @NotNull StructCodec codec() { 224 | return CODEC; 225 | } 226 | } 227 | 228 | record Item(@NotNull List predicates, @NotNull List functions, 229 | long weight, long quality, @NotNull Material name) implements Choice.Single { 230 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 231 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Item::predicates, 232 | "functions", LootFunction.CODEC.list().optional(List.of()), Item::functions, 233 | "weight", Codec.LONG.optional(1L), Item::weight, 234 | "quality", Codec.LONG.optional(0L), Item::quality, 235 | "name", Material.CODEC, Item::name, 236 | Item::new 237 | ); 238 | 239 | @Override 240 | public @NotNull List generate(@NotNull LootContext context) { 241 | return List.of(LootFunction.apply(functions, ItemStack.of(name), context)); 242 | } 243 | 244 | @Override 245 | public @NotNull StructCodec codec() { 246 | return CODEC; 247 | } 248 | } 249 | 250 | record LootTable(@NotNull List predicates, @NotNull List functions, 251 | long weight, long quality, @NotNull Key value) implements Choice.Single { 252 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 253 | "conditions", LootPredicate.CODEC.list().optional(List.of()), LootTable::predicates, 254 | "functions", LootFunction.CODEC.list().optional(List.of()), LootTable::functions, 255 | "weight", Codec.LONG.optional(1L), LootTable::weight, 256 | "quality", Codec.LONG.optional(0L), LootTable::quality, 257 | "value", Codec.KEY, LootTable::value, 258 | LootTable::new 259 | ); 260 | 261 | @Override 262 | public @NotNull List generate(@NotNull LootContext context) { 263 | var table = context.vanilla().tableRegistry(value); 264 | if (table == null) return List.of(); 265 | 266 | return LootFunction.apply(functions, table.generate(context), context); 267 | } 268 | 269 | @Override 270 | public @NotNull StructCodec codec() { 271 | return CODEC; 272 | } 273 | } 274 | 275 | record Sequence(@NotNull List predicates, @NotNull List children) implements LootEntry { 276 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 277 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Sequence::predicates, 278 | "children", LootEntry.CODEC.list().optional(List.of()), Sequence::children, 279 | Sequence::new 280 | ); 281 | 282 | @Override 283 | public @NotNull List requestChoices(@NotNull LootContext context) { 284 | if (!LootPredicate.all(predicates, context)) return List.of(); 285 | 286 | List options = new ArrayList<>(); 287 | for (var entry : this.children()) { 288 | var choices = entry.requestChoices(context); 289 | if (choices.isEmpty()) { 290 | break; 291 | } 292 | options.addAll(choices); 293 | } 294 | return options; 295 | } 296 | 297 | @Override 298 | public @NotNull StructCodec codec() { 299 | return CODEC; 300 | } 301 | } 302 | 303 | record Tag(@NotNull List predicates, @NotNull List functions, 304 | long weight, long quality, @NotNull String name, boolean expand) implements Choice.Single { 305 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 306 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Tag::predicates, 307 | "functions", LootFunction.CODEC.list().optional(List.of()), Tag::functions, 308 | "weight", Codec.LONG.optional(1L), Tag::weight, 309 | "quality", Codec.LONG.optional(0L), Tag::quality, 310 | "name", Codec.STRING, Tag::name, 311 | "expand", Codec.BOOLEAN, Tag::expand, 312 | Tag::new 313 | ); 314 | 315 | private @NotNull Set getItems() { 316 | return MinecraftServer.getTagManager().getTag(net.minestom.server.gamedata.tags.Tag.BasicType.ITEMS, name).getValues(); 317 | } 318 | 319 | @Override 320 | public @NotNull List requestChoices(@NotNull LootContext context) { 321 | if (!LootPredicate.all(predicates, context)) { 322 | return List.of(); 323 | } else if (!expand) { 324 | return List.of(this); 325 | } 326 | 327 | List choices = new ArrayList<>(); 328 | for (var key : getItems()) { 329 | Material material = Material.fromKey(key); 330 | if (material == null) continue; 331 | choices.add(new Choice() { 332 | @Override 333 | public @Range(from = 1L, to = Long.MAX_VALUE) long getWeight(@NotNull LootContext context) { 334 | return Tag.this.getWeight(context); 335 | } 336 | 337 | @Override 338 | public @NotNull List generate(@NotNull LootContext context) { 339 | return List.of(ItemStack.of(material)); 340 | } 341 | 342 | }); 343 | } 344 | return choices; 345 | } 346 | 347 | @Override 348 | public @NotNull List generate(@NotNull LootContext context) { 349 | List items = new ArrayList<>(); 350 | for (var key : getItems()) { 351 | Material material = Material.fromKey(key); 352 | if (material == null) continue; 353 | 354 | items.add(LootFunction.apply(functions, ItemStack.of(material), context)); 355 | } 356 | 357 | return items; 358 | } 359 | 360 | @Override 361 | public @NotNull StructCodec codec() { 362 | return CODEC; 363 | } 364 | } 365 | 366 | 367 | } 368 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootFunction.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.*; 4 | import net.goldenstack.loot.util.nbt.NBTPath; 5 | import net.goldenstack.loot.util.nbt.NBTReference; 6 | import net.goldenstack.loot.util.nbt.NBTUtils; 7 | import net.goldenstack.loot.util.predicate.ItemPredicate; 8 | import net.kyori.adventure.key.Key; 9 | import net.kyori.adventure.nbt.*; 10 | import net.kyori.adventure.text.Component; 11 | import net.kyori.adventure.util.RGBLike; 12 | import net.minestom.server.MinecraftServer; 13 | import net.minestom.server.ServerFlag; 14 | import net.minestom.server.codec.Codec; 15 | import net.minestom.server.codec.Result; 16 | import net.minestom.server.codec.StructCodec; 17 | import net.minestom.server.codec.Transcoder; 18 | import net.minestom.server.color.Color; 19 | import net.minestom.server.component.DataComponent; 20 | import net.minestom.server.component.DataComponentMap; 21 | import net.minestom.server.component.DataComponents; 22 | import net.minestom.server.entity.*; 23 | import net.minestom.server.entity.attribute.Attribute; 24 | import net.minestom.server.entity.attribute.AttributeModifier; 25 | import net.minestom.server.entity.attribute.AttributeOperation; 26 | import net.minestom.server.gamedata.tags.Tag; 27 | import net.minestom.server.instance.block.Block; 28 | import net.minestom.server.item.ItemStack; 29 | import net.minestom.server.item.Material; 30 | import net.minestom.server.item.book.FilteredText; 31 | import net.minestom.server.item.component.*; 32 | import net.minestom.server.item.enchant.Enchantment; 33 | import net.minestom.server.potion.PotionEffect; 34 | import net.minestom.server.potion.PotionType; 35 | import net.minestom.server.registry.DynamicRegistry; 36 | import net.minestom.server.registry.Registries; 37 | import org.jetbrains.annotations.NotNull; 38 | import org.jetbrains.annotations.Nullable; 39 | 40 | import java.io.IOException; 41 | import java.util.*; 42 | 43 | /** 44 | * A function that allows loot to pass through it, potentially making modifications. 45 | */ 46 | @SuppressWarnings("UnstableApiUsage") 47 | public interface LootFunction { 48 | 49 | @NotNull Codec CODEC = makeCodec().orElse(makeCodec().list().transform(Sequence::new, seq -> ((Sequence) seq).functions())); 50 | 51 | private static StructCodec makeCodec() { 52 | return Codec.RegistryTaggedUnion(registries -> { 53 | class Holder { 54 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 55 | } 56 | return Holder.CODEC; 57 | }, LootFunction::codec, "function"); 58 | } 59 | 60 | static @NotNull DynamicRegistry> createDefaultRegistry() { 61 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:loot_functions"); 62 | registry.register("apply_bonus", ApplyBonus.CODEC); 63 | registry.register("copy_components", CopyComponents.CODEC); 64 | registry.register("copy_custom_data", CopyCustomData.CODEC); 65 | registry.register("copy_name", CopyName.CODEC); 66 | registry.register("copy_state", CopyState.CODEC); 67 | registry.register("enchanted_count_increase", EnchantedCountIncrease.CODEC); 68 | registry.register("enchant_randomly", EnchantRandomly.CODEC); 69 | registry.register("enchant_with_levels", EnchantWithLevels.CODEC); 70 | registry.register("exploration_map", ExplorationMap.CODEC); 71 | registry.register("explosion_decay", ExplosionDecay.CODEC); 72 | registry.register("fill_player_head", FillPlayerHead.CODEC); 73 | registry.register("filtered", Filtered.CODEC); 74 | registry.register("furnace_smelt", FurnaceSmelt.CODEC); 75 | registry.register("limit_count", LimitCount.CODEC); 76 | registry.register("modify_contents", ModifyContents.CODEC); 77 | registry.register("reference", Reference.CODEC); 78 | registry.register("set_attributes", SetAttributes.CODEC); 79 | registry.register("set_banner_pattern", SetBannerPattern.CODEC); 80 | registry.register("set_book_cover", SetBookCover.CODEC); 81 | registry.register("set_components", SetComponents.CODEC); 82 | registry.register("set_contents", SetContents.CODEC); 83 | registry.register("set_count", SetCount.CODEC); 84 | registry.register("set_custom_data", SetCustomData.CODEC); 85 | registry.register("set_custom_model_data", SetCustomModelData.CODEC); 86 | registry.register("set_damage", SetDamage.CODEC); 87 | registry.register("set_enchantments", SetEnchantments.CODEC); 88 | registry.register("set_firework_explosion", SetFireworkExplosion.CODEC); 89 | registry.register("set_fireworks", SetFireworks.CODEC); 90 | registry.register("set_instrument", SetInstrument.CODEC); 91 | registry.register("set_item", SetItem.CODEC); 92 | registry.register("set_loot_table", SetLootTable.CODEC); 93 | registry.register("set_lore", SetLore.CODEC); 94 | registry.register("set_name", SetName.CODEC); 95 | registry.register("set_ominous_bottle_amplifier", SetOminousBottleAmplifier.CODEC); 96 | registry.register("set_potion", SetPotion.CODEC); 97 | registry.register("set_stew_effect", SetStewEffect.CODEC); 98 | registry.register("set_writable_book_pages", SetWritableBookPages.CODEC); 99 | registry.register("set_written_book_pages", SetWrittenBookPages.CODEC); 100 | registry.register("sequence", Sequence.CODEC); 101 | registry.register("toggle_tooltips", ToggleTooltips.CODEC); 102 | return registry; 103 | } 104 | 105 | /** 106 | * Performs any mutations on the provided object and returns the result. 107 | * @param input the input item to this function 108 | * @param context the context object, to use if required 109 | * @return the modified form of the input 110 | */ 111 | @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context); 112 | 113 | /** 114 | * @return the codec that can encode this function 115 | */ 116 | @NotNull StructCodec codec(); 117 | 118 | /** 119 | * Applies each function to the given item consecutively. 120 | * @param functions the functions to apply 121 | * @param item the item to modify 122 | * @param context the context to use 123 | * @return the modified item 124 | */ 125 | static @NotNull ItemStack apply(@NotNull Collection functions, @NotNull ItemStack item, @NotNull LootContext context) { 126 | for (LootFunction function : functions) { 127 | item = function.apply(item, context); 128 | } 129 | return item; 130 | } 131 | 132 | /** 133 | * Applies each function to each of the given items consecutively. 134 | * @param functions the functions to apply 135 | * @param items the items to modify 136 | * @param context the context to use 137 | * @return the modified items 138 | */ 139 | static @NotNull List apply(@NotNull Collection functions, @NotNull List items, @NotNull LootContext context) { 140 | List newItems = new ArrayList<>(items.size()); 141 | for (ItemStack item : items) { 142 | newItems.add(LootFunction.apply(functions, item, context)); 143 | } 144 | return newItems; 145 | } 146 | 147 | record ApplyBonus(@NotNull List predicates, @NotNull DynamicRegistry.Key enchantment, @NotNull Formula.Wrapper formula) implements LootFunction { 148 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 149 | "conditions", LootPredicate.CODEC.list().optional(List.of()), ApplyBonus::predicates, 150 | "enchantment", Codec.RegistryKey(Registries::enchantment), ApplyBonus::enchantment, 151 | StructCodec.INLINE, Formula.CODEC, ApplyBonus::formula, 152 | ApplyBonus::new 153 | ); 154 | 155 | public sealed interface Formula { 156 | 157 | enum FormulaType { 158 | BINOMIAL_WITH_BONUS_COUNT, 159 | ORE_DROPS, 160 | UNIFORM_BONUS_COUNT, 161 | } 162 | 163 | record Wrapper(Formula parameters) { 164 | private static StructCodec wrap(@NotNull StructCodec codec) { 165 | return StructCodec.struct( 166 | "parameters", codec.transform(a->a,a->(T)a), Wrapper::parameters, 167 | Wrapper::new 168 | ); 169 | } 170 | 171 | private static final StructCodec BINOMIAL_WITH_BONUS_COUNT = wrap(BinomialWithBonusCount.CODEC); 172 | private static final StructCodec ORE_DROPS = new StructCodec<>() { 173 | @Override 174 | public @NotNull Result decodeFromMap(@NotNull Transcoder coder, Transcoder.@NotNull MapLike map) { 175 | return new Result.Ok<>(new Wrapper(new OreDrops())); 176 | } 177 | 178 | @Override 179 | public @NotNull Result encodeToMap(@NotNull Transcoder coder, @NotNull Wrapper value, Transcoder.@NotNull MapBuilder map) { 180 | return new Result.Ok<>(map.build()); 181 | } 182 | }; 183 | private static final StructCodec UNIFORM_BONUS_COUNT = wrap(UniformBonusCount.CODEC); 184 | 185 | public static @NotNull StructCodec codec(@NotNull FormulaType type) { 186 | return switch (type) { 187 | case BINOMIAL_WITH_BONUS_COUNT -> BINOMIAL_WITH_BONUS_COUNT; 188 | case ORE_DROPS -> ORE_DROPS; 189 | case UNIFORM_BONUS_COUNT -> UNIFORM_BONUS_COUNT; 190 | }; 191 | } 192 | } 193 | 194 | @NotNull Codec CODEC = Codec.KEY.transform(key -> switch (key.asString()) { 195 | case "minecraft:binomial_with_bonus_count" -> FormulaType.BINOMIAL_WITH_BONUS_COUNT; 196 | case "minecraft:ore_drops" -> FormulaType.ORE_DROPS; 197 | case "minecraft:uniform_bonus_count" -> FormulaType.UNIFORM_BONUS_COUNT; 198 | default -> throw new IllegalArgumentException(); 199 | }, type -> Key.key(type.toString().toLowerCase())).unionType("formula", Wrapper::codec, (Wrapper formula) -> switch (formula.parameters()) { 200 | case BinomialWithBonusCount ignored -> FormulaType.BINOMIAL_WITH_BONUS_COUNT; 201 | case OreDrops ignored -> FormulaType.ORE_DROPS; 202 | case UniformBonusCount ignored -> FormulaType.UNIFORM_BONUS_COUNT; 203 | }); 204 | 205 | int calculate(@NotNull Random random, int count, int level); 206 | 207 | record UniformBonusCount(int bonusMultiplier) implements Formula { 208 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 209 | "bonusMultiplier", StructCodec.INT, UniformBonusCount::bonusMultiplier, 210 | UniformBonusCount::new 211 | ); 212 | 213 | @Override 214 | public int calculate(@NotNull Random random, int count, int level) { 215 | return count + random.nextInt(bonusMultiplier * level + 1); 216 | } 217 | } 218 | 219 | record OreDrops() implements Formula { 220 | public static final @NotNull StructCodec CODEC = StructCodec.struct(OreDrops::new); 221 | 222 | @Override 223 | public int calculate(@NotNull Random random, int count, int level) { 224 | if (level <= 0) return count; 225 | 226 | return count * Math.max(1, random.nextInt(level + 2)); 227 | } 228 | } 229 | 230 | record BinomialWithBonusCount(float probability, int extra) implements Formula { 231 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 232 | "probability", Codec.FLOAT, BinomialWithBonusCount::probability, 233 | "extra", Codec.INT, BinomialWithBonusCount::extra, 234 | BinomialWithBonusCount::new 235 | ); 236 | 237 | @Override 238 | public int calculate(@NotNull Random random, int count, int level) { 239 | for (int i = 0; i < extra + level; i++) { 240 | if (random.nextFloat() < probability) { 241 | count++; 242 | } 243 | } 244 | 245 | return count; 246 | } 247 | } 248 | 249 | } 250 | 251 | @Override 252 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 253 | ItemStack tool = context.get(LootContext.TOOL); 254 | if (tool == null) return input; 255 | 256 | int level = EnchantmentUtils.level(tool, enchantment); 257 | int newCount = formula.parameters().calculate(context.require(LootContext.RANDOM), input.amount(), level); 258 | 259 | return input.withAmount(newCount); 260 | } 261 | 262 | @Override 263 | public @NotNull StructCodec codec() { 264 | return CODEC; 265 | } 266 | } 267 | 268 | record CopyComponents(@NotNull List predicates, @NotNull RelevantTarget source, 269 | @Nullable List> include, @Nullable List> exclude) implements LootFunction { 270 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 271 | "conditions", LootPredicate.CODEC.list().optional(List.of()), CopyComponents::predicates, 272 | "source", RelevantTarget.CODEC, CopyComponents::source, 273 | "include", Codec.KEY.>transform(DataComponent::fromKey, DataComponent::key).list().optional(), CopyComponents::include, 274 | "exclude", Codec.KEY.>transform(DataComponent::fromKey, DataComponent::key).list().optional(), CopyComponents::exclude, 275 | CopyComponents::new 276 | ); 277 | 278 | @Override 279 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 280 | if (!LootPredicate.all(predicates, context)) return input; 281 | 282 | // TODO: Incomplete 283 | throw new UnsupportedOperationException("TODO: Implement Tag for blocks."); 284 | } 285 | 286 | @Override 287 | public @NotNull StructCodec codec() { 288 | return CODEC; 289 | } 290 | } 291 | 292 | record CopyCustomData(@NotNull List predicates, @NotNull LootNBT source, @NotNull List ops) implements LootFunction { 293 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 294 | "conditions", LootPredicate.CODEC.list().optional(List.of()), CopyCustomData::predicates, 295 | "source", LootNBT.CODEC, CopyCustomData::source, 296 | "ops", Operation.CODEC.list(), CopyCustomData::ops, 297 | CopyCustomData::new 298 | ); 299 | 300 | public record Operation(@NotNull NBTPath source, @NotNull NBTPath target, @NotNull Operator op) { 301 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 302 | "source", NBTPath.CODEC, Operation::source, 303 | "target", NBTPath.CODEC, Operation::target, 304 | "op", Operator.SERIALIZER, Operation::op, 305 | Operation::new 306 | ); 307 | 308 | public void execute(@NotNull NBTReference nbt, @NotNull BinaryTag sourceTag) { 309 | List nbts = new ArrayList<>(); 310 | source.get(sourceTag).forEach(ref -> nbts.add(ref.get())); 311 | 312 | if (nbts.isEmpty()) return; 313 | op.merge(nbt, target, nbts); 314 | } 315 | } 316 | 317 | public enum Operator { 318 | REPLACE() { 319 | @Override 320 | public void merge(@NotNull NBTReference nbt, @NotNull NBTPath target, @NotNull List source) { 321 | target.set(nbt, source.getLast()); 322 | } 323 | }, 324 | APPEND() { 325 | @Override 326 | public void merge(@NotNull NBTReference nbt, @NotNull NBTPath target, @NotNull List source) { 327 | List nbts = target.getWithDefaults(nbt, ListBinaryTag::empty); 328 | 329 | for (var ref : nbts) { 330 | source.forEach(ref::listAdd); 331 | } 332 | } 333 | }, 334 | MERGE() { 335 | @Override 336 | public void merge(@NotNull NBTReference nbt, @NotNull NBTPath target, @NotNull List source) { 337 | List nbts = target.getWithDefaults(nbt, CompoundBinaryTag::empty); 338 | 339 | for (var ref : nbts) { 340 | if (ref.get() instanceof CompoundBinaryTag compound) { 341 | for (var nbt2 : source) { 342 | if (nbt2 instanceof CompoundBinaryTag compound2) { 343 | ref.set(NBTUtils.merge(compound, compound2)); 344 | } 345 | } 346 | } 347 | } 348 | } 349 | }; 350 | 351 | public static final @NotNull Codec SERIALIZER = Codec.Enum(Operator.class); 352 | 353 | public abstract void merge(@NotNull NBTReference nbt, @NotNull NBTPath target, @NotNull List source); 354 | } 355 | 356 | @Override 357 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 358 | if (!LootPredicate.all(predicates, context)) return input; 359 | 360 | BinaryTag sourceNBT = source.getNBT(context); 361 | if (sourceNBT == null) return input; 362 | 363 | NBTReference targetNBT = NBTReference.of(input.get(DataComponents.CUSTOM_DATA, CustomData.EMPTY).nbt()); 364 | 365 | for (Operation operation : ops) { 366 | operation.execute(targetNBT, sourceNBT); 367 | } 368 | 369 | if (targetNBT.get() instanceof CompoundBinaryTag compound) { 370 | return input.with(DataComponents.CUSTOM_DATA, new CustomData(compound)); 371 | } else { 372 | return input; 373 | } 374 | } 375 | 376 | @Override 377 | public @NotNull StructCodec codec() { 378 | return CODEC; 379 | } 380 | } 381 | 382 | record CopyName(@NotNull List predicates, @NotNull RelevantTarget source) implements LootFunction { 383 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 384 | "conditions", LootPredicate.CODEC.list().optional(List.of()), CopyName::predicates, 385 | "source", RelevantTarget.CODEC, CopyName::source, 386 | CopyName::new 387 | ); 388 | 389 | @Override 390 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 391 | if (!LootPredicate.all(predicates, context)) return input; 392 | 393 | Object key = context.get(source.key()); 394 | 395 | Component customName; 396 | if (key instanceof Entity entity && entity.getCustomName() != null) { 397 | customName = entity.getCustomName(); 398 | } else if (key instanceof Block block && block.hasTag(VanillaInterface.CUSTOM_NAME)) { 399 | customName = block.getTag(VanillaInterface.CUSTOM_NAME); 400 | } else { 401 | return input; 402 | } 403 | 404 | return input.with(DataComponents.CUSTOM_NAME, customName); 405 | } 406 | 407 | @Override 408 | public @NotNull StructCodec codec() { 409 | return CODEC; 410 | } 411 | } 412 | 413 | record CopyState(@NotNull List predicates, @NotNull Block block, @NotNull List properties) implements LootFunction { 414 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 415 | "conditions", LootPredicate.CODEC.list().optional(List.of()), CopyState::predicates, 416 | "block", Codec.KEY.transform(Block::fromKey, Block::key), CopyState::block, 417 | "properties", Codec.STRING.list(), CopyState::properties, 418 | CopyState::new 419 | ); 420 | 421 | public CopyState { 422 | List props = new ArrayList<>(properties); 423 | props.removeIf(name -> !block.properties().containsKey(name)); 424 | properties = List.copyOf(props); 425 | } 426 | 427 | @Override 428 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 429 | if (!LootPredicate.all(predicates, context)) return input; 430 | 431 | Block block = context.get(LootContext.BLOCK_STATE); 432 | if (block == null) return input; 433 | 434 | ItemBlockState irritableBowelSyndrome = input.get(DataComponents.BLOCK_STATE, ItemBlockState.EMPTY); 435 | 436 | if (!block.key().equals(this.block.key())) return input; 437 | 438 | for (var prop : properties) { 439 | @Nullable String value = block.getProperty(prop); 440 | if (value == null) continue; 441 | 442 | irritableBowelSyndrome = irritableBowelSyndrome.with(prop, value); 443 | } 444 | 445 | return input.with(DataComponents.BLOCK_STATE, irritableBowelSyndrome); 446 | } 447 | 448 | @Override 449 | public @NotNull StructCodec codec() { 450 | return CODEC; 451 | } 452 | } 453 | 454 | record EnchantedCountIncrease(@NotNull List predicates, @NotNull DynamicRegistry.Key enchantment, 455 | @NotNull LootNumber count, @Nullable Integer limit) implements LootFunction { 456 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 457 | "conditions", LootPredicate.CODEC.list().optional(List.of()), EnchantedCountIncrease::predicates, 458 | "enchantment", Codec.RegistryKey(Registries::enchantment), EnchantedCountIncrease::enchantment, 459 | "count", LootNumber.CODEC, EnchantedCountIncrease::count, 460 | "limit", Codec.INT.optional(), EnchantedCountIncrease::limit, 461 | EnchantedCountIncrease::new 462 | ); 463 | 464 | @Override 465 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 466 | if (!LootPredicate.all(predicates, context)) return input; 467 | 468 | Entity attacker = context.get(LootContext.ATTACKING_ENTITY); 469 | int level = EnchantmentUtils.level(attacker, enchantment); 470 | 471 | if (level == 0) return input; 472 | 473 | int newAmount = input.amount() + level * count.getInt(context); 474 | 475 | return input.withAmount(limit != null ? Math.min(limit, newAmount) : newAmount); 476 | } 477 | 478 | @Override 479 | public @NotNull StructCodec codec() { 480 | return CODEC; 481 | } 482 | } 483 | 484 | record EnchantRandomly(@NotNull List predicates, @Nullable List> options, boolean onlyCompatible) implements LootFunction { 485 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 486 | "conditions", LootPredicate.CODEC.list().optional(List.of()), EnchantRandomly::predicates, 487 | "options", Codec.RegistryKey(Registries::enchantment).list().optional(), EnchantRandomly::options, 488 | "only_compatible", Codec.BOOLEAN.optional(true), EnchantRandomly::onlyCompatible, 489 | EnchantRandomly::new 490 | ); 491 | 492 | @Override 493 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 494 | var reg = MinecraftServer.getEnchantmentRegistry(); 495 | 496 | List> values = new ArrayList<>(); 497 | 498 | if (options == null) { 499 | reg.values().forEach(value -> values.add(reg.getKey(value))); 500 | } else { 501 | values.addAll(options); 502 | } 503 | 504 | if (onlyCompatible && !input.material().equals(Material.BOOK)) { 505 | values.removeIf(ench -> !reg.get(ench).supportedItems().contains(input.material())); 506 | } 507 | 508 | if (values.isEmpty()) return input; 509 | 510 | Random rng = context.require(LootContext.RANDOM); 511 | 512 | DynamicRegistry.Key chosen = values.get(rng.nextInt(values.size())); 513 | 514 | int level = rng.nextInt(reg.get(chosen).maxLevel() + 1); 515 | 516 | return EnchantmentUtils.modifyItem(input, map -> map.put(chosen, level)); 517 | } 518 | 519 | @Override 520 | public @NotNull StructCodec codec() { 521 | return CODEC; 522 | } 523 | } 524 | 525 | record EnchantWithLevels(@NotNull List predicates, @NotNull LootNumber levels, @Nullable List> options) implements LootFunction { 526 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 527 | "conditions", LootPredicate.CODEC.list().optional(List.of()), EnchantWithLevels::predicates, 528 | "levels", LootNumber.CODEC, EnchantWithLevels::levels, 529 | "options", Template.keyOrTag(Registries::enchantment, Tag.BasicType.ENCHANTMENTS).optional(), EnchantWithLevels::options, 530 | EnchantWithLevels::new 531 | ); 532 | 533 | @Override 534 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 535 | if (!LootPredicate.all(predicates, context)) return input; 536 | 537 | return context.vanilla().enchant(context.require(LootContext.RANDOM), input, levels.getInt(context), options); 538 | } 539 | 540 | @Override 541 | public @NotNull StructCodec codec() { 542 | return CODEC; 543 | } 544 | } 545 | 546 | record ExplorationMap(@NotNull List predicates) implements LootFunction { 547 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 548 | "conditions", LootPredicate.CODEC.list().optional(List.of()), ExplorationMap::predicates, 549 | ExplorationMap::new 550 | ); 551 | 552 | @Override 553 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 554 | if (!LootPredicate.all(predicates, context)) return input; 555 | 556 | // TODO: Incomplete 557 | throw new UnsupportedOperationException("TODO: Implement ExplorationMap functionality and serialization"); 558 | } 559 | 560 | @Override 561 | public @NotNull StructCodec codec() { 562 | return CODEC; 563 | } 564 | } 565 | 566 | record ExplosionDecay(@NotNull List predicates) implements LootFunction { 567 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 568 | "conditions", LootPredicate.CODEC.list().optional(List.of()), ExplosionDecay::predicates, 569 | ExplosionDecay::new 570 | ); 571 | 572 | @Override 573 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 574 | if (!LootPredicate.all(predicates, context)) return input; 575 | 576 | Float radius = context.get(LootContext.EXPLOSION_RADIUS); 577 | if (radius == null) return input; 578 | 579 | Random random = context.require(LootContext.RANDOM); 580 | 581 | float chance = 1 / radius; 582 | int trials = input.amount(); 583 | 584 | int newAmount = 0; 585 | 586 | for (int i = 0; i < trials; i++) { 587 | if (random.nextFloat() <= chance) { 588 | newAmount++; 589 | } 590 | } 591 | 592 | return input.withAmount(newAmount); 593 | } 594 | 595 | @Override 596 | public @NotNull StructCodec codec() { 597 | return CODEC; 598 | } 599 | } 600 | 601 | record FillPlayerHead(@NotNull List predicates, @NotNull RelevantEntity entity) implements LootFunction { 602 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 603 | "conditions", LootPredicate.CODEC.list().optional(List.of()), FillPlayerHead::predicates, 604 | "entity", RelevantEntity.CODEC, FillPlayerHead::entity, 605 | FillPlayerHead::new 606 | ); 607 | 608 | @Override 609 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 610 | if (!LootPredicate.all(predicates, context)) return input; 611 | 612 | if (!input.material().equals(Material.PLAYER_HEAD)) return input; 613 | 614 | if (!(context.get(entity.key()) instanceof Player player)) return input; 615 | 616 | PlayerSkin skin = player.getSkin(); 617 | if (skin == null) return input; 618 | 619 | return input.with(DataComponents.PROFILE, new HeadProfile(skin)); 620 | } 621 | 622 | @Override 623 | public @NotNull StructCodec codec() { 624 | return CODEC; 625 | } 626 | } 627 | 628 | record Filtered(@NotNull List predicates, @NotNull ItemPredicate predicate, @NotNull LootFunction modifier) implements LootFunction { 629 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 630 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Filtered::predicates, 631 | "item_filter", ItemPredicate.CODEC, Filtered::predicate, 632 | "modifier", LootFunction.CODEC, Filtered::modifier, 633 | Filtered::new 634 | ); 635 | 636 | @Override 637 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 638 | return LootPredicate.all(predicates, context) && predicate.test(input) ? 639 | modifier.apply(input, context) : input; 640 | } 641 | 642 | @Override 643 | public @NotNull StructCodec codec() { 644 | return CODEC; 645 | } 646 | } 647 | 648 | record FurnaceSmelt(@NotNull List predicates) implements LootFunction { 649 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 650 | "conditions", LootPredicate.CODEC.list().optional(List.of()), FurnaceSmelt::predicates, 651 | FurnaceSmelt::new 652 | ); 653 | 654 | @Override 655 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 656 | if (!LootPredicate.all(predicates, context)) return input; 657 | 658 | ItemStack smelted = context.vanilla().smelt(input); 659 | 660 | return smelted != null ? smelted.withAmount(input.amount()) : input; 661 | } 662 | 663 | @Override 664 | public @NotNull StructCodec codec() { 665 | return CODEC; 666 | } 667 | } 668 | 669 | record LimitCount(@NotNull List predicates, @NotNull LootNumberRange limit) implements LootFunction { 670 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 671 | "conditions", LootPredicate.CODEC.list().optional(List.of()), LimitCount::predicates, 672 | "limit", LootNumberRange.CODEC, LimitCount::limit, 673 | LimitCount::new 674 | ); 675 | 676 | @Override 677 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 678 | if (!LootPredicate.all(predicates, context)) return input; 679 | return input.withAmount(i -> (int) limit.limit(context, i)); 680 | } 681 | 682 | @Override 683 | public @NotNull StructCodec codec() { 684 | return CODEC; 685 | } 686 | } 687 | 688 | record ModifyContents(@NotNull List predicates, @NotNull List modifier, 689 | @NotNull DataComponent> component) implements LootFunction { 690 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 691 | "conditions", LootPredicate.CODEC.list().optional(List.of()), ModifyContents::predicates, 692 | "modifier", LootFunction.CODEC.list(), ModifyContents::modifier, 693 | "component", Template.CONTAINER, ModifyContents::component, 694 | ModifyContents::new 695 | ); 696 | 697 | @Override 698 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 699 | if (!LootPredicate.all(predicates, context)) return input; 700 | 701 | List items = input.get(component); 702 | if (items == null) return input; 703 | 704 | List updated = new ArrayList<>(); 705 | for (ItemStack item : items) { 706 | updated.add(LootFunction.apply(modifier, item, context)); 707 | } 708 | 709 | return input.with(component, updated); 710 | } 711 | 712 | @Override 713 | public @NotNull StructCodec codec() { 714 | return CODEC; 715 | } 716 | } 717 | 718 | record Reference(@NotNull List predicates, @NotNull Key name) implements LootFunction { 719 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 720 | "conditions", LootPredicate.CODEC.list().optional(List.of()), Reference::predicates, 721 | "name", Codec.KEY, Reference::name, 722 | Reference::new 723 | ); 724 | 725 | @Override 726 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 727 | if (!LootPredicate.all(predicates, context)) return input; 728 | 729 | LootFunction function = context.vanilla().functionRegistry(name); 730 | 731 | return function != null ? function.apply(input, context) : input; 732 | } 733 | 734 | @Override 735 | public @NotNull StructCodec codec() { 736 | return CODEC; 737 | } 738 | } 739 | 740 | record SetAttributes(@NotNull List predicates, @NotNull List modifiers, boolean replace) implements LootFunction { 741 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 742 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetAttributes::predicates, 743 | "modifiers", AttributeDirective.CODEC.list(), SetAttributes::modifiers, 744 | "replace", Codec.BOOLEAN.optional(true), SetAttributes::replace, 745 | SetAttributes::new 746 | ); 747 | 748 | public record AttributeDirective(@NotNull Key id, @NotNull Attribute attribute, @NotNull AttributeOperation operation, 749 | @NotNull LootNumber amount, @NotNull List slots) { 750 | 751 | public static final @NotNull Codec CUSTOM_SLOT = Template.constant( 752 | slot -> slot.name().toLowerCase(Locale.ROOT).replace("_", ""), EquipmentSlot.values() 753 | ); 754 | 755 | public static final @NotNull Codec CODEC = StructCodec.struct( 756 | "id", Codec.KEY, AttributeDirective::id, 757 | "attribute", Attribute.CODEC, AttributeDirective::attribute, 758 | "operation", AttributeOperation.CODEC, AttributeDirective::operation, 759 | "amount", LootNumber.CODEC, AttributeDirective::amount, 760 | "slot", CUSTOM_SLOT.listOrSingle(Integer.MAX_VALUE), AttributeDirective::slots, 761 | AttributeDirective::new 762 | ); 763 | 764 | } 765 | 766 | @Override 767 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 768 | if (!LootPredicate.all(predicates, context)) return input; 769 | 770 | var component = input.get(DataComponents.ATTRIBUTE_MODIFIERS, AttributeList.EMPTY); 771 | 772 | List list = replace ? new ArrayList<>() : new ArrayList<>(component.modifiers()); 773 | 774 | for (var modifier : modifiers) { 775 | if (modifier.slots().isEmpty()) continue; 776 | 777 | AttributeModifier mod = new AttributeModifier( 778 | modifier.id(), 779 | modifier.amount().getDouble(context), 780 | modifier.operation() 781 | ); 782 | 783 | EquipmentSlot slot = modifier.slots().get(context.require(LootContext.RANDOM).nextInt(modifier.slots().size())); 784 | 785 | EquipmentSlotGroup group = switch (slot) { 786 | case MAIN_HAND -> EquipmentSlotGroup.MAIN_HAND; 787 | case OFF_HAND -> EquipmentSlotGroup.OFF_HAND; 788 | case BOOTS -> EquipmentSlotGroup.FEET; 789 | case LEGGINGS -> EquipmentSlotGroup.LEGS; 790 | case CHESTPLATE -> EquipmentSlotGroup.CHEST; 791 | case HELMET -> EquipmentSlotGroup.HEAD; 792 | case BODY -> EquipmentSlotGroup.BODY; 793 | case SADDLE -> EquipmentSlotGroup.SADDLE; 794 | }; 795 | 796 | list.add(new AttributeList.Modifier(modifier.attribute(), mod, group)); 797 | } 798 | 799 | return input.with(DataComponents.ATTRIBUTE_MODIFIERS, new AttributeList(list)); 800 | } 801 | 802 | @Override 803 | public @NotNull StructCodec codec() { 804 | return CODEC; 805 | } 806 | } 807 | 808 | record SetBannerPattern(@NotNull List predicates, @NotNull BannerPatterns patterns, boolean append) implements LootFunction { 809 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 810 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetBannerPattern::predicates, 811 | "patterns", BannerPatterns.CODEC, SetBannerPattern::patterns, 812 | "append", Codec.BOOLEAN, SetBannerPattern::append, 813 | SetBannerPattern::new 814 | ); 815 | 816 | @Override 817 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 818 | if (!LootPredicate.all(predicates, context)) return input; 819 | 820 | if (append) { 821 | BannerPatterns patterns = input.get(DataComponents.BANNER_PATTERNS); 822 | if (patterns != null) { 823 | List layers = new ArrayList<>(patterns.layers()); 824 | layers.addAll(this.patterns().layers()); 825 | return input.with(DataComponents.BANNER_PATTERNS, new BannerPatterns(layers)); 826 | } 827 | } 828 | 829 | return input.with(DataComponents.BANNER_PATTERNS, patterns); 830 | } 831 | 832 | @Override 833 | public @NotNull StructCodec codec() { 834 | return CODEC; 835 | } 836 | } 837 | 838 | record SetBookCover(@NotNull List predicates, @Nullable FilteredText title, 839 | @Nullable String author, @Nullable Integer generation) implements LootFunction { 840 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 841 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetBookCover::predicates, 842 | "title", FilteredText.STRING_CODEC.optional(), SetBookCover::title, 843 | "author", Codec.STRING.optional(), SetBookCover::author, 844 | "generation", Codec.INT.optional(), SetBookCover::generation, 845 | SetBookCover::new 846 | ); 847 | 848 | @Override 849 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 850 | if (!LootPredicate.all(predicates, context)) return input; 851 | 852 | WrittenBookContent content = input.get(DataComponents.WRITTEN_BOOK_CONTENT, WrittenBookContent.EMPTY); 853 | 854 | WrittenBookContent updated = new WrittenBookContent( 855 | title != null ? title : content.title(), 856 | author != null ? author : content.author(), 857 | generation != null ? generation : content.generation(), 858 | content.pages(), 859 | content.resolved() 860 | ); 861 | 862 | return input.with(DataComponents.WRITTEN_BOOK_CONTENT, updated); 863 | } 864 | 865 | @Override 866 | public @NotNull StructCodec codec() { 867 | return CODEC; 868 | } 869 | } 870 | 871 | record SetComponents(@NotNull List predicates, @NotNull DataComponentMap changes) implements LootFunction { 872 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 873 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetComponents::predicates, 874 | "components", DataComponent.PATCH_CODEC, SetComponents::changes, 875 | SetComponents::new 876 | ); 877 | 878 | @Override 879 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 880 | if (!LootPredicate.all(predicates, context)) return input; 881 | 882 | ItemStack.Builder builder = input.builder(); 883 | 884 | // This and .constantGeneric are hacks for until there exists a way to apply a patch to an item 885 | for (DataComponent.Value entry : changes.entrySet()) { 886 | constantGeneric(builder, entry.component(), entry.value()); 887 | } 888 | 889 | return builder.build(); 890 | } 891 | 892 | @SuppressWarnings("unchecked") 893 | private static void constantGeneric(@NotNull ItemStack.Builder builder, @NotNull DataComponent key, Object value) { 894 | builder.set(key, (T) value); 895 | } 896 | 897 | @Override 898 | public @NotNull StructCodec codec() { 899 | return CODEC; 900 | } 901 | } 902 | 903 | record SetContents(@NotNull List predicates, @NotNull List entries, 904 | @NotNull DataComponent> type) implements LootFunction { 905 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 906 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetContents::predicates, 907 | "modifier", LootEntry.CODEC.list(), SetContents::entries, 908 | "type", Template.CONTAINER, SetContents::type, 909 | SetContents::new 910 | ); 911 | 912 | @Override 913 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 914 | if (!LootPredicate.all(predicates, context)) return input; 915 | 916 | List contents = new ArrayList<>(); 917 | 918 | for (LootEntry entry : entries) { 919 | for (LootEntry.Choice choice : entry.requestChoices(context)) { 920 | contents.addAll(choice.generate(context)); 921 | } 922 | } 923 | 924 | return input.with(type, contents); 925 | } 926 | 927 | @Override 928 | public @NotNull StructCodec codec() { 929 | return CODEC; 930 | } 931 | } 932 | 933 | record SetCount(@NotNull List predicates, @NotNull LootNumber count, boolean add) implements LootFunction { 934 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 935 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetCount::predicates, 936 | "count", LootNumber.CODEC, SetCount::count, 937 | "add", Codec.BOOLEAN.optional(false), SetCount::add, 938 | SetCount::new 939 | ); 940 | 941 | @Override 942 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 943 | if (!LootPredicate.all(predicates, context)) return input; 944 | return input.withAmount(amount -> (this.add ? amount : 0) + this.count.getInt(context)); 945 | } 946 | 947 | @Override 948 | public @NotNull StructCodec codec() { 949 | return CODEC; 950 | } 951 | } 952 | 953 | record SetCustomData(@NotNull List predicates, @NotNull CompoundBinaryTag tag) implements LootFunction { 954 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 955 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetCustomData::predicates, 956 | "tag", Codec.STRING.transform(s -> { 957 | try { 958 | return TagStringIO.get().asCompound(s); 959 | } catch (IOException e) { 960 | throw new RuntimeException(e); 961 | } 962 | }, TagStringIOExt::writeTag), SetCustomData::tag, 963 | SetCustomData::new 964 | ); 965 | 966 | @Override 967 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 968 | if (!LootPredicate.all(predicates, context)) return input; 969 | 970 | return input.with(DataComponents.CUSTOM_DATA, new CustomData(tag)); 971 | } 972 | 973 | @Override 974 | public @NotNull StructCodec codec() { 975 | return CODEC; 976 | } 977 | } 978 | 979 | record SetCustomModelData(@NotNull List predicates, @NotNull LootNumber value) implements LootFunction { 980 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 981 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetCustomModelData::predicates, 982 | "value", LootNumber.CODEC, SetCustomModelData::value, 983 | SetCustomModelData::new 984 | ); 985 | 986 | @Override 987 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 988 | if (!LootPredicate.all(predicates, context)) return input; 989 | 990 | return input; 991 | // TODO: Incomplete 992 | // return input.with(ItemComponent.CUSTOM_MODEL_DATA, new CustomModelData(value.getInt(context)); 993 | } 994 | 995 | @Override 996 | public @NotNull StructCodec codec() { 997 | return CODEC; 998 | } 999 | } 1000 | 1001 | record SetDamage(@NotNull List predicates, @NotNull LootNumber damage, boolean add) implements LootFunction { 1002 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1003 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetDamage::predicates, 1004 | "damage", LootNumber.CODEC, SetDamage::damage, 1005 | "add", Codec.BOOLEAN.optional(false), SetDamage::add, 1006 | SetDamage::new 1007 | ); 1008 | 1009 | @Override 1010 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1011 | if (!LootPredicate.all(predicates, context)) return input; 1012 | 1013 | int maxDamage = input.get(DataComponents.MAX_DAMAGE, -1); 1014 | if (maxDamage == -1) return input; 1015 | 1016 | double damage = input.get(DataComponents.DAMAGE, 0) / (double) maxDamage; 1017 | 1018 | double currentDura = add ? 1 - damage : 0; 1019 | double newDura = Math.max(0, Math.min(1, currentDura + this.damage.getDouble(context))); 1020 | 1021 | double newDamage = 1 - newDura; 1022 | 1023 | return input.with(DataComponents.DAMAGE, (int) Math.floor(newDamage * maxDamage)); 1024 | } 1025 | 1026 | @Override 1027 | public @NotNull StructCodec codec() { 1028 | return CODEC; 1029 | } 1030 | } 1031 | 1032 | record SetEnchantments(@NotNull List predicates, @NotNull Map, LootNumber> enchantments, boolean add) implements LootFunction { 1033 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1034 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetEnchantments::predicates, 1035 | "enchantments", Codec.RegistryKey(Registries::enchantment).mapValue(LootNumber.CODEC), SetEnchantments::enchantments, 1036 | "add", Codec.BOOLEAN.optional(false), SetEnchantments::add, 1037 | SetEnchantments::new 1038 | ); 1039 | 1040 | @Override 1041 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1042 | if (!LootPredicate.all(predicates, context)) return input; 1043 | 1044 | return EnchantmentUtils.modifyItem(input, map -> { 1045 | this.enchantments.forEach((enchantment, number) -> { 1046 | int count = number.getInt(context); 1047 | if (add) { 1048 | count += map.getOrDefault(enchantment, 0); 1049 | } 1050 | map.put(enchantment, count); 1051 | }); 1052 | }); 1053 | } 1054 | 1055 | @Override 1056 | public @NotNull StructCodec codec() { 1057 | return CODEC; 1058 | } 1059 | } 1060 | 1061 | record SetFireworkExplosion(@NotNull List predicates, @Nullable FireworkExplosion.Shape shape, 1062 | @Nullable List colors, @Nullable List fadeColors, 1063 | @Nullable Boolean trail, @Nullable Boolean twinkle) implements LootFunction { 1064 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1065 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetFireworkExplosion::predicates, 1066 | "shape", Codec.Enum(FireworkExplosion.Shape.class).optional(), SetFireworkExplosion::shape, 1067 | "colors", Color.CODEC.list().optional(), SetFireworkExplosion::colors, 1068 | "fade_colors", Color.CODEC.list().optional(), SetFireworkExplosion::fadeColors, 1069 | "has_trail", Codec.BOOLEAN.optional(), SetFireworkExplosion::trail, 1070 | "has_twinkle", Codec.BOOLEAN.optional(), SetFireworkExplosion::twinkle, 1071 | SetFireworkExplosion::new 1072 | ); 1073 | 1074 | private static final @NotNull FireworkExplosion DEFAULT = new FireworkExplosion(FireworkExplosion.Shape.SMALL_BALL, List.of(), List.of(), false, false); 1075 | 1076 | @Override 1077 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1078 | if (!LootPredicate.all(predicates, context)) return input; 1079 | 1080 | FireworkExplosion firework = input.get(DataComponents.FIREWORK_EXPLOSION, DEFAULT); 1081 | 1082 | FireworkExplosion updated = new FireworkExplosion( 1083 | this.shape != null ? this.shape : firework.shape(), 1084 | this.colors != null ? this.colors : firework.colors(), 1085 | this.fadeColors != null ? this.fadeColors : firework.fadeColors(), 1086 | this.trail != null ? this.trail : firework.hasTrail(), 1087 | this.twinkle != null ? this.twinkle : firework.hasTwinkle() 1088 | ); 1089 | 1090 | return input.with(DataComponents.FIREWORK_EXPLOSION, updated); 1091 | } 1092 | 1093 | @Override 1094 | public @NotNull StructCodec codec() { 1095 | return CODEC; 1096 | } 1097 | } 1098 | 1099 | record SetFireworks(@NotNull List predicates, @Nullable Integer flightDuration, @NotNull ListOperation.WithValues explosions) implements LootFunction { 1100 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1101 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetFireworks::predicates, 1102 | "flight_duration", Codec.INT.optional(), SetFireworks::flightDuration, 1103 | "explosions", ListOperation.WithValues.codec(FireworkExplosion.CODEC), SetFireworks::explosions, 1104 | SetFireworks::new 1105 | ); 1106 | 1107 | @Override 1108 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1109 | if (!LootPredicate.all(predicates, context)) return input; 1110 | 1111 | FireworkList list = input.get(DataComponents.FIREWORKS, FireworkList.EMPTY); 1112 | 1113 | FireworkList updated = new FireworkList( 1114 | this.flightDuration != null ? this.flightDuration.byteValue() : list.flightDuration(), 1115 | explosions.operation().apply(this.explosions.values(), list.explosions()) 1116 | ); 1117 | 1118 | return input.with(DataComponents.FIREWORKS, updated); 1119 | } 1120 | 1121 | @Override 1122 | public @NotNull StructCodec codec() { 1123 | return CODEC; 1124 | } 1125 | } 1126 | 1127 | record SetInstrument(@NotNull List predicates) implements LootFunction { 1128 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1129 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetInstrument::predicates, 1130 | SetInstrument::new 1131 | ); 1132 | 1133 | @Override 1134 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1135 | if (!LootPredicate.all(predicates, context)) return input; 1136 | 1137 | // TODO: Incomplete 1138 | throw new UnsupportedOperationException("TODO: Implement SetInstrument functionality and serialization"); 1139 | } 1140 | 1141 | @Override 1142 | public @NotNull StructCodec codec() { 1143 | return CODEC; 1144 | } 1145 | } 1146 | 1147 | record SetItem(@NotNull List predicates, @NotNull Material item) implements LootFunction { 1148 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1149 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetItem::predicates, 1150 | "item", Material.CODEC, SetItem::item, 1151 | SetItem::new 1152 | ); 1153 | 1154 | @Override 1155 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1156 | if (!LootPredicate.all(predicates, context)) return input; 1157 | 1158 | return input.builder().material(item).build(); 1159 | } 1160 | 1161 | @Override 1162 | public @NotNull StructCodec codec() { 1163 | return CODEC; 1164 | } 1165 | } 1166 | 1167 | record SetLootTable(@NotNull List predicates, @NotNull Key name, long seed) implements LootFunction { 1168 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1169 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetLootTable::predicates, 1170 | "name", Codec.KEY, SetLootTable::name, 1171 | "seed", Codec.LONG.optional(0L), SetLootTable::seed, 1172 | SetLootTable::new 1173 | ); 1174 | 1175 | @Override 1176 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1177 | if (!LootPredicate.all(predicates, context)) return input; 1178 | if (input.isAir()) return input; 1179 | 1180 | return input.with(DataComponents.CONTAINER_LOOT, new SeededContainerLoot(name.asString(), seed)); 1181 | } 1182 | 1183 | @Override 1184 | public @NotNull StructCodec codec() { 1185 | return CODEC; 1186 | } 1187 | } 1188 | 1189 | record SetLore(@NotNull List predicates, @NotNull List lore, 1190 | @NotNull ListOperation operation, @Nullable RelevantEntity entity) implements LootFunction { 1191 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1192 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetLore::predicates, 1193 | "lore", Codec.COMPONENT.list(), SetLore::lore, 1194 | StructCodec.INLINE, ListOperation.CODEC, SetLore::operation, 1195 | "entity", RelevantEntity.CODEC.optional(), SetLore::entity, 1196 | SetLore::new 1197 | ); 1198 | 1199 | @Override 1200 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1201 | if (!LootPredicate.all(predicates, context)) return input; 1202 | 1203 | List components = input.get(DataComponents.LORE, List.of()); 1204 | 1205 | // TODO: Incomplete 1206 | // TODO: https://minecraft.wiki/w/Raw_JSON_text_format#Component_resolution 1207 | // This is not used in vanilla so it's fine for now. 1208 | 1209 | return input.with(DataComponents.LORE, operation.apply(lore, components)); 1210 | } 1211 | 1212 | @Override 1213 | public @NotNull StructCodec codec() { 1214 | return CODEC; 1215 | } 1216 | } 1217 | 1218 | record SetName(@NotNull List predicates, @Nullable Component name, 1219 | @Nullable RelevantEntity entity, @NotNull Target target) implements LootFunction { 1220 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1221 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetName::predicates, 1222 | "name", Codec.COMPONENT.optional(), SetName::name, 1223 | "entity", RelevantEntity.CODEC.optional(), SetName::entity, 1224 | "target", Target.CODEC.optional(Target.CUSTOM_NAME), SetName::target, 1225 | SetName::new 1226 | ); 1227 | 1228 | public enum Target { 1229 | ITEM_NAME("item_name", DataComponents.ITEM_NAME), 1230 | CUSTOM_NAME("custom_name", DataComponents.CUSTOM_NAME); 1231 | 1232 | public static final @NotNull Codec CODEC = Codec.Enum(Target.class); // Relies on the enum names themselves being accurate 1233 | 1234 | private final String id; 1235 | private final DataComponent component; 1236 | 1237 | Target(String id, DataComponent component) { 1238 | this.id = id; 1239 | this.component = component; 1240 | } 1241 | 1242 | public String id() { 1243 | return id; 1244 | } 1245 | 1246 | public DataComponent component() { 1247 | return component; 1248 | } 1249 | } 1250 | 1251 | @Override 1252 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1253 | if (!LootPredicate.all(predicates, context)) return input; 1254 | 1255 | if (name == null) return input; 1256 | 1257 | Component component = this.name; 1258 | // TODO: Incomplete 1259 | // TODO: https://minecraft.wiki/w/Raw_JSON_text_format#Component_resolution 1260 | // This is not used in vanilla so it's fine for now. 1261 | 1262 | return input.with(target.component(), component); 1263 | } 1264 | 1265 | @Override 1266 | public @NotNull StructCodec codec() { 1267 | return CODEC; 1268 | } 1269 | } 1270 | 1271 | record SetOminousBottleAmplifier(@NotNull List predicates, @NotNull LootNumber amplifier) implements LootFunction { 1272 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1273 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetOminousBottleAmplifier::predicates, 1274 | "amplifier", LootNumber.CODEC, SetOminousBottleAmplifier::amplifier, 1275 | SetOminousBottleAmplifier::new 1276 | ); 1277 | 1278 | @Override 1279 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1280 | if (!LootPredicate.all(predicates, context)) return input; 1281 | 1282 | int amplifier = Math.max(0, Math.min(this.amplifier.getInt(context), 4)); 1283 | 1284 | return input.with(DataComponents.OMINOUS_BOTTLE_AMPLIFIER, amplifier); 1285 | } 1286 | 1287 | @Override 1288 | public @NotNull StructCodec codec() { 1289 | return CODEC; 1290 | } 1291 | } 1292 | 1293 | record SetPotion(@NotNull List predicates, @NotNull Key id) implements LootFunction { 1294 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1295 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetPotion::predicates, 1296 | "id", Codec.KEY, SetPotion::id, 1297 | SetPotion::new 1298 | ); 1299 | 1300 | @Override 1301 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1302 | if (!LootPredicate.all(predicates, context)) return input; 1303 | 1304 | if (id.asString().equals("minecraft:empty")) { 1305 | return input.without(DataComponents.POTION_CONTENTS); 1306 | } 1307 | 1308 | PotionContents existing = input.get(DataComponents.POTION_CONTENTS, PotionContents.EMPTY); 1309 | PotionContents updated = new PotionContents(PotionType.fromKey(id), existing.customColor(), existing.customEffects()); 1310 | 1311 | return input.with(DataComponents.POTION_CONTENTS, updated); 1312 | } 1313 | 1314 | @Override 1315 | public @NotNull StructCodec codec() { 1316 | return CODEC; 1317 | } 1318 | } 1319 | 1320 | record SetStewEffect(@NotNull List predicates, @NotNull List effects) implements LootFunction { 1321 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1322 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetStewEffect::predicates, 1323 | "effects", AddedEffect.CODEC.list(), SetStewEffect::effects, 1324 | SetStewEffect::new 1325 | ); 1326 | 1327 | public record AddedEffect(@NotNull PotionEffect effect, @NotNull LootNumber duration) { 1328 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1329 | "type", PotionEffect.CODEC, AddedEffect::effect, 1330 | "duration", LootNumber.CODEC, AddedEffect::duration, 1331 | AddedEffect::new 1332 | ); 1333 | } 1334 | 1335 | @Override 1336 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1337 | if (!LootPredicate.all(predicates, context)) return input; 1338 | 1339 | if (!Material.SUSPICIOUS_STEW.equals(input.material()) || effects.isEmpty()) return input; 1340 | 1341 | AddedEffect effect = effects.get(context.require(LootContext.RANDOM).nextInt(effects.size())); 1342 | 1343 | long duration = effect.duration().getInt(context); 1344 | if (!effect.effect().registry().isInstantaneous()) { 1345 | duration *= ServerFlag.SERVER_TICKS_PER_SECOND; 1346 | } 1347 | 1348 | SuspiciousStewEffects.Effect added = new SuspiciousStewEffects.Effect(effect.effect(), (int) duration); 1349 | 1350 | SuspiciousStewEffects current = input.get(DataComponents.SUSPICIOUS_STEW_EFFECTS, SuspiciousStewEffects.EMPTY); 1351 | return input.with(DataComponents.SUSPICIOUS_STEW_EFFECTS, current.with(added)); 1352 | } 1353 | 1354 | @Override 1355 | public @NotNull StructCodec codec() { 1356 | return CODEC; 1357 | } 1358 | } 1359 | 1360 | record SetWritableBookPages(@NotNull List predicates, @NotNull List> pages, @NotNull ListOperation operation) implements LootFunction { 1361 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1362 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetWritableBookPages::predicates, 1363 | "pages", FilteredText.STRING_CODEC.list(), SetWritableBookPages::pages, 1364 | StructCodec.INLINE, ListOperation.CODEC, SetWritableBookPages::operation, 1365 | SetWritableBookPages::new 1366 | ); 1367 | 1368 | @Override 1369 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1370 | if (!LootPredicate.all(predicates, context)) return input; 1371 | 1372 | WritableBookContent content = input.get(DataComponents.WRITABLE_BOOK_CONTENT, WritableBookContent.EMPTY); 1373 | 1374 | return input.with(DataComponents.WRITABLE_BOOK_CONTENT, new WritableBookContent(operation.apply(pages, content.pages()))); 1375 | } 1376 | 1377 | @Override 1378 | public @NotNull StructCodec codec() { 1379 | return CODEC; 1380 | } 1381 | } 1382 | 1383 | record SetWrittenBookPages(@NotNull List predicates, @NotNull List> pages, @NotNull ListOperation operation) implements LootFunction { 1384 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1385 | "conditions", LootPredicate.CODEC.list().optional(List.of()), SetWrittenBookPages::predicates, 1386 | "pages", FilteredText.COMPONENT_CODEC.list(), SetWrittenBookPages::pages, 1387 | StructCodec.INLINE, ListOperation.CODEC, SetWrittenBookPages::operation, 1388 | SetWrittenBookPages::new 1389 | ); 1390 | 1391 | @Override 1392 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1393 | if (!LootPredicate.all(predicates, context)) return input; 1394 | 1395 | WrittenBookContent content = input.get(DataComponents.WRITTEN_BOOK_CONTENT, WrittenBookContent.EMPTY); 1396 | WrittenBookContent updated = new WrittenBookContent(content.title(), content.author(), content.generation(), operation.apply(pages, content.pages()), content.resolved()); 1397 | 1398 | return input.with(DataComponents.WRITTEN_BOOK_CONTENT, updated); 1399 | } 1400 | 1401 | @Override 1402 | public @NotNull StructCodec codec() { 1403 | return CODEC; 1404 | } 1405 | } 1406 | 1407 | record Sequence(@NotNull List functions) implements LootFunction { 1408 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1409 | "functions", LootFunction.CODEC.list(), Sequence::functions, 1410 | Sequence::new 1411 | ); 1412 | 1413 | @Override 1414 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1415 | return LootFunction.apply(functions, input, context); 1416 | } 1417 | 1418 | @Override 1419 | public @NotNull StructCodec codec() { 1420 | return CODEC; 1421 | } 1422 | } 1423 | 1424 | record ToggleTooltips(@NotNull List predicates, @NotNull Map, Boolean> toggles) implements LootFunction { 1425 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 1426 | "conditions", LootPredicate.CODEC.list().optional(List.of()), ToggleTooltips::predicates, 1427 | "toggles", DataComponent.CODEC.mapValue(StructCodec.BOOLEAN), ToggleTooltips::toggles, 1428 | ToggleTooltips::new 1429 | ); 1430 | 1431 | @Override 1432 | public @NotNull ItemStack apply(@NotNull ItemStack input, @NotNull LootContext context) { 1433 | if (!LootPredicate.all(predicates, context)) return input; 1434 | 1435 | TooltipDisplay display = input.get(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.EMPTY); 1436 | 1437 | for (var entry : toggles.entrySet()) { 1438 | display = entry.getValue() ? display.with(entry.getKey()) : display.without(entry.getKey()); 1439 | } 1440 | 1441 | return input.with(DataComponents.TOOLTIP_DISPLAY, display); 1442 | } 1443 | 1444 | @Override 1445 | public @NotNull StructCodec codec() { 1446 | return CODEC; 1447 | } 1448 | } 1449 | 1450 | } 1451 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootGenerator.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.minestom.server.coordinate.Point; 4 | import net.minestom.server.instance.Instance; 5 | import net.minestom.server.item.ItemStack; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Something that can generate loot. 12 | */ 13 | public interface LootGenerator { 14 | 15 | @NotNull List generate(@NotNull LootContext context); 16 | 17 | default void blockDrop(@NotNull LootContext context, @NotNull Instance instance, @NotNull Point block) { 18 | for (ItemStack item : generate(context)) { 19 | Trove.blockDrop(instance, item, block); 20 | } 21 | } 22 | 23 | default void drop(@NotNull LootContext context, @NotNull Instance instance, @NotNull Point pos) { 24 | for (ItemStack item : generate(context)) { 25 | Trove.drop(instance, item, pos); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootNBT.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.RelevantEntity; 4 | import net.kyori.adventure.key.Key; 5 | import net.kyori.adventure.nbt.BinaryTag; 6 | import net.kyori.adventure.nbt.CompoundBinaryTag; 7 | import net.kyori.adventure.nbt.IntBinaryTag; 8 | import net.kyori.adventure.nbt.StringBinaryTag; 9 | import net.minestom.server.codec.Codec; 10 | import net.minestom.server.codec.StructCodec; 11 | import net.minestom.server.coordinate.Point; 12 | import net.minestom.server.instance.block.Block; 13 | import net.minestom.server.registry.DynamicRegistry; 14 | import org.jetbrains.annotations.NotNull; 15 | import org.jetbrains.annotations.Nullable; 16 | 17 | import java.util.Map; 18 | 19 | /** 20 | * Returns NBT data from the provided context. 21 | */ 22 | @SuppressWarnings("UnstableApiUsage") 23 | public interface LootNBT { 24 | 25 | @NotNull Codec CODEC = Codec.RegistryTaggedUnion(registries -> { 26 | class Holder { 27 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 28 | } 29 | return Holder.CODEC; 30 | }, LootNBT::codec, "type").orElse(Codec.STRING.transform( 31 | str -> new Context(Context.Target.fromString(str)), 32 | nbt -> ((Context) nbt).target.toString() 33 | )); 34 | 35 | static @NotNull DynamicRegistry> createDefaultRegistry() { 36 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:loot_nbt"); 37 | registry.register("context", Context.CODEC); 38 | registry.register("storage", Storage.CODEC); 39 | return registry; 40 | } 41 | 42 | /** 43 | * Generates some NBT based on the provided context. 44 | * @param context the context to use for NBT 45 | * @return the NBT, or null if there is none 46 | */ 47 | @Nullable BinaryTag getNBT(@NotNull LootContext context); 48 | 49 | /** 50 | * @return the codec that can encode this function 51 | */ 52 | @NotNull StructCodec codec(); 53 | 54 | record Storage(@NotNull Key source) implements LootNBT { 55 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 56 | "source", Codec.KEY, Storage::source, 57 | Storage::new 58 | ); 59 | 60 | @Override 61 | public @Nullable BinaryTag getNBT(@NotNull LootContext context) { 62 | return context.vanilla().commandStorage(source); 63 | } 64 | 65 | @Override 66 | public @NotNull StructCodec codec() { 67 | return CODEC; 68 | } 69 | } 70 | 71 | record Context(@NotNull Target target) implements LootNBT { 72 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 73 | "target", Codec.STRING.transform(Context.Target::fromString, Context.Target::toString), Context::target, 74 | Context::new 75 | ); 76 | 77 | public sealed interface Target { 78 | @Nullable BinaryTag getNBT(@NotNull LootContext context); 79 | 80 | static @NotNull Target fromString(@NotNull String input) { 81 | if (input.equals("block_entity")) return new BlockEntity(); 82 | 83 | for (var target : RelevantEntity.values()) { 84 | if (target.id().equals(input)) return new Entity(target); 85 | } 86 | 87 | throw new IllegalArgumentException("Expected block_entity or a valid entity target name"); 88 | } 89 | 90 | record BlockEntity() implements Target { 91 | @SuppressWarnings("DataFlowIssue") 92 | @Override 93 | public @NotNull BinaryTag getNBT(@NotNull LootContext context) { 94 | Block block = context.require(LootContext.BLOCK_STATE); 95 | Point pos = context.require(LootContext.ORIGIN); 96 | 97 | CompoundBinaryTag nbt = block.hasNbt() ? block.nbt() : CompoundBinaryTag.empty(); 98 | 99 | return nbt.put(Map.of( 100 | "x", IntBinaryTag.intBinaryTag(pos.blockX()), 101 | "y", IntBinaryTag.intBinaryTag(pos.blockY()), 102 | "z", IntBinaryTag.intBinaryTag(pos.blockZ()), 103 | "id", StringBinaryTag.stringBinaryTag(block.key().asString()) 104 | )); 105 | } 106 | 107 | @Override 108 | public String toString() { 109 | return "block_entity"; 110 | } 111 | } 112 | 113 | record Entity(@NotNull RelevantEntity target) implements Target { 114 | @Override 115 | public @NotNull BinaryTag getNBT(@NotNull LootContext context) { 116 | var entity = context.require(target.key()); 117 | 118 | return context.vanilla().serializeEntity(entity); 119 | } 120 | 121 | @Override 122 | public String toString() { 123 | return target.id(); 124 | } 125 | } 126 | } 127 | 128 | @Override 129 | public @Nullable BinaryTag getNBT(@NotNull LootContext context) { 130 | return target.getNBT(context); 131 | } 132 | 133 | @Override 134 | public @NotNull StructCodec codec() { 135 | return CODEC; 136 | } 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootNumber.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.nbt.NBTPath; 4 | import net.goldenstack.loot.util.nbt.NBTReference; 5 | import net.kyori.adventure.key.Key; 6 | import net.kyori.adventure.nbt.CompoundBinaryTag; 7 | import net.kyori.adventure.nbt.IntBinaryTag; 8 | import net.kyori.adventure.nbt.NumberBinaryTag; 9 | import net.minestom.server.codec.Codec; 10 | import net.minestom.server.codec.StructCodec; 11 | import net.minestom.server.item.enchant.LevelBasedValue; 12 | import net.minestom.server.registry.DynamicRegistry; 13 | import org.jetbrains.annotations.NotNull; 14 | 15 | import java.util.List; 16 | import java.util.Random; 17 | 18 | /** 19 | * Generates numbers based on provided loot contexts. 20 | */ 21 | @SuppressWarnings("UnstableApiUsage") 22 | public interface LootNumber { 23 | 24 | @NotNull Codec CODEC = Codec.DOUBLE.transform(Constant::new, a -> ((Constant) a).value()).orElse(Codec.RegistryTaggedUnion(registries -> { 25 | class Holder { 26 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 27 | } 28 | return Holder.CODEC; 29 | }, LootNumber::codec, "type")); 30 | 31 | static @NotNull DynamicRegistry> createDefaultRegistry() { 32 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:loot_numbers"); 33 | registry.register("binomial", Binomial.CODEC); 34 | registry.register("constant", Constant.CODEC); 35 | registry.register("enchantment_level", EnchantmentLevel.CODEC); 36 | registry.register("score", Score.CODEC); 37 | registry.register("storage", Storage.CODEC); 38 | registry.register("uniform", Uniform.CODEC); 39 | return registry; 40 | } 41 | 42 | /** 43 | * Generates an integer depending on the information in the provided context.
44 | * This is an explicitly impure method—it depends on state outside the given context. 45 | * @param context the context object, to use if required 46 | * @return the integer generated by this loot number for the provided context 47 | */ 48 | int getInt(@NotNull LootContext context); 49 | 50 | /** 51 | * Generates a double depending on the information in the provided context.
52 | * This is an explicitly impure method—it depends on state outside the given context. 53 | * @param context the context object, to use if required 54 | * @return the double generated by this loot number for the provided context 55 | */ 56 | double getDouble(@NotNull LootContext context); 57 | 58 | /** 59 | * @return the codec that can encode this number 60 | */ 61 | @NotNull StructCodec codec(); 62 | 63 | record Binomial(@NotNull LootNumber trials, @NotNull LootNumber probability) implements LootNumber { 64 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 65 | "n", LootNumber.CODEC, Binomial::trials, 66 | "p", LootNumber.CODEC, Binomial::probability, 67 | Binomial::new 68 | ); 69 | 70 | @Override 71 | public int getInt(@NotNull LootContext context) { 72 | int trials = trials().getInt(context); 73 | double probability = probability().getDouble(context); 74 | Random random = context.require(LootContext.RANDOM); 75 | 76 | int successes = 0; 77 | for (int trial = 0; trial < trials; trial++) { 78 | if (random.nextDouble() < probability) { 79 | successes++; 80 | } 81 | } 82 | return successes; 83 | } 84 | 85 | @Override 86 | public double getDouble(@NotNull LootContext context) { 87 | return getInt(context); 88 | } 89 | 90 | @Override 91 | public @NotNull StructCodec codec() { 92 | return CODEC; 93 | } 94 | } 95 | 96 | record Constant(@NotNull Double value) implements LootNumber { 97 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 98 | "value", Codec.DOUBLE, Constant::value, 99 | Constant::new 100 | ); 101 | 102 | @Override 103 | public int getInt(@NotNull LootContext context) { 104 | return value.intValue(); 105 | } 106 | 107 | @Override 108 | public double getDouble(@NotNull LootContext context) { 109 | return value; 110 | } 111 | 112 | @Override 113 | public @NotNull StructCodec codec() { 114 | return CODEC; 115 | } 116 | } 117 | 118 | record EnchantmentLevel(@NotNull LevelBasedValue amount) implements LootNumber { 119 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 120 | "amount", LevelBasedValue.CODEC, EnchantmentLevel::amount, 121 | EnchantmentLevel::new 122 | ); 123 | 124 | @Override 125 | public int getInt(@NotNull LootContext context) { 126 | return (int) Math.round(getDouble(context)); 127 | } 128 | 129 | @Override 130 | public double getDouble(@NotNull LootContext context) { 131 | return amount.calc(context.require(LootContext.ENCHANTMENT_LEVEL)); 132 | } 133 | 134 | @Override 135 | public @NotNull StructCodec codec() { 136 | return CODEC; 137 | } 138 | } 139 | 140 | record Score(@NotNull LootScore target, @NotNull String objective, double scale) implements LootNumber { 141 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 142 | "target", LootScore.CODEC, Score::target, 143 | "score", Codec.STRING, Score::objective, 144 | "scale", Codec.DOUBLE, Score::scale, 145 | Score::new 146 | ); 147 | 148 | @Override 149 | public int getInt(@NotNull LootContext context) { 150 | return (int) Math.round(getDouble(context)); 151 | } 152 | 153 | @Override 154 | public double getDouble(@NotNull LootContext context) { 155 | var score = target.apply(context).apply(objective); 156 | 157 | return score != null ? score * scale : 0; 158 | } 159 | 160 | @Override 161 | public @NotNull StructCodec codec() { 162 | return CODEC; 163 | } 164 | } 165 | 166 | record Storage(@NotNull Key storage, @NotNull NBTPath path) implements LootNumber { 167 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 168 | "storage", Codec.KEY, Storage::storage, 169 | "path", NBTPath.CODEC, Storage::path, 170 | Storage::new 171 | ); 172 | 173 | @Override 174 | public int getInt(@NotNull LootContext context) { 175 | return get(context).intValue(); 176 | } 177 | 178 | @Override 179 | public double getDouble(@NotNull LootContext context) { 180 | return get(context).doubleValue(); 181 | } 182 | 183 | private NumberBinaryTag get(@NotNull LootContext context) { 184 | CompoundBinaryTag compound = context.vanilla().commandStorage(storage); 185 | 186 | List refs = path.get(compound != null ? compound : CompoundBinaryTag.empty()); 187 | if (refs.size() != 1) return IntBinaryTag.intBinaryTag(0); 188 | 189 | if (refs.getFirst().get() instanceof NumberBinaryTag number) { 190 | return number; 191 | } else { 192 | return IntBinaryTag.intBinaryTag(0); 193 | } 194 | } 195 | 196 | @Override 197 | public @NotNull StructCodec codec() { 198 | return CODEC; 199 | } 200 | } 201 | 202 | record Uniform(@NotNull LootNumber min, @NotNull LootNumber max) implements LootNumber { 203 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 204 | "min", LootNumber.CODEC, Uniform::min, 205 | "max", LootNumber.CODEC, Uniform::max, 206 | Uniform::new 207 | ); 208 | 209 | @Override 210 | public int getInt(@NotNull LootContext context) { 211 | return context.require(LootContext.RANDOM).nextInt(min().getInt(context), max().getInt(context) + 1); 212 | } 213 | 214 | @Override 215 | public double getDouble(@NotNull LootContext context) { 216 | return context.require(LootContext.RANDOM).nextDouble(min().getDouble(context), max().getDouble(context)); 217 | } 218 | 219 | @Override 220 | public @NotNull StructCodec codec() { 221 | return CODEC; 222 | } 223 | } 224 | 225 | } 226 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootPool.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.minestom.server.codec.StructCodec; 4 | import net.minestom.server.item.ItemStack; 5 | import org.jetbrains.annotations.NotNull; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * A loot pool. 13 | * @param rolls the default number of rolls to occur 14 | * @param bonusRolls the number of bonus rolls to occur. Multiplied by the context's luck. 15 | * @param entries the entries to generate loot from. 16 | * @param predicates the predicates for loot generation 17 | * @param functions the modifiers applied to each item 18 | */ 19 | public record LootPool(@NotNull LootNumber rolls, 20 | @NotNull LootNumber bonusRolls, 21 | @NotNull List entries, 22 | @NotNull List predicates, 23 | @NotNull List functions) implements LootGenerator { 24 | 25 | @SuppressWarnings("UnstableApiUsage") 26 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 27 | "rolls", LootNumber.CODEC, LootPool::rolls, 28 | "bonus_rolls", LootNumber.CODEC.optional(new LootNumber.Constant(0D)), LootPool::bonusRolls, 29 | "entries", LootEntry.CODEC.list(), LootPool::entries, 30 | "conditions", LootPredicate.CODEC.list().optional(List.of()), LootPool::predicates, 31 | "functions", LootFunction.CODEC.list().optional(List.of()), LootPool::functions, 32 | LootPool::new 33 | ); 34 | 35 | @Override 36 | public @NotNull List generate(@NotNull LootContext context) { 37 | if (!(LootPredicate.all(predicates, context))) return List.of(); 38 | 39 | int rolls = this.rolls.getInt(context); 40 | 41 | Double luck = context.get(LootContext.LUCK); 42 | if (luck != null) { 43 | rolls += (int) Math.floor(luck * this.bonusRolls.getDouble(context)); 44 | } 45 | 46 | List items = new ArrayList<>(); 47 | 48 | for (int i = 0; i < rolls; i++) { 49 | LootEntry.Choice choice = pickChoice(entries, context); 50 | if (choice == null) continue; 51 | 52 | items.addAll(choice.generate(context)); 53 | } 54 | 55 | return LootFunction.apply(functions, items, context); 56 | } 57 | 58 | /** 59 | * Picks a random choice from the choices generated by the provided entries, weighted with each choice's weight. If 60 | * no choices were generated, null is returned. 61 | * @param entries the entries to generate choices to choose from 62 | * @param context the context, to use if needed 63 | * @return the picked choice, or null if no choices were generated 64 | */ 65 | static @Nullable LootEntry.Choice pickChoice(@NotNull List entries, @NotNull LootContext context) { 66 | List choices = new ArrayList<>(); 67 | for (LootEntry entry : entries) { 68 | choices.addAll(entry.requestChoices(context)); 69 | } 70 | 71 | if (choices.isEmpty()) { 72 | return null; 73 | } 74 | 75 | long totalWeight = 0; 76 | long[] weightMilestones = new long[choices.size()]; 77 | for (int i = 0; i < choices.size(); i++) { 78 | // Prevent the weight of this choice from being less than 1 79 | totalWeight += Math.max(1, choices.get(i).getWeight(context)); 80 | 81 | weightMilestones[i] = totalWeight; 82 | } 83 | 84 | long value = context.require(LootContext.RANDOM).nextLong(0, totalWeight); 85 | 86 | LootEntry.Choice choice = choices.getLast(); 87 | 88 | for (int i = 0; i < weightMilestones.length; i++) { 89 | if (value < weightMilestones[i]) { 90 | choice = choices.get(i); 91 | break; 92 | } 93 | } 94 | 95 | return choice; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootPredicate.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.EnchantmentUtils; 4 | import net.goldenstack.loot.util.LootNumberRange; 5 | import net.goldenstack.loot.util.RelevantEntity; 6 | import net.goldenstack.loot.util.predicate.*; 7 | import net.kyori.adventure.key.Key; 8 | import net.minestom.server.codec.Codec; 9 | import net.minestom.server.codec.StructCodec; 10 | import net.minestom.server.coordinate.Point; 11 | import net.minestom.server.entity.Entity; 12 | import net.minestom.server.entity.damage.DamageType; 13 | import net.minestom.server.instance.Instance; 14 | import net.minestom.server.instance.Weather; 15 | import net.minestom.server.instance.block.Block; 16 | import net.minestom.server.instance.block.predicate.BlockPredicate; 17 | import net.minestom.server.item.ItemStack; 18 | import net.minestom.server.item.enchant.Enchantment; 19 | import net.minestom.server.item.enchant.LevelBasedValue; 20 | import net.minestom.server.registry.DynamicRegistry; 21 | import net.minestom.server.registry.Registries; 22 | import org.jetbrains.annotations.NotNull; 23 | import org.jetbrains.annotations.Nullable; 24 | 25 | import java.util.List; 26 | import java.util.Map; 27 | import java.util.function.Predicate; 28 | 29 | /** 30 | * A predicate over a loot context, returning whether or not a given context passes some arbitrary predicate. 31 | */ 32 | @SuppressWarnings("UnstableApiUsage") 33 | public interface LootPredicate extends Predicate<@NotNull LootContext> { 34 | 35 | @NotNull StructCodec CODEC = Codec.RegistryTaggedUnion(registries -> { 36 | class Holder { 37 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 38 | } 39 | return Holder.CODEC; 40 | }, LootPredicate::codec, "condition"); 41 | 42 | static @NotNull DynamicRegistry> createDefaultRegistry() { 43 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:loot_predicates"); 44 | registry.register("all_of", AllOf.CODEC); 45 | registry.register("any_of", AnyOf.CODEC); 46 | registry.register("block_state_property", BlockStateProperty.CODEC); 47 | registry.register("damage_source_properties", DamageSourceProperties.CODEC); 48 | registry.register("enchantment_active_check", EnchantmentActiveCheck.CODEC); 49 | registry.register("entity_properties", EntityProperties.CODEC); 50 | registry.register("entity_scores", EntityScores.CODEC); 51 | registry.register("inverted", Inverted.CODEC); 52 | registry.register("killed_by_player", KilledByPlayer.CODEC); 53 | registry.register("location_check", LocationCheck.CODEC); 54 | registry.register("match_tool", MatchTool.CODEC); 55 | registry.register("random_chance", RandomChance.CODEC); 56 | registry.register("random_chance_with_enchanted_bonus", RandomChanceWithEnchantedBonus.CODEC); 57 | registry.register("reference", Reference.CODEC); 58 | registry.register("survives_explosion", SurvivesExplosion.CODEC); 59 | registry.register("table_bonus", TableBonus.CODEC); 60 | registry.register("time_check", TimeCheck.CODEC); 61 | registry.register("value_check", ValueCheck.CODEC); 62 | registry.register("weather_check", WeatherCheck.CODEC); 63 | return registry; 64 | } 65 | 66 | /** 67 | * Returns whether or not the provided loot context passes this predicate. 68 | * @param context the context object, to use if required 69 | * @return true if the provided loot context is valid according to this predicate 70 | */ 71 | @Override 72 | boolean test(@NotNull LootContext context); 73 | 74 | /** 75 | * @return the codec that can encode this predicate 76 | */ 77 | @NotNull StructCodec codec(); 78 | 79 | /** 80 | * Returns whether or not every given predicate verifies the provided context. 81 | */ 82 | static boolean all(@NotNull List predicates, @NotNull LootContext context) { 83 | if (predicates.isEmpty()) { 84 | return true; 85 | } 86 | for (var predicate : predicates) { 87 | if (!predicate.test(context)) { 88 | return false; 89 | } 90 | } 91 | return true; 92 | } 93 | 94 | record AllOf(@NotNull List terms) implements LootPredicate { 95 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 96 | "terms", LootPredicate.CODEC.list(), AllOf::terms, 97 | AllOf::new 98 | ); 99 | 100 | @Override 101 | public boolean test(@NotNull LootContext context) { 102 | return all(terms, context); 103 | } 104 | 105 | @Override 106 | public @NotNull StructCodec codec() { 107 | return CODEC; 108 | } 109 | } 110 | 111 | record AnyOf(@NotNull List terms) implements LootPredicate { 112 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 113 | "terms", LootPredicate.CODEC.list(), AnyOf::terms, 114 | AnyOf::new 115 | ); 116 | 117 | @Override 118 | public boolean test(@NotNull LootContext context) { 119 | if (terms.isEmpty()) { 120 | return false; 121 | } 122 | for (var predicate : terms) { 123 | if (predicate.test(context)) { 124 | return true; 125 | } 126 | } 127 | return false; 128 | } 129 | 130 | @Override 131 | public @NotNull StructCodec codec() { 132 | return CODEC; 133 | } 134 | } 135 | 136 | record BlockStateProperty(@NotNull Key block, @Nullable BlockPredicate properties) implements LootPredicate { 137 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 138 | "block", Codec.KEY, BlockStateProperty::block, 139 | "properties", BlockPredicate.CODEC.optional(), BlockStateProperty::properties, 140 | BlockStateProperty::new 141 | ); 142 | 143 | @Override 144 | public boolean test(@NotNull LootContext context) { 145 | Block block = context.get(LootContext.BLOCK_STATE); 146 | 147 | return block != null && this.block.equals(block.key()) && (properties == null || properties.test(block)); 148 | } 149 | 150 | @Override 151 | public @NotNull StructCodec codec() { 152 | return CODEC; 153 | } 154 | } 155 | 156 | record DamageSourceProperties(@Nullable DamageSourcePredicate predicate) implements LootPredicate { 157 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 158 | "predicate", DamageSourcePredicate.CODEC.optional(), DamageSourceProperties::predicate, 159 | DamageSourceProperties::new 160 | ); 161 | 162 | @Override 163 | public boolean test(@NotNull LootContext context) { 164 | Instance world = context.get(LootContext.WORLD); 165 | Point origin = context.get(LootContext.ORIGIN); 166 | DamageType damage = context.get(LootContext.DAMAGE_SOURCE); 167 | 168 | if (predicate == null || world == null || origin == null || damage == null) { 169 | return false; 170 | } 171 | 172 | return predicate.test(world, origin, damage); 173 | } 174 | 175 | @Override 176 | public @NotNull StructCodec codec() { 177 | return CODEC; 178 | } 179 | } 180 | 181 | record EnchantmentActiveCheck(boolean active) implements LootPredicate { 182 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 183 | "active", Codec.BOOLEAN, EnchantmentActiveCheck::active, 184 | EnchantmentActiveCheck::new 185 | ); 186 | 187 | @Override 188 | public boolean test(@NotNull LootContext context) { 189 | return context.require(LootContext.ENCHANTMENT_ACTIVE) == active; 190 | } 191 | 192 | @Override 193 | public @NotNull StructCodec codec() { 194 | return CODEC; 195 | } 196 | } 197 | 198 | record EntityProperties(@Nullable EntityPredicate predicate, @NotNull RelevantEntity entity) implements LootPredicate { 199 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 200 | "predicate", EntityPredicate.CODEC, EntityProperties::predicate, 201 | "entity", RelevantEntity.CODEC, EntityProperties::entity, 202 | EntityProperties::new 203 | ); 204 | 205 | @Override 206 | public boolean test(@NotNull LootContext context) { 207 | Entity entity = context.get(this.entity.key()); 208 | Point origin = context.get(LootContext.ORIGIN); 209 | 210 | return predicate == null || predicate.test(context.require(LootContext.WORLD), origin, entity); 211 | } 212 | 213 | @Override 214 | public @NotNull StructCodec codec() { 215 | return CODEC; 216 | } 217 | } 218 | 219 | record EntityScores(@NotNull Map scores, @NotNull RelevantEntity entity) implements LootPredicate { 220 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 221 | "scores", Codec.STRING.mapValue(LootNumberRange.CODEC), EntityScores::scores, 222 | "entity", RelevantEntity.CODEC, EntityScores::entity, 223 | EntityScores::new 224 | ); 225 | 226 | @Override 227 | public boolean test(@NotNull LootContext context) { 228 | Entity entity = context.get(this.entity.key()); 229 | if (entity == null) return false; 230 | 231 | for (var entry : scores.entrySet()) { 232 | Integer score = context.vanilla().score(entity, entry.getKey()); 233 | if (score == null || !entry.getValue().check(context, score)) { 234 | return false; 235 | } 236 | } 237 | 238 | return true; 239 | } 240 | 241 | @Override 242 | public @NotNull StructCodec codec() { 243 | return CODEC; 244 | } 245 | } 246 | 247 | record Inverted(@NotNull LootPredicate term) implements LootPredicate { 248 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 249 | "term", LootPredicate.CODEC, Inverted::term, 250 | Inverted::new 251 | ); 252 | 253 | @Override 254 | public boolean test(@NotNull LootContext context) { 255 | return !term.test(context); 256 | } 257 | 258 | @Override 259 | public @NotNull StructCodec codec() { 260 | return CODEC; 261 | } 262 | } 263 | 264 | record KilledByPlayer() implements LootPredicate { 265 | public static final @NotNull StructCodec CODEC = StructCodec.struct(KilledByPlayer::new); 266 | 267 | @Override 268 | public boolean test(@NotNull LootContext context) { 269 | return context.has(LootContext.LAST_DAMAGE_PLAYER); 270 | } 271 | 272 | @Override 273 | public @NotNull StructCodec codec() { 274 | return CODEC; 275 | } 276 | } 277 | 278 | record LocationCheck(@Nullable LocationPredicate predicate, double offsetX, double offsetY, double offsetZ) implements LootPredicate { 279 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 280 | "predicate", LocationPredicate.CODEC, LocationCheck::predicate, 281 | "offsetX", Codec.DOUBLE.optional(0D), LocationCheck::offsetX, 282 | "offsetY", Codec.DOUBLE.optional(0D), LocationCheck::offsetY, 283 | "offsetZ", Codec.DOUBLE.optional(0D), LocationCheck::offsetZ, 284 | LocationCheck::new 285 | ); 286 | 287 | @Override 288 | public boolean test(@NotNull LootContext context) { 289 | Point origin = context.get(LootContext.ORIGIN); 290 | 291 | if (origin == null) return false; 292 | if (predicate == null) return true; 293 | 294 | return predicate.test(context.require(LootContext.WORLD), origin.add(offsetX, offsetY, offsetZ)); 295 | } 296 | 297 | @Override 298 | public @NotNull StructCodec codec() { 299 | return CODEC; 300 | } 301 | } 302 | 303 | record MatchTool(@Nullable ItemPredicate predicate) implements LootPredicate { 304 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 305 | "predicate", ItemPredicate.CODEC, MatchTool::predicate, 306 | MatchTool::new 307 | ); 308 | 309 | @Override 310 | public boolean test(@NotNull LootContext context) { 311 | ItemStack tool = context.get(LootContext.TOOL); 312 | 313 | if (tool == null) return false; 314 | if (predicate == null) return true; 315 | 316 | return predicate.test(tool); 317 | } 318 | 319 | @Override 320 | public @NotNull StructCodec codec() { 321 | return CODEC; 322 | } 323 | } 324 | 325 | record RandomChance(@NotNull LootNumber chance) implements LootPredicate { 326 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 327 | "chance", LootNumber.CODEC, RandomChance::chance, 328 | RandomChance::new 329 | ); 330 | 331 | @Override 332 | public boolean test(@NotNull LootContext context) { 333 | return context.require(LootContext.RANDOM).nextDouble() < chance.getDouble(context); 334 | } 335 | 336 | @Override 337 | public @NotNull StructCodec codec() { 338 | return CODEC; 339 | } 340 | } 341 | 342 | record RandomChanceWithEnchantedBonus(@NotNull DynamicRegistry.Key enchantment, float unenchantedChance, @NotNull LevelBasedValue enchantedChance) implements LootPredicate { 343 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 344 | "enchantment", Codec.RegistryKey(Registries::enchantment), RandomChanceWithEnchantedBonus::enchantment, 345 | "unenchanted_chance", Codec.FLOAT, RandomChanceWithEnchantedBonus::unenchantedChance, 346 | "enchanted_chance", LevelBasedValue.CODEC, RandomChanceWithEnchantedBonus::enchantedChance, 347 | RandomChanceWithEnchantedBonus::new 348 | ); 349 | 350 | @Override 351 | public boolean test(@NotNull LootContext context) { 352 | Entity attacker = context.get(LootContext.ATTACKING_ENTITY); 353 | 354 | int level = EnchantmentUtils.level(attacker, enchantment); 355 | 356 | float chance = level > 0 ? enchantedChance.calc(level) : unenchantedChance; 357 | return context.require(LootContext.RANDOM).nextFloat() < chance; 358 | } 359 | 360 | @Override 361 | public @NotNull StructCodec codec() { 362 | return CODEC; 363 | } 364 | } 365 | 366 | record Reference(@NotNull Key name) implements LootPredicate { 367 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 368 | "name", Codec.KEY, Reference::name, 369 | Reference::new 370 | ); 371 | 372 | @Override 373 | public boolean test(@NotNull LootContext context) { 374 | LootPredicate predicate = context.vanilla().predicateRegistry(name); 375 | 376 | return predicate != null && predicate.test(context); 377 | } 378 | 379 | @Override 380 | public @NotNull StructCodec codec() { 381 | return CODEC; 382 | } 383 | } 384 | 385 | record SurvivesExplosion() implements LootPredicate { 386 | public static final @NotNull StructCodec CODEC = StructCodec.struct(SurvivesExplosion::new); 387 | 388 | @Override 389 | public boolean test(@NotNull LootContext context) { 390 | Float radius = context.get(LootContext.EXPLOSION_RADIUS); 391 | return radius == null || context.require(LootContext.RANDOM).nextFloat() <= (1 / radius); 392 | } 393 | 394 | @Override 395 | public @NotNull StructCodec codec() { 396 | return CODEC; 397 | } 398 | } 399 | 400 | record TableBonus(@NotNull DynamicRegistry.Key enchantment, @NotNull List chances) implements LootPredicate { 401 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 402 | "enchantment", Codec.RegistryKey(Registries::enchantment), TableBonus::enchantment, 403 | "chances", Codec.FLOAT.list(), TableBonus::chances, 404 | TableBonus::new 405 | ); 406 | 407 | @Override 408 | public boolean test(@NotNull LootContext context) { 409 | ItemStack tool = context.get(LootContext.TOOL); 410 | 411 | int level = EnchantmentUtils.level(tool, enchantment); 412 | 413 | float chance = chances.get(Math.min(this.chances.size() - 1, level)); 414 | 415 | return context.require(LootContext.RANDOM).nextFloat() < chance; 416 | } 417 | 418 | @Override 419 | public @NotNull StructCodec codec() { 420 | return CODEC; 421 | } 422 | } 423 | 424 | record TimeCheck(@Nullable Long period, @NotNull LootNumberRange value) implements LootPredicate { 425 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 426 | "period", Codec.LONG.optional(), TimeCheck::period, 427 | "value", LootNumberRange.CODEC, TimeCheck::value, 428 | TimeCheck::new 429 | ); 430 | 431 | @Override 432 | public boolean test(@NotNull LootContext context) { 433 | long time = context.require(LootContext.WORLD).getTime(); 434 | 435 | if (period != null) { 436 | time %= period; 437 | } 438 | 439 | return value.check(context, time); 440 | } 441 | 442 | @Override 443 | public @NotNull StructCodec codec() { 444 | return CODEC; 445 | } 446 | } 447 | 448 | record ValueCheck(@NotNull LootNumber value, @NotNull LootNumberRange range) implements LootPredicate { 449 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 450 | "value", LootNumber.CODEC, ValueCheck::value, 451 | "range", LootNumberRange.CODEC, ValueCheck::range, 452 | ValueCheck::new 453 | ); 454 | 455 | @Override 456 | public boolean test(@NotNull LootContext context) { 457 | return range.check(context, value.getInt(context)); 458 | } 459 | 460 | @Override 461 | public @NotNull StructCodec codec() { 462 | return CODEC; 463 | } 464 | } 465 | 466 | record WeatherCheck(@Nullable Boolean raining, @Nullable Boolean thundering) implements LootPredicate { 467 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 468 | "raining", Codec.BOOLEAN.optional(), WeatherCheck::raining, 469 | "thundering", Codec.BOOLEAN.optional(), WeatherCheck::thundering, 470 | WeatherCheck::new 471 | ); 472 | 473 | @Override 474 | public boolean test(@NotNull LootContext context) { 475 | Weather weather = context.require(LootContext.WORLD).getWeather(); 476 | 477 | return (raining == null || raining == weather.isRaining()) && 478 | (thundering == null || thundering == weather.thunderLevel() > 0); 479 | } 480 | 481 | @Override 482 | public @NotNull StructCodec codec() { 483 | return CODEC; 484 | } 485 | } 486 | 487 | } 488 | 489 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootScore.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.goldenstack.loot.util.RelevantEntity; 4 | import net.minestom.server.codec.Codec; 5 | import net.minestom.server.codec.StructCodec; 6 | import net.minestom.server.registry.DynamicRegistry; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | import java.util.function.Function; 11 | 12 | /** 13 | * A score provider that produces functions that map an objective to a score value. 14 | */ 15 | @SuppressWarnings("UnstableApiUsage") 16 | public interface LootScore extends Function<@NotNull LootContext, Function<@NotNull String, @Nullable Integer>> { 17 | 18 | @NotNull Codec CODEC = RelevantEntity.CODEC.transform(Context::new, c -> ((Context) c).name()).orElse(Codec.RegistryTaggedUnion(registries -> { 19 | class Holder { 20 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 21 | } 22 | return Holder.CODEC; 23 | }, LootScore::codec, "type")); 24 | 25 | static @NotNull DynamicRegistry> createDefaultRegistry() { 26 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:loot_scores"); 27 | registry.register("context", Context.CODEC); 28 | registry.register("fixed", Fixed.CODEC); 29 | return registry; 30 | } 31 | 32 | @Override 33 | @NotNull Function<@NotNull String, @Nullable Integer> apply(@NotNull LootContext context); 34 | 35 | /** 36 | * @return the codec that can encode this score 37 | */ 38 | @NotNull StructCodec codec(); 39 | 40 | record Context(@NotNull RelevantEntity name) implements LootScore { 41 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 42 | "name", RelevantEntity.CODEC, Context::name, 43 | Context::new 44 | ); 45 | 46 | @Override 47 | public @NotNull Function<@NotNull String, @Nullable Integer> apply(@NotNull LootContext context) { 48 | return objective -> context.vanilla().score(context.require(name.key()), objective); 49 | } 50 | 51 | @Override 52 | public @NotNull StructCodec codec() { 53 | return CODEC; 54 | } 55 | } 56 | 57 | record Fixed(@NotNull String name) implements LootScore { 58 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 59 | "name", Codec.STRING, Fixed::name, 60 | Fixed::new 61 | ); 62 | 63 | @Override 64 | public @NotNull Function<@NotNull String, @Nullable Integer> apply(@NotNull LootContext context) { 65 | return objective -> context.vanilla().score(name, objective); 66 | } 67 | 68 | @Override 69 | public @NotNull StructCodec codec() { 70 | return CODEC; 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/LootTable.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.kyori.adventure.key.Key; 4 | import net.minestom.server.codec.Codec; 5 | import net.minestom.server.codec.StructCodec; 6 | import net.minestom.server.item.ItemStack; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * A loot table. 15 | * @param pools the pools that generate items in this table 16 | * @param functions the functions applied to each output item of this table 17 | * @param randomSequence An ID specifying the name of the random sequence that is used to generate loot from this loot table. 18 | */ 19 | public record LootTable(@NotNull List pools, @NotNull List functions, @Nullable Key randomSequence) implements LootGenerator { 20 | 21 | public static final @NotNull LootTable EMPTY = new LootTable(List.of(), List.of(), null); 22 | 23 | @SuppressWarnings("UnstableApiUsage") 24 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 25 | "pools", LootPool.CODEC.list().optional(List.of()), LootTable::pools, 26 | "functions", LootFunction.CODEC.list().optional(List.of()), LootTable::functions, 27 | "random_sequence", Codec.KEY.optional(), LootTable::randomSequence, 28 | LootTable::new 29 | ); 30 | 31 | @Override 32 | public @NotNull List generate(@NotNull LootContext context) { 33 | List items = new ArrayList<>(); 34 | 35 | for (var pool : pools) { 36 | for (var item : pool.generate(context)) { 37 | items.add(LootFunction.apply(functions, item, context)); 38 | } 39 | } 40 | 41 | return items; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/Trove.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot; 2 | 3 | import net.kyori.adventure.key.Key; 4 | import net.kyori.adventure.nbt.BinaryTag; 5 | import net.kyori.adventure.nbt.TagStringIOExt; 6 | import net.minestom.server.MinecraftServer; 7 | import net.minestom.server.codec.Transcoder; 8 | import net.minestom.server.coordinate.Point; 9 | import net.minestom.server.coordinate.Pos; 10 | import net.minestom.server.coordinate.Vec; 11 | import net.minestom.server.entity.EntityType; 12 | import net.minestom.server.entity.ItemEntity; 13 | import net.minestom.server.instance.Instance; 14 | import net.minestom.server.item.ItemStack; 15 | import net.minestom.server.registry.RegistryTranscoder; 16 | import net.minestom.server.utils.time.TimeUnit; 17 | import org.jetbrains.annotations.NotNull; 18 | 19 | import java.io.IOException; 20 | import java.nio.file.Files; 21 | import java.nio.file.Path; 22 | import java.util.HashMap; 23 | import java.util.List; 24 | import java.util.Map; 25 | import java.util.concurrent.ThreadLocalRandom; 26 | import java.util.stream.Collectors; 27 | import java.util.stream.StreamSupport; 28 | 29 | public class Trove { 30 | 31 | private Trove() {} 32 | 33 | /** 34 | * Parses every JSON file in the provided directory, or one of its subdirectories, into loot tables, returning the 35 | * results in to a table registry instance. 36 | * @param directory the directory to parse 37 | * @return the registry instance that contains parsing information 38 | */ 39 | @SuppressWarnings("UnstableApiUsage") 40 | public static @NotNull Map readTables(@NotNull Path directory) { 41 | Map tables = new HashMap<>(); 42 | 43 | final String FILE_SUFFIX = ".json"; 44 | 45 | List files; 46 | try (var stream = Files.find(directory, Integer.MAX_VALUE, 47 | (path, attr) -> attr.isRegularFile() && path.getFileName().toString().endsWith(FILE_SUFFIX))) { 48 | files = stream.toList(); 49 | } catch (IOException e) { 50 | throw new RuntimeException(e); 51 | } 52 | 53 | final Transcoder coder = new RegistryTranscoder<>(Transcoder.NBT, MinecraftServer.process()); 54 | 55 | for (var path : files) { 56 | 57 | String keyPath = StreamSupport.stream(directory.relativize(path).spliterator(), false).map(Path::toString).collect(Collectors.joining("/")); 58 | 59 | if (!keyPath.endsWith(FILE_SUFFIX)) continue; 60 | keyPath = keyPath.substring(0, keyPath.length() - FILE_SUFFIX.length()); 61 | 62 | BinaryTag tag; 63 | try { 64 | tag = TagStringIOExt.readTag(Files.readString(path)); 65 | } catch (IOException e) { 66 | throw new RuntimeException(e); 67 | } 68 | 69 | tables.put( 70 | Key.key(keyPath), 71 | LootTable.CODEC.decode(coder, tag).orElseThrow("parsing " + path) 72 | ); 73 | } 74 | 75 | return tables; 76 | } 77 | 78 | public static void blockDrop(@NotNull Instance instance, @NotNull ItemStack item, @NotNull Point block) { 79 | ThreadLocalRandom rng = ThreadLocalRandom.current(); 80 | 81 | Pos spawn = new Pos( 82 | block.blockX() + 0.5 + rng.nextDouble(-0.25, 0.25), 83 | block.blockY() + 0.5 + rng.nextDouble(-0.25, 0.25) - EntityType.ITEM.height() / 2, 84 | block.blockZ() + 0.5 + rng.nextDouble(-0.25, 0.25), 85 | rng.nextFloat(360), 86 | 0 87 | ); 88 | 89 | drop(instance, item, spawn); 90 | } 91 | 92 | public static void drop(@NotNull Instance instance, @NotNull ItemStack item, @NotNull Point position) { 93 | ItemEntity entity = new ItemEntity(item); 94 | 95 | ThreadLocalRandom rng = ThreadLocalRandom.current(); 96 | 97 | Vec vel = new Vec( 98 | rng.nextDouble(-0.1, 0.1), 99 | 0.2, 100 | rng.nextDouble(-0.1, 0.1) 101 | ).mul(20); 102 | 103 | entity.setPickupDelay(10, TimeUnit.SERVER_TICK); 104 | 105 | entity.setInstance(instance, position); 106 | entity.setVelocity(vel); 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/EnchantmentUtils.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.minestom.server.component.DataComponent; 4 | import net.minestom.server.component.DataComponents; 5 | import net.minestom.server.entity.Entity; 6 | import net.minestom.server.entity.EquipmentSlot; 7 | import net.minestom.server.entity.LivingEntity; 8 | import net.minestom.server.item.ItemStack; 9 | import net.minestom.server.item.Material; 10 | import net.minestom.server.item.component.EnchantmentList; 11 | import net.minestom.server.item.enchant.Enchantment; 12 | import net.minestom.server.registry.DynamicRegistry; 13 | import org.jetbrains.annotations.NotNull; 14 | import org.jetbrains.annotations.Nullable; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | import java.util.function.Consumer; 19 | 20 | public class EnchantmentUtils { 21 | 22 | private EnchantmentUtils() { 23 | } 24 | 25 | public static int level(@Nullable ItemStack item, @NotNull DynamicRegistry.Key key) { 26 | if (item == null) return 0; 27 | 28 | EnchantmentList enchantments = item.get(DataComponents.ENCHANTMENTS); 29 | if (enchantments == null) return 0; 30 | 31 | return enchantments.enchantments().getOrDefault(key, 0); 32 | } 33 | 34 | public static int level(@Nullable Entity entity, @NotNull DynamicRegistry.Key key) { 35 | int level = 0; 36 | if (entity instanceof LivingEntity living) { 37 | for (EquipmentSlot slot : EquipmentSlot.values()) { 38 | EnchantmentList ench = living.getEquipment(slot).get(DataComponents.ENCHANTMENTS); 39 | if (ench == null) continue; 40 | 41 | level = Math.max(level, ench.level(key)); 42 | } 43 | } 44 | 45 | return level; 46 | } 47 | 48 | public static @NotNull ItemStack modifyItem(@NotNull ItemStack item, @NotNull Consumer, Integer>> enchantments) { 49 | DataComponent type = item.material().equals(Material.ENCHANTED_BOOK) ? DataComponents.STORED_ENCHANTMENTS : DataComponents.ENCHANTMENTS; 50 | 51 | EnchantmentList component = item.get(type, EnchantmentList.EMPTY); 52 | 53 | var map = new HashMap<>(component.enchantments()); 54 | enchantments.accept(map); 55 | 56 | // Make the book enchanted! 57 | if (!map.isEmpty() && item.material().equals(Material.BOOK)) { 58 | return item.builder() 59 | .material(Material.ENCHANTED_BOOK) 60 | .set(DataComponents.STORED_ENCHANTMENTS, new EnchantmentList(map)) 61 | .build(); 62 | } else { 63 | return item.with(type, new EnchantmentList(map)); 64 | } 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/ListOperation.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.minestom.server.codec.Codec; 4 | import net.minestom.server.codec.StructCodec; 5 | import net.minestom.server.registry.DynamicRegistry; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.stream.Stream; 12 | 13 | @SuppressWarnings("UnstableApiUsage") 14 | public sealed interface ListOperation { 15 | 16 | @NotNull StructCodec CODEC = Codec.RegistryTaggedUnion(registries -> { 17 | class Holder { 18 | static final @NotNull DynamicRegistry> CODEC = createDefaultRegistry(); 19 | } 20 | return Holder.CODEC; 21 | }, ListOperation::codec, "type"); 22 | 23 | static @NotNull DynamicRegistry> createDefaultRegistry() { 24 | final DynamicRegistry> registry = DynamicRegistry.create("minecraft:list_operations"); 25 | registry.register("append", Append.CODEC); 26 | registry.register("insert", Insert.CODEC); 27 | registry.register("replace_all", ReplaceAll.CODEC); 28 | registry.register("replace_section", ReplaceSection.CODEC); 29 | return registry; 30 | } 31 | 32 | @NotNull List apply(@NotNull List values, @NotNull List input); 33 | 34 | /** 35 | * @return the codec that can encode this list operation 36 | */ 37 | @NotNull StructCodec codec(); 38 | 39 | record WithValues(@NotNull ListOperation operation, @NotNull List values) { 40 | public static Codec> codec(Codec codec) { 41 | return StructCodec.struct( 42 | StructCodec.INLINE, ListOperation.CODEC, WithValues::operation, 43 | "values", codec.list(), WithValues::values, 44 | WithValues::new 45 | ); 46 | } 47 | } 48 | 49 | record Append() implements ListOperation { 50 | public static final @NotNull StructCodec CODEC = StructCodec.struct(Append::new); 51 | 52 | @Override 53 | public @NotNull List apply(@NotNull List values, @NotNull List input) { 54 | return Stream.concat(input.stream(), values.stream()).toList(); 55 | } 56 | 57 | @Override 58 | public @NotNull StructCodec codec() { 59 | return CODEC; 60 | } 61 | } 62 | 63 | record Insert(int offset) implements ListOperation { 64 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 65 | "offset", Codec.INT.optional(0), Insert::offset, 66 | Insert::new 67 | ); 68 | 69 | @Override 70 | public @NotNull List apply(@NotNull List values, @NotNull List input) { 71 | List items = new ArrayList<>(); 72 | items.addAll(input.subList(0, this.offset)); 73 | items.addAll(values); 74 | items.addAll(input.subList(this.offset, input.size())); 75 | return items; 76 | } 77 | 78 | @Override 79 | public @NotNull StructCodec codec() { 80 | return CODEC; 81 | } 82 | } 83 | 84 | record ReplaceAll() implements ListOperation { 85 | public static final @NotNull StructCodec CODEC = StructCodec.struct(ReplaceAll::new); 86 | 87 | @Override 88 | public @NotNull List apply(@NotNull List values, @NotNull List input) { 89 | return values; 90 | } 91 | 92 | @Override 93 | public @NotNull StructCodec codec() { 94 | return CODEC; 95 | } 96 | } 97 | 98 | record ReplaceSection(int offset, @Nullable Integer size) implements ListOperation { 99 | public static final @NotNull StructCodec CODEC = StructCodec.struct( 100 | "offset", Codec.INT.optional(0), ReplaceSection::offset, 101 | "size", Codec.INT.optional(), ReplaceSection::size, 102 | ReplaceSection::new 103 | ); 104 | 105 | @Override 106 | public @NotNull List apply(@NotNull List values, @NotNull List input) { 107 | List items = new ArrayList<>(); 108 | items.addAll(input.subList(0, offset)); 109 | items.addAll(values); 110 | 111 | int size = this.size != null ? this.size : values.size(); 112 | 113 | // Add truncated part of list of possible 114 | if (offset + size < input.size()) { 115 | items.addAll(input.subList(offset + size, input.size())); 116 | } 117 | 118 | return items; 119 | } 120 | 121 | @Override 122 | public @NotNull StructCodec codec() { 123 | return CODEC; 124 | } 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/LootNumberRange.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.goldenstack.loot.LootContext; 4 | import net.goldenstack.loot.LootNumber; 5 | import net.minestom.server.codec.Codec; 6 | import net.minestom.server.codec.StructCodec; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | /** 11 | * An inclusive number range based on loot numbers. 12 | * @param min the optional minimum value 13 | * @param max the optional maximum value 14 | */ 15 | public record LootNumberRange(@Nullable LootNumber min, @Nullable LootNumber max) { 16 | 17 | @SuppressWarnings({"UnstableApiUsage", "NumberEquality"}) 18 | public static final @NotNull Codec CODEC = Codec.DOUBLE.transform(LootNumber.Constant::new, LootNumber.Constant::value) 19 | .transform(n -> new LootNumberRange(n, n), r -> { 20 | if (r.min() instanceof LootNumber.Constant(Double min) && r.max() instanceof LootNumber.Constant(Double max) && min == max) { 21 | return (LootNumber.Constant) r.min(); 22 | } else throw new UnsupportedOperationException("Using struct codec"); 23 | }).orElse(StructCodec.struct( 24 | "min", LootNumber.CODEC, LootNumberRange::min, 25 | "max", LootNumber.CODEC, LootNumberRange::max, 26 | LootNumberRange::new 27 | )); 28 | 29 | /** 30 | * Limits the provided value to between the minimum and maximum.
31 | * This API currently guarantees that, if the minimum ends up being larger than the maximum, the resulting value 32 | * will be equal to the maximum. 33 | * @param context the context, to use for getting the values of the min and max 34 | * @param number the number to constrain to between the minimum and maximum 35 | * @return the constrained number 36 | */ 37 | public long limit(@NotNull LootContext context, long number) { 38 | if (this.min != null) { 39 | number = Math.max(this.min.getInt(context), number); 40 | } 41 | if (this.max != null) { 42 | number = Math.min(this.max.getInt(context), number); 43 | } 44 | return number; 45 | } 46 | 47 | /** 48 | * Limits the provided value to between the minimum and maximum.
49 | * This API currently guarantees that, if the minimum ends up being larger than the maximum, the resulting value 50 | * will be equal to the maximum. 51 | * @param context the context, to use for getting the values of the min and max 52 | * @param number the number to constrain to between the minimum and maximum 53 | * @return the constrained number 54 | */ 55 | public double limit(@NotNull LootContext context, double number) { 56 | if (this.min != null) { 57 | number = Math.max(this.min.getDouble(context), number); 58 | } 59 | if (this.max != null) { 60 | number = Math.min(this.max.getDouble(context), number); 61 | } 62 | return number; 63 | } 64 | 65 | /** 66 | * Assures that the provided number is not smaller than the minimum and is not larger than the maximum. If either of 67 | * the bounds is null, it's always considered as passing. 68 | * @param context the context, to use for getting the values of the min and max 69 | * @param number the number to check the validity of 70 | * @return true if the provided number fits within {@link #min()} and {@link #max()}, and false otherwise 71 | */ 72 | public boolean check(@NotNull LootContext context, long number) { 73 | return (this.min == null || this.min.getInt(context) <= number) && 74 | (this.max == null || this.max.getInt(context) >= number); 75 | } 76 | 77 | /** 78 | * Assures that the provided number is not smaller than the minimum and is not larger than the maximum. If either of 79 | * the bounds is null, it's always considered as passing. 80 | * @param context the context, to use for getting the values of the min and max 81 | * @param number the number to check the validity of 82 | * @return true if the provided number fits within {@link #min()} and {@link #max()}, and false otherwise 83 | */ 84 | public boolean check(@NotNull LootContext context, double number) { 85 | return (this.min == null || this.min.getDouble(context) <= number) && 86 | (this.max == null || this.max.getDouble(context) >= number); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/RelevantEntity.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.goldenstack.loot.LootContext; 4 | import net.minestom.server.codec.Codec; 5 | import net.minestom.server.entity.Entity; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public enum RelevantEntity { 9 | THIS("this", LootContext.THIS_ENTITY), 10 | KILLER("killer", LootContext.ATTACKING_ENTITY), 11 | DIRECT_KILLER("direct_killer", LootContext.DIRECT_ATTACKING_ENTITY), 12 | LAST_PLAYER_DAMAGE("killer_player", LootContext.LAST_DAMAGE_PLAYER); 13 | 14 | @SuppressWarnings("UnstableApiUsage") 15 | public static final @NotNull Codec CODEC = Codec.Enum(RelevantEntity.class); // Relies on the enum names themselves being accurate 16 | 17 | private final @NotNull String id; 18 | private final @NotNull LootContext.Key key; 19 | 20 | RelevantEntity(@NotNull String id, @NotNull LootContext.Key key) { 21 | this.id = id; 22 | this.key = key; 23 | } 24 | 25 | public @NotNull String id() { 26 | return id; 27 | } 28 | 29 | public @NotNull LootContext.Key key() { 30 | return key; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/RelevantTarget.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.goldenstack.loot.LootContext; 4 | import net.minestom.server.codec.Codec; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | public enum RelevantTarget { 8 | THIS("this", LootContext.THIS_ENTITY), 9 | ATTACKING_ENTITY("attacking_entity", LootContext.ATTACKING_ENTITY), 10 | LAST_DAMAGE_PLAYER("last_damage_player", LootContext.LAST_DAMAGE_PLAYER), 11 | BLOCK_ENTITY("block_entity", LootContext.BLOCK_STATE); 12 | 13 | @SuppressWarnings("UnstableApiUsage") 14 | public static final Codec CODEC = Codec.Enum(RelevantTarget.class); // Relies on the enum names themselves being accurate 15 | 16 | private final @NotNull String id; 17 | private final @NotNull LootContext.Key key; 18 | 19 | RelevantTarget(@NotNull String id, @NotNull LootContext.Key key) { 20 | this.id = id; 21 | this.key = key; 22 | } 23 | 24 | public @NotNull String id() { 25 | return id; 26 | } 27 | 28 | public @NotNull LootContext.Key key() { 29 | return key; 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/Template.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.kyori.adventure.key.Key; 4 | import net.minestom.server.MinecraftServer; 5 | import net.minestom.server.codec.Codec; 6 | import net.minestom.server.component.DataComponent; 7 | import net.minestom.server.component.DataComponents; 8 | import net.minestom.server.gamedata.tags.Tag; 9 | import net.minestom.server.item.ItemStack; 10 | import net.minestom.server.registry.DynamicRegistry; 11 | import net.minestom.server.registry.Registries; 12 | import org.jetbrains.annotations.NotNull; 13 | 14 | import java.util.*; 15 | import java.util.function.Function; 16 | import java.util.stream.Collectors; 17 | import java.util.stream.Stream; 18 | 19 | @SuppressWarnings("UnstableApiUsage") 20 | public class Template { 21 | 22 | // TODO: Need equivalent of compoundSplit (investigate orElse usage) 23 | 24 | private static final @NotNull Map>> NAMED_CONTAINERS = 25 | Stream.of(DataComponents.CONTAINER, DataComponents.BUNDLE_CONTENTS, DataComponents.CHARGED_PROJECTILES) 26 | .collect(Collectors.toMap(DataComponent::key, Function.identity())); 27 | 28 | public static final @NotNull Codec>> CONTAINER = Codec.KEY.transform(NAMED_CONTAINERS::get, DataComponent::key); 29 | 30 | public static @NotNull Codec>> keyOrTag(@NotNull Registries.Selector selector, @NotNull Tag.BasicType type) { 31 | return Codec.RegistryKey(selector).list() 32 | .orElse(Codec.STRING.transform(string -> { 33 | if (string.startsWith("#")) { 34 | List> values = new ArrayList<>(); 35 | MinecraftServer.getTagManager() 36 | .getTag(type, string.substring(1)) 37 | .getValues() 38 | .forEach(value -> values.add(DynamicRegistry.Key.of(value))); 39 | return values; 40 | } else { 41 | return List.of(DynamicRegistry.Key.of(string)); 42 | } 43 | }, ignored -> { 44 | throw new UnsupportedOperationException(); 45 | })); 46 | } 47 | 48 | @SafeVarargs 49 | public static @NotNull Codec constant(@NotNull Function name, @NotNull T @NotNull ... entries) { 50 | return constant(name, Arrays.asList(entries)); 51 | } 52 | 53 | public static @NotNull Codec constant(@NotNull Function name, @NotNull Collection entries) { 54 | Map named = entries.stream().collect(Collectors.toMap(name, Function.identity())); 55 | 56 | return Codec.STRING.transform(string -> Objects.requireNonNull(named.get(string)), name::apply); 57 | } 58 | 59 | // public static @NotNull BinaryTagSerializer compoundSplit(@NotNull BinaryTagSerializer inline, @NotNull BinaryTagSerializer compound) { 60 | // return new BinaryTagSerializer<>() { 61 | // @Override 62 | // public @NotNull BinaryTag write(@NotNull Context context, @NotNull T value) { 63 | // return compound.write(context, value); 64 | // } 65 | // 66 | // @Override 67 | // public @NotNull T read(@NotNull Context context, @NotNull BinaryTag tag) { 68 | // return (tag instanceof CompoundBinaryTag ? compound : inline).read(context, tag); 69 | // } 70 | // }; 71 | // } 72 | // 73 | // public record Entry(@NotNull String key, @NotNull Class type, @NotNull BinaryTagSerializer serializer) {} 74 | // 75 | // public static @NotNull Entry entry(@NotNull String key, @NotNull Class type, @NotNull BinaryTagSerializer serializer) { 76 | // key = NamespaceID.from(key).asString(); 77 | // return new Entry<>(key, type, serializer); 78 | // } 79 | // 80 | // @SafeVarargs 81 | // public static @NotNull BinaryTagSerializer registry(@NotNull String key, @NotNull Entry @NotNull ... entries) { 82 | // Map> named = Arrays.stream(entries).collect(Collectors.toMap(Entry::key, Function.identity())); 83 | // Map, Entry> typed = Arrays.stream(entries).collect(Collectors.toMap(Entry::type, Function.identity())); 84 | // 85 | // return new BinaryTagSerializer<>() { 86 | // @Override 87 | // public @NotNull BinaryTag write(@NotNull Context context, @NotNull T value) { 88 | // return handle(typed.get(value.getClass()), context, value); 89 | // } 90 | // 91 | // @SuppressWarnings("unchecked") 92 | // private BinaryTag handle(@NotNull Entry entry, Context context, T value) { 93 | // BinaryTag tag = entry.serializer().write(context, (N) value); 94 | // if (tag instanceof CompoundBinaryTag compoud) { 95 | // return compoud.put(key, StringBinaryTag.stringBinaryTag(entry.key())); 96 | // } else { 97 | // return tag; 98 | // } 99 | // } 100 | // 101 | // @Override 102 | // public @NotNull T read(@NotNull Context context, @NotNull BinaryTag raw) { 103 | // if (!(raw instanceof CompoundBinaryTag tag)) throw new IllegalArgumentException("Expected a compound tag"); 104 | // if (!(tag.get(key) instanceof StringBinaryTag string)) throw new IllegalArgumentException("Expected a string at key '" + key + "'"); 105 | // 106 | // Entry entry = named.get(string.value()); 107 | // if (entry == null) throw new IllegalArgumentException("Invalid named key '" + string.value() + "'"); 108 | // 109 | // return entry.serializer().read(context, tag); 110 | // } 111 | // }; 112 | // } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/VanillaInterface.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util; 2 | 3 | import net.goldenstack.loot.LootFunction; 4 | import net.goldenstack.loot.LootPredicate; 5 | import net.goldenstack.loot.LootTable; 6 | import net.kyori.adventure.key.Key; 7 | import net.kyori.adventure.nbt.BinaryTag; 8 | import net.kyori.adventure.nbt.CompoundBinaryTag; 9 | import net.kyori.adventure.text.Component; 10 | import net.minestom.server.entity.Entity; 11 | import net.minestom.server.item.ItemStack; 12 | import net.minestom.server.item.Material; 13 | import net.minestom.server.item.enchant.Enchantment; 14 | import net.minestom.server.registry.DynamicRegistry; 15 | import net.minestom.server.tag.Tag; 16 | import org.jetbrains.annotations.NotNull; 17 | import org.jetbrains.annotations.Nullable; 18 | 19 | import java.util.List; 20 | import java.util.Random; 21 | 22 | public interface VanillaInterface { 23 | 24 | static @NotNull VanillaInterface defaults() { 25 | return new VanillaInterface() { 26 | @Override 27 | public @Nullable Integer score(@NotNull Entity entity, @NotNull String objective) { 28 | return null; 29 | } 30 | 31 | @Override 32 | public @Nullable Integer score(@NotNull String name, @NotNull String objective) { 33 | return null; 34 | } 35 | 36 | @Override 37 | public @NotNull BinaryTag serializeEntity(@NotNull Entity entity) { 38 | return CompoundBinaryTag.empty(); 39 | } 40 | 41 | @Override 42 | public @NotNull ItemStack enchant(@NotNull Random random, @NotNull ItemStack item, int levels, @Nullable List> enchantments) { 43 | return item; 44 | } 45 | 46 | @Override 47 | public @Nullable ItemStack smelt(@NotNull ItemStack input) { 48 | return null; 49 | } 50 | 51 | @Override 52 | public @Nullable LootTable tableRegistry(@NotNull Key key) { 53 | return null; 54 | } 55 | 56 | @Override 57 | public @Nullable LootPredicate predicateRegistry(@NotNull Key key) { 58 | return null; 59 | } 60 | 61 | @Override 62 | public @Nullable LootFunction functionRegistry(@NotNull Key key) { 63 | return null; 64 | } 65 | 66 | @Override 67 | public @Nullable CompoundBinaryTag commandStorage(@NotNull Key key) { 68 | return null; 69 | } 70 | }; 71 | } 72 | 73 | @NotNull Tag CUSTOM_NAME = Tag.Component("CustomName"); 74 | 75 | @NotNull Tag> DECORATED_POT_SHERDS = Tag.String("sherds") 76 | .map(Key::key, Key::asString) 77 | .map(Material::fromKey, Material::key) 78 | .list().defaultValue(List::of); 79 | 80 | @NotNull Tag> CONTAINER_ITEMS = Tag.ItemStack("Items").list().defaultValue(List::of); 81 | 82 | @Nullable Integer score(@NotNull Entity entity, @NotNull String objective); 83 | 84 | @Nullable Integer score(@NotNull String name, @NotNull String objective); 85 | 86 | @NotNull BinaryTag serializeEntity(@NotNull Entity entity); 87 | 88 | @NotNull ItemStack enchant(@NotNull Random random, @NotNull ItemStack item, int levels, @Nullable List> enchantments); 89 | 90 | @Nullable ItemStack smelt(@NotNull ItemStack input); 91 | 92 | @Nullable LootTable tableRegistry(@NotNull Key key); 93 | 94 | @Nullable LootPredicate predicateRegistry(@NotNull Key key); 95 | 96 | @Nullable LootFunction functionRegistry(@NotNull Key key); 97 | 98 | @Nullable CompoundBinaryTag commandStorage(@NotNull Key key); 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/nbt/NBTPath.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.nbt; 2 | 3 | import it.unimi.dsi.fastutil.ints.IntSet; 4 | import net.kyori.adventure.nbt.*; 5 | import net.minestom.server.codec.Codec; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | import java.io.IOException; 10 | import java.io.StringReader; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.function.Consumer; 15 | import java.util.function.Supplier; 16 | import java.util.stream.Collectors; 17 | 18 | /** 19 | * A NBTPath allows selecting specific elements from a NBT tree, based on a list of selectors. Each selector has the 20 | * ability to select any number of elements from its predecessor—this allows arbitrary item selection from any NBT type. 21 | *
22 | * It also provides multiple ways to manipulate NBT results as there is no deeply mutable NBT implementation. 23 | */ 24 | public record NBTPath(@NotNull List selectors) { 25 | 26 | @SuppressWarnings("UnstableApiUsage") 27 | public static final @NotNull Codec CODEC = Parser.CODEC; 28 | 29 | /** 30 | * Selects an arbitrary number of elements from provided NBT. 31 | */ 32 | public sealed interface Selector { 33 | 34 | /** 35 | * Passes each selected NBT element into the given consumer. 36 | */ 37 | void get(@NotNull NBTReference source, @NotNull Consumer consumer); 38 | 39 | /** 40 | * Modifies the provided {@code source} so that, if possible, this path selector will select at least one NBT 41 | * element from it. If a placeholder element is needed, {@code nextElement} is to be used. 42 | */ 43 | void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement); 44 | 45 | /** 46 | * Provides a tag that this selector may be willing to modify. 47 | */ 48 | @NotNull BinaryTag preparedNBT(); 49 | 50 | record RootKey(@NotNull String key) implements Selector { 51 | @Override 52 | public void get(@NotNull NBTReference source, @NotNull Consumer consumer) { 53 | if (source.has(key)) { 54 | consumer.accept(source.get(key)); 55 | } 56 | } 57 | 58 | @Override 59 | public void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement) {} 60 | 61 | @Override 62 | public @NotNull BinaryTag preparedNBT() { 63 | return CompoundBinaryTag.empty(); 64 | } 65 | 66 | @Override 67 | public String toString() { 68 | return key; 69 | } 70 | } 71 | 72 | record Key(@NotNull String key) implements Selector { 73 | @Override 74 | public void get(@NotNull NBTReference source, @NotNull Consumer consumer) { 75 | if (source.has(key)) { 76 | consumer.accept(source.get(key)); 77 | } 78 | } 79 | 80 | @Override 81 | public void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement) { 82 | if (!source.has(key)) { 83 | source.get(key).set(nextElement.get()); 84 | } 85 | } 86 | 87 | @Override 88 | public @NotNull BinaryTag preparedNBT() { 89 | return CompoundBinaryTag.empty(); 90 | } 91 | 92 | @Override 93 | public String toString() { 94 | return "." + key; 95 | } 96 | } 97 | 98 | record CompoundFilter(@NotNull CompoundBinaryTag filter) implements Selector { 99 | @Override 100 | public void get(@NotNull NBTReference source, @NotNull Consumer consumer) { 101 | if (NBTUtils.compareNBT(filter, source.get(), false)) { 102 | consumer.accept(source); 103 | } 104 | } 105 | 106 | @Override 107 | public void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement) { 108 | if (!NBTUtils.compareNBT(filter, source.get(), false)) { 109 | source.set(filter); 110 | } 111 | } 112 | 113 | @Override 114 | public @NotNull BinaryTag preparedNBT() { 115 | return CompoundBinaryTag.empty(); 116 | } 117 | 118 | @Override 119 | public String toString() { 120 | try { 121 | return TagStringIO.get().asString(filter); 122 | } catch (IOException e) { 123 | throw new RuntimeException(e); 124 | } 125 | } 126 | } 127 | 128 | record EntireList() implements Selector { 129 | @Override 130 | public void get(@NotNull NBTReference source, @NotNull Consumer consumer) { 131 | int size = source.listSize(); 132 | for (int i = 0; i < size; i++) { 133 | consumer.accept(source.get(i)); 134 | } 135 | } 136 | 137 | @Override 138 | public void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement) { 139 | if (source.listSize() == 0) { 140 | source.listAdd(nextElement.get()); 141 | } 142 | } 143 | 144 | @Override 145 | public @NotNull BinaryTag preparedNBT() { 146 | return ListBinaryTag.empty(); 147 | } 148 | 149 | @Override 150 | public String toString() { 151 | return "[]"; 152 | } 153 | } 154 | 155 | record Index(int index) implements Selector { 156 | @Override 157 | public void get(@NotNull NBTReference source, @NotNull Consumer consumer) { 158 | var newIndex = index >= 0 ? index : source.listSize() + index; 159 | 160 | if (newIndex < 0 || newIndex >= source.listSize()) return; 161 | 162 | consumer.accept(source.get(newIndex)); 163 | } 164 | 165 | @Override 166 | public void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement) {} 167 | 168 | @Override 169 | public @NotNull BinaryTag preparedNBT() { 170 | return ListBinaryTag.empty(); 171 | } 172 | 173 | @Override 174 | public String toString() { 175 | return "[" + index + "]"; 176 | } 177 | } 178 | 179 | record ListFilter(@NotNull CompoundBinaryTag filter) implements Selector { 180 | @Override 181 | public void get(@NotNull NBTReference source, @NotNull Consumer consumer) { 182 | int listSize = source.listSize(); 183 | for (int i = 0; i < listSize; i++) { 184 | NBTReference ref = source.get(i); 185 | if (NBTUtils.compareNBT(filter, ref.get(), false)) { 186 | consumer.accept(ref); 187 | } 188 | } 189 | } 190 | 191 | @Override 192 | public void prepare(@NotNull NBTReference source, @NotNull Supplier nextElement) { 193 | int listSize = source.listSize(); 194 | if (listSize == -1) return; 195 | 196 | for (int i = 0; i < listSize; i++) { 197 | if (NBTUtils.compareNBT(filter, source.get(i).get(), false)) { 198 | return; 199 | } 200 | } 201 | 202 | source.listAdd(filter); 203 | } 204 | 205 | @Override 206 | public @NotNull BinaryTag preparedNBT() { 207 | return ListBinaryTag.empty(); 208 | } 209 | 210 | @Override 211 | public String toString() { 212 | try { 213 | return "[" + TagStringIO.get().asString(filter) + "]"; 214 | } catch (IOException e) { 215 | throw new RuntimeException(e); 216 | } 217 | } 218 | } 219 | 220 | } 221 | 222 | /** 223 | * Strings {@code source} through each selector in {@link #selectors()}, returning the selected results. It is 224 | * possible for there to be none. Modifying the resulting NBT references does nothing. 225 | * @param source the source, to get the NBT from 226 | * @return the list of selected NBT, which may be empty 227 | */ 228 | public @NotNull List get(@NotNull BinaryTag source) { 229 | List references = List.of(NBTReference.of(source)); 230 | for (var selector : selectors()) { 231 | List newReferences = new ArrayList<>(); 232 | 233 | references.forEach(nbt -> selector.get(nbt, newReferences::add)); 234 | 235 | if (newReferences.isEmpty()) { 236 | return List.of(); 237 | } 238 | references = newReferences; 239 | } 240 | return references; 241 | } 242 | 243 | /** 244 | * Strings {@code source} through each selector, making each selector 245 | * {@link Selector#prepare(NBTReference, Supplier) prepare} each element. This should result in this method 246 | * returning nothing much less often, although it is still possible. Modifying the resulting NBT references will 247 | * result in the provided {@code source} being modified. 248 | * @param source the source, to get the NBT from 249 | * @param finalDefault the default value for results produced from the last path selector 250 | * @return the list of selected NBT, which may be empty 251 | */ 252 | public @NotNull List getWithDefaults(@NotNull NBTReference source, @NotNull Supplier finalDefault) { 253 | List references = List.of(source); 254 | 255 | for (int selectorIndex = 0; selectorIndex < selectors().size(); selectorIndex++) { 256 | var selector = selectors().get(selectorIndex); 257 | Supplier next = (selectorIndex < selectors().size() - 1) ? selectors().get(selectorIndex + 1)::preparedNBT : finalDefault; 258 | 259 | List newNBT = new ArrayList<>(); 260 | for (var nbt : references) { 261 | selector.prepare(nbt, next); 262 | selector.get(nbt, newNBT::add); 263 | } 264 | if (newNBT.isEmpty()) { 265 | return List.of(); 266 | } 267 | 268 | references = newNBT; 269 | } 270 | 271 | return references; 272 | } 273 | 274 | /** 275 | * Strings {@code source} through each selector, making each selector 276 | * {@link Selector#prepare(NBTReference, Supplier) prepare} each element. This should result in this method 277 | * returning nothing much less often, although it is still possible. Modifying the resulting NBT references will 278 | * result in the provided {@code source} being modified. This is equivalent to calling 279 | * {@link #getWithDefaults(NBTReference, Supplier)} and setting all of the results to {@code setValue}. 280 | * @param source the source, to get the NBT from 281 | * @param setValue the value to set all selected elements to 282 | * @return the list of selected NBT, which may be empty 283 | */ 284 | public @NotNull List set(@NotNull NBTReference source, @NotNull BinaryTag setValue) { 285 | List references = getWithDefaults(source, () -> setValue); 286 | for (var reference : references) { 287 | reference.set(setValue); 288 | } 289 | return references; 290 | } 291 | 292 | @Override 293 | public String toString() { 294 | return selectors().stream().map(Selector::toString).collect(Collectors.joining()); 295 | } 296 | } 297 | 298 | @SuppressWarnings("UnstableApiUsage") 299 | class Parser { 300 | 301 | static final @NotNull IntSet VALID_SELECTOR_STARTERS = IntSet.of('.', '{', '['); 302 | static final @NotNull IntSet VALID_INTEGER_CHARACTERS = IntSet.of('-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); 303 | static final @NotNull IntSet INVALID_UNQUOTED_CHARACTERS = IntSet.of(-1, '.', '\'', '\"', '{', '}', '[', ']'); 304 | 305 | static final Codec CODEC = Codec.STRING.transform(s -> { 306 | try { 307 | return readPath(new StringReader(s)); 308 | } catch (IOException e) { 309 | throw new RuntimeException(e); 310 | } 311 | }, NBTPath::toString); 312 | 313 | static @NotNull NBTPath readPath(@NotNull StringReader reader) throws IOException { 314 | List selectors = new ArrayList<>(); 315 | 316 | if (!VALID_SELECTOR_STARTERS.contains(peek(reader))) { 317 | var key = readString(reader); 318 | if (key != null) { 319 | selectors.add(new NBTPath.Selector.RootKey(key)); 320 | } 321 | } 322 | 323 | while (true) { 324 | reader.mark(0); 325 | 326 | if (!VALID_SELECTOR_STARTERS.contains(peek(reader))) { 327 | if (selectors.isEmpty()) { 328 | throw new IllegalArgumentException("NBT paths must contain at least one selector"); 329 | } 330 | return new NBTPath(List.copyOf(selectors)); 331 | } 332 | 333 | var selector = readPathSelector(reader); 334 | if (selector == null) { 335 | throw new IllegalArgumentException("Invalid NBT path selector"); 336 | } 337 | 338 | selectors.add(selector); 339 | } 340 | } 341 | 342 | // Returning null indicates a failure to read 343 | @SuppressWarnings("ResultOfMethodCallIgnored") 344 | static @Nullable NBTPath.Selector readPathSelector(@NotNull StringReader reader) throws IOException { 345 | var firstChar = peek(reader); 346 | return switch (firstChar) { 347 | case '.' -> { 348 | reader.skip(1); // Skip period 349 | 350 | var string = readString(reader); 351 | yield string != null ? new NBTPath.Selector.Key(string) : null; 352 | } 353 | case '{' -> { 354 | var compound = readCompound(reader); 355 | yield compound != null ? new NBTPath.Selector.CompoundFilter(compound) : null; 356 | } 357 | case '[' -> { 358 | reader.skip(1); // Skip opening square brackets 359 | 360 | var secondChar = peek(reader); 361 | var selector = switch(secondChar) { 362 | case ']' -> new NBTPath.Selector.EntireList(); 363 | case '{' -> { 364 | var compound = readCompound(reader); 365 | yield compound != null ? new NBTPath.Selector.ListFilter(compound) : null; 366 | } 367 | default -> { 368 | if (VALID_INTEGER_CHARACTERS.contains(secondChar)) { 369 | var index = readInteger(reader); 370 | yield index != null ? new NBTPath.Selector.Index(index) : null; 371 | } 372 | yield null; 373 | } 374 | }; 375 | 376 | reader.skip(1); // Skip closing square brackets 377 | yield selector; 378 | } 379 | default -> null; 380 | }; 381 | } 382 | 383 | @SuppressWarnings("ResultOfMethodCallIgnored") 384 | private static @Nullable Integer readInteger(@NotNull StringReader reader) throws IOException { 385 | StringBuilder builder = new StringBuilder(); 386 | 387 | int peek; 388 | while (VALID_INTEGER_CHARACTERS.contains(peek = reader.read())) { 389 | builder.appendCodePoint(peek); 390 | } 391 | 392 | // Unread the one extra character that was read; this does nothing if the entire string has been read 393 | reader.skip(-1); 394 | 395 | try { 396 | return Integer.parseInt(builder.toString()); 397 | } catch (NumberFormatException e) { 398 | return null; 399 | } 400 | } 401 | 402 | @SuppressWarnings("ResultOfMethodCallIgnored") 403 | private static @Nullable String readString(@NotNull StringReader reader) throws IOException { 404 | var peek = peek(reader); 405 | if (peek == -1) { 406 | return null; 407 | } 408 | 409 | StringBuilder builder = new StringBuilder(); 410 | 411 | if (peek == '"' || peek == '\'') { // Read quoted string 412 | reader.skip(1); // Skip the character we know already 413 | 414 | boolean escape = false; 415 | 416 | while (true) { 417 | var next = reader.read(); 418 | 419 | if (next == '\\') { // Read escape character 420 | escape = true; 421 | } else if (next == peek && !escape) { // Return if unescaped closing character 422 | return builder.toString(); 423 | } else { 424 | if (escape) { // If there was an unused escape, re-add it; there's only one character it's used for 425 | builder.appendCodePoint('\\'); 426 | } 427 | 428 | if (next == -1) { 429 | return null; 430 | } 431 | 432 | builder.appendCodePoint(next); // Add the next character always 433 | } 434 | } 435 | } 436 | 437 | // Read unquoted string 438 | int read; 439 | while (!INVALID_UNQUOTED_CHARACTERS.contains(read = reader.read())) { 440 | builder.appendCodePoint(read); 441 | } 442 | 443 | // Unread the one extra character that was read; this does nothing if the entire string has been read 444 | reader.skip(-1); 445 | 446 | return builder.isEmpty() ? null : builder.toString(); 447 | } 448 | 449 | @SuppressWarnings("ResultOfMethodCallIgnored") 450 | private static int peek(@NotNull StringReader reader) throws IOException { 451 | var codePoint = reader.read(); 452 | reader.skip(-1); 453 | return codePoint; 454 | } 455 | 456 | @SuppressWarnings("ResultOfMethodCallIgnored") 457 | private static BinaryTag readTag(@NotNull StringReader reader) throws IOException { 458 | StringBuilder builder = new StringBuilder(); 459 | int count = 0; 460 | 461 | while (true) { 462 | int code = reader.read(); 463 | 464 | if (code == -1) break; 465 | 466 | builder.appendCodePoint(code); 467 | count++; 468 | } 469 | 470 | String dump = builder.toString(); 471 | 472 | Map.Entry entry = TagStringIOExt.readTagEmbedded(dump); 473 | 474 | reader.skip(-count + entry.getValue().length()); 475 | return entry.getKey(); 476 | } 477 | 478 | private static CompoundBinaryTag readCompound(@NotNull StringReader reader) throws IOException { 479 | if (readTag(reader) instanceof CompoundBinaryTag compound) { 480 | return compound; 481 | } else { 482 | throw new IllegalArgumentException("Expected an inline compound"); 483 | } 484 | } 485 | 486 | } 487 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/nbt/NBTReference.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.nbt; 2 | 3 | import net.kyori.adventure.nbt.BinaryTag; 4 | import net.kyori.adventure.nbt.BinaryTagTypes; 5 | import net.kyori.adventure.nbt.CompoundBinaryTag; 6 | import net.kyori.adventure.nbt.ListBinaryTag; 7 | import org.jetbrains.annotations.NotNull; 8 | 9 | import java.util.concurrent.atomic.AtomicReference; 10 | import java.util.function.Consumer; 11 | import java.util.function.Supplier; 12 | 13 | public record NBTReference(@NotNull Supplier getter, @NotNull Consumer setter) { 14 | 15 | public static @NotNull NBTReference of(@NotNull BinaryTag tag) { 16 | AtomicReference reference = new AtomicReference<>(tag); 17 | return new NBTReference(reference::get, reference::set); 18 | } 19 | 20 | public BinaryTag get() { 21 | return getter.get(); 22 | } 23 | 24 | public void set(BinaryTag nbt) { 25 | setter.accept(nbt); 26 | } 27 | 28 | public boolean has(@NotNull String key) { 29 | return get() instanceof CompoundBinaryTag compound && compound.get(key) != null; 30 | } 31 | 32 | public NBTReference get(@NotNull String key) { 33 | return new NBTReference( 34 | () -> get() instanceof CompoundBinaryTag compound ? compound.get(key) : null, 35 | nbt -> { 36 | if (get() instanceof CompoundBinaryTag compound) { 37 | set(compound.put(key, nbt)); 38 | } 39 | } 40 | ); 41 | } 42 | 43 | public int listSize() { 44 | return get() instanceof ListBinaryTag list ? list.size() : -1; 45 | } 46 | 47 | public @NotNull NBTReference get(int index) { 48 | return new NBTReference( 49 | () -> get() instanceof ListBinaryTag list && index >= 0 && index < list.size() ? list.get(index) : null, 50 | value -> { 51 | if (get() instanceof ListBinaryTag list 52 | && (value.type().equals(BinaryTagTypes.END) || list.elementType().equals(value.type())) 53 | && index >= 0 && index < list.size()) { 54 | set(list.set(index, value, null)); 55 | } 56 | } 57 | ); 58 | } 59 | 60 | public void listAdd(@NotNull BinaryTag tag) { 61 | if (get() instanceof ListBinaryTag list && (list.size() == 0 || list.elementType().equals(tag.type()))) { 62 | set(list.add(tag)); 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/nbt/NBTUtils.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.nbt; 2 | 3 | import net.kyori.adventure.nbt.BinaryTag; 4 | import net.kyori.adventure.nbt.CompoundBinaryTag; 5 | import net.kyori.adventure.nbt.ListBinaryTag; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.jetbrains.annotations.Nullable; 8 | 9 | public class NBTUtils { 10 | 11 | private NBTUtils() {} 12 | 13 | /** 14 | * Checks to see if everything in {@code standard} is contained in {@code comparison}. The comparison is allowed to 15 | * have extra fields that are not contained in the standard. 16 | * @param standard the standard that the comparison must have all elements of 17 | * @param comparison the comparison, that is being compared against the standard. NBT compounds in this parameter, 18 | * whether deeper in the tree or not, are allowed to have keys that the standard does not - it's 19 | * basically compared against a standard. 20 | * @param assureListOrder whether or not to assure list order. When true, lists are directly compared, but when 21 | * false, the comparison is checked to see if it contains each item in the standard. 22 | * @return true if the comparison fits the standard, otherwise false 23 | */ 24 | public static boolean compareNBT(@Nullable BinaryTag standard, @Nullable BinaryTag comparison, boolean assureListOrder) { 25 | if (standard == null) { 26 | return true; // If there's no standard, it must always pass 27 | } else if (comparison == null) { 28 | return false; // If it's null at this point, we already assured that standard is null, so it must be invalid 29 | } else if (!standard.type().equals(comparison.type())) { 30 | return false; // If the classes aren't equal it can't fulfill the standard anyway 31 | } 32 | // If the list order is assured, it will be handled with the simple #equals call later in the method 33 | if (!assureListOrder && standard instanceof ListBinaryTag guaranteeList) { 34 | ListBinaryTag comparisonList = ((ListBinaryTag) comparison); 35 | if (guaranteeList.size() == 0) { 36 | return comparisonList.size() == 0; 37 | } 38 | for (BinaryTag nbt : guaranteeList) { 39 | boolean contains = false; 40 | for (BinaryTag compare : comparisonList) { 41 | if (compareNBT(nbt, compare, false)) { 42 | contains = true; 43 | break; 44 | } 45 | } 46 | if (!contains) { 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | 53 | if (standard instanceof CompoundBinaryTag standardCompound) { 54 | CompoundBinaryTag comparisonCompound = ((CompoundBinaryTag) comparison); 55 | for (String key : standardCompound.keySet()) { 56 | if (!compareNBT(comparisonCompound.get(key), comparisonCompound.get(key), assureListOrder)) { 57 | return false; 58 | } 59 | } 60 | return true; 61 | } 62 | 63 | return standard.equals(comparison); 64 | } 65 | 66 | /** 67 | * Merges the two provided compounds, preferring the value of the {@code changes} compound and merging any nested 68 | * NBT compounds like it would for the first-level ones. 69 | * @param base the base compound, to be merged onto 70 | * @param changes the changes to make to the base compound 71 | * @return the merged compound 72 | */ 73 | public static CompoundBinaryTag merge(@NotNull CompoundBinaryTag base, @NotNull CompoundBinaryTag changes) { 74 | CompoundBinaryTag.Builder result = CompoundBinaryTag.builder(); 75 | 76 | result.put(base); 77 | 78 | changes.iterator().forEachRemaining((entry) -> { 79 | BinaryTag value = entry.getValue(); 80 | 81 | if (base.get(entry.getKey()) instanceof CompoundBinaryTag baseCompound 82 | && entry.getValue() instanceof CompoundBinaryTag changeCompound) { 83 | value = NBTUtils.merge(baseCompound, changeCompound); 84 | } 85 | 86 | result.put(entry.getKey(), value); 87 | }); 88 | 89 | return result.build(); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/predicate/DamageSourcePredicate.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.predicate; 2 | 3 | import net.minestom.server.codec.Codec; 4 | import net.minestom.server.coordinate.Point; 5 | import net.minestom.server.entity.damage.DamageType; 6 | import net.minestom.server.instance.Instance; 7 | import net.minestom.server.utils.Unit; 8 | import org.jetbrains.annotations.NotNull; 9 | 10 | // TODO: Incomplete 11 | 12 | @SuppressWarnings("UnstableApiUsage") 13 | public interface DamageSourcePredicate { 14 | 15 | @NotNull Codec CODEC = Codec.UNIT.transform(a -> (instance, pos, type) -> false, a -> Unit.INSTANCE); 16 | 17 | boolean test(@NotNull Instance instance, @NotNull Point pos, @NotNull DamageType type); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/predicate/EntityPredicate.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.predicate; 2 | 3 | import net.minestom.server.codec.Codec; 4 | import net.minestom.server.coordinate.Point; 5 | import net.minestom.server.entity.Entity; 6 | import net.minestom.server.instance.Instance; 7 | import net.minestom.server.utils.Unit; 8 | import org.jetbrains.annotations.NotNull; 9 | import org.jetbrains.annotations.Nullable; 10 | 11 | // TODO: Incomplete 12 | 13 | @SuppressWarnings("UnstableApiUsage") 14 | public interface EntityPredicate { 15 | 16 | @NotNull Codec CODEC = Codec.UNIT.transform(a -> (instance, pos, entity) -> false, a -> Unit.INSTANCE); 17 | 18 | boolean test(@NotNull Instance instance, @Nullable Point pos, @Nullable Entity entity); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/predicate/ItemPredicate.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.predicate; 2 | 3 | import net.minestom.server.codec.Codec; 4 | import net.minestom.server.item.ItemStack; 5 | import net.minestom.server.utils.Unit; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | // TODO: Incomplete 9 | 10 | @SuppressWarnings("UnstableApiUsage") 11 | public interface ItemPredicate { 12 | 13 | @NotNull Codec CODEC = Codec.UNIT.transform(a -> item -> false, a -> Unit.INSTANCE); 14 | 15 | boolean test(@NotNull ItemStack itemStack); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/net/goldenstack/loot/util/predicate/LocationPredicate.java: -------------------------------------------------------------------------------- 1 | package net.goldenstack.loot.util.predicate; 2 | 3 | import net.minestom.server.codec.Codec; 4 | import net.minestom.server.coordinate.Point; 5 | import net.minestom.server.instance.Instance; 6 | import net.minestom.server.utils.Unit; 7 | import org.jetbrains.annotations.NotNull; 8 | 9 | // TODO: Incomplete 10 | 11 | @SuppressWarnings("UnstableApiUsage") 12 | public interface LocationPredicate { 13 | 14 | @NotNull Codec CODEC = Codec.UNIT.transform(a -> (instance, point) -> false, a -> Unit.INSTANCE); 15 | 16 | boolean test(@NotNull Instance instance, @NotNull Point point); 17 | 18 | } 19 | --------------------------------------------------------------------------------