commit bbebb40b7b5dec5ffef5e8bc6b2aacb36887a8f3 Author: Grimmer Date: Wed Apr 8 19:22:57 2026 +0200 v1.0.0 — initial release for Minecraft 1.21.11 Enhances shulker boxes with a flat top-down view, tooltip grid previews, item hints and labels on the lid, and a fill bar. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c5c18da --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +# IntelliJ / IDE +.idea/ +*.iml +*.ipr +*.iws +out/ +.idea_modules/ +/bin/ + +# Compiled class files +*.class + +# Log files +*.log + +# Package files +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# Avoid ignoring Gradle wrapper jar +!gradle-wrapper.jar + +# Gradle +.gradle/ +build/ +**/build/ +gradle-app.setting +.gradletasknamecache + +# Common working directory +run/ + +# JVM crash logs +hs_err_pid* +replay_pid* + +# OS +.DS_Store +Thumbs.db +[Dd]esktop.ini +$RECYCLE.BIN/ + +# Temporary files +*~ +.fuse_hidden* +.nfs* +._* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md new file mode 100644 index 0000000..539ab00 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# Better Shulkers + +A Fabric mod for Minecraft 1.21.11 that enhances shulker boxes with a top-down flat view, tooltip previews, item hints, labels and a fill bar. + +Better Shulkers focuses specifically on shulker boxes and aims to stay lightweight and simple. If you're looking for a more feature-rich mod that covers other containers as well, check out [Peek](https://modrinth.com/mod/peek) by henkelmax, which served as the original inspiration for this project. + +## Features + +- **Flat top-down view** — shulker boxes are displayed from above in GUIs instead of the default angled 3D view, making their lid fully visible +- **Tooltip grid preview** — hover over a shulker box to see its contents laid out in a grid +- **Item hints on the lid** — displays the most relevant item directly on the lid, both in GUIs and in the world +- **Custom labels** — shows the shulker box's custom name on the lid +- **Fill bar** — a durability-style bar indicating how full the shulker box is + + + +## Installation + +1. Install [Fabric Loader](https://fabricmc.net/use/) for Minecraft 1.21.11 +2. Drop `bettershulkers-x.x.x+1.21.11.jar` into your `mods/` folder +3. (Optional) Install [Cloth Config](https://modrinth.com/mod/cloth-config) and [Mod Menu](https://modrinth.com/mod/modmenu) to access the in-game settings screen + +## Configuration + +All options are accessible through Mod Menu (requires Cloth Config). Available settings: + +| Option | Default | Description | +|---|---|---| +| Show Tooltip Preview | When Filled | When to show the grid preview (Always / When Filled / Never) | +| Show Item Hints in GUI | On | Item and label hints on the lid in inventory and other GUIs | +| Show Item Hints in World | On | Item and label hints on the lid of placed shulker boxes | +| Item Display Type | Single Type | Which item to display on the lid (None / Single Type / Bulk / First Item) | +| Show Labels | On | Show the custom name on the lid | +| Hide Hint Background in GUI | Off | Hide the shulker-like background of item hints | +| Item Hints Scale | 100% | Scale of the item hint icon (50–200%) | +| Show Fill Bar | On | Show a fill bar on shulker boxes | + +## License + +[LGPL-3.0](LICENSE) diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..25af20b --- /dev/null +++ b/build.gradle @@ -0,0 +1,75 @@ +plugins { + id 'fabric-loom' version "${fabric_loom_version}" + id 'java' +} + +version = "${mod_version}+${minecraft_version}" +group = mod_group + +base { + archivesName = "bettershulkers" +} + +repositories { + maven { url = 'https://maven.shedaniel.me/' } + maven { url = 'https://maven.terraformersmc.com/releases/' } + maven { + url = 'https://maven.parchmentmc.org' + content { includeGroupByRegex("org\\.parchmentmc\\..*") } + } +} + +loom { + accessWidenerPath = file("src/main/resources/${mod_id}.accesswidener") +} + +dependencies { + minecraft "com.mojang:minecraft:${minecraft_version}" + mappings loom.layered() { + officialMojangMappings() + parchment("org.parchmentmc.data:${parchment_mappings}@zip") + } + modImplementation "net.fabricmc:fabric-loader:${fabric_loader_version}" + + Set apiModules = [ + "fabric-api-base", + "fabric-resource-loader-v1", + "fabric-networking-api-v1" + ] + + apiModules.forEach { + modImplementation(fabricApi.module(it, fabric_api_version)) + } + + modCompileOnlyApi("me.shedaniel.cloth:cloth-config-fabric:${cloth_config_version}") { + exclude(group: "net.fabricmc.fabric-api") + } + modCompileOnly "com.terraformersmc:modmenu:${modmenu_version}" +} + +processResources { + filesMatching('fabric.mod.json') { + expand 'mod_version': mod_version, + 'minecraft_version': minecraft_version, + 'fabric_loader_version': fabric_loader_version, + 'cloth_config_version': cloth_config_version, + 'modmenu_version': modmenu_version + } +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } + // withSourcesJar() +} + +tasks.withType(JavaCompile).configureEach { + it.options.release = 21 +} + +jar { + from("LICENSE") { + rename { "${it}_${base.archivesName.get()}" } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..055af92 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +org.gradle.jvmargs=-Xmx4G +org.gradle.daemon=false + +java_version=21 + +minecraft_version=1.21.11 +fabric_loader_version=0.18.1 +fabric_api_version=0.139.4+1.21.11 +parchment_mappings=parchment-1.21.10:2025.10.12 +fabric_loom_version=1.14-SNAPSHOT + +cloth_config_version=20.0.149 +modmenu_version=17.0.0-alpha.1 + +mod_version=1.0.0 +mod_id=better_shulkers +mod_name=Better Shulkers +mod_group=sh.grimmer.bettershulkers diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..23449a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..a9f4254 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { url = 'https://maven.fabricmc.net/' } + gradlePluginPortal() + mavenCentral() + } +} + +rootProject.name = 'better-shulkers' diff --git a/src/main/java/sh/grimmer/bettershulkers/BetterShulkers.java b/src/main/java/sh/grimmer/bettershulkers/BetterShulkers.java new file mode 100644 index 0000000..a968718 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/BetterShulkers.java @@ -0,0 +1,57 @@ +package sh.grimmer.bettershulkers; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.loader.api.FabricLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import sh.grimmer.bettershulkers.config.BetterShulkersConfig; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Path; + +public class BetterShulkers implements ModInitializer { + + public static final String MOD_ID = "better_shulkers"; + public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static BetterShulkersConfig CONFIG; + + @Override + public void onInitialize() { + CONFIG = loadConfig(); + } + + private static BetterShulkersConfig loadConfig() { + Path configPath = getConfigPath(); + if (Files.exists(configPath)) { + try (Reader reader = Files.newBufferedReader(configPath)) { + BetterShulkersConfig loaded = GSON.fromJson(reader, BetterShulkersConfig.class); + if (loaded != null) { + loaded.save(); + return loaded; + } + } catch (Exception e) { + LOGGER.error("Failed to load config, using defaults", e); + } + } + BetterShulkersConfig config = new BetterShulkersConfig(); + config.save(); + return config; + } + + public static Path getConfigPath() { + return FabricLoader.getInstance().getConfigDir().resolve(MOD_ID + ".json"); + } + + public static void saveConfig() { + if (CONFIG != null) { + CONFIG.save(); + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/config/BetterShulkersConfig.java b/src/main/java/sh/grimmer/bettershulkers/config/BetterShulkersConfig.java new file mode 100644 index 0000000..d5c7a9d --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/config/BetterShulkersConfig.java @@ -0,0 +1,42 @@ +package sh.grimmer.bettershulkers.config; + +import com.google.gson.annotations.SerializedName; +import sh.grimmer.bettershulkers.BetterShulkers; + +import java.io.Writer; +import java.nio.file.Files; + +public class BetterShulkersConfig { + + @SerializedName("tooltip_preview") + public TooltipPreviewMode tooltipPreview = TooltipPreviewMode.WHEN_FILLED; + + @SerializedName("show_item_hint") + public boolean showItemHint = true; + + @SerializedName("show_block_hint") + public boolean showBlockHint = true; + + @SerializedName("show_labels") + public boolean showLabels = true; + + @SerializedName("item_display_type") + public ShulkerItemDisplayType itemDisplayType = ShulkerItemDisplayType.SINGLE_TYPE; + + @SerializedName("hide_model_behind_hint") + public boolean hideModelBehindHint = false; + + @SerializedName("hint_item_scale") + public int hintItemScale = 100; + + @SerializedName("show_fill_bar") + public boolean showFillBar = true; + + public void save() { + try (Writer writer = Files.newBufferedWriter(BetterShulkers.getConfigPath())) { + BetterShulkers.GSON.toJson(this, writer); + } catch (Exception e) { + BetterShulkers.LOGGER.error("Failed to save config", e); + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/config/ShulkerItemDisplayType.java b/src/main/java/sh/grimmer/bettershulkers/config/ShulkerItemDisplayType.java new file mode 100644 index 0000000..8dd2fa6 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/config/ShulkerItemDisplayType.java @@ -0,0 +1,32 @@ +package sh.grimmer.bettershulkers.config; + +import com.google.gson.annotations.SerializedName; +import net.minecraft.network.chat.Component; + +public enum ShulkerItemDisplayType { + @SerializedName("none") + NONE("none"), + @SerializedName("single_type") + SINGLE_TYPE("single_type"), + @SerializedName("bulk") + BULK("bulk"), + @SerializedName("first_item") + FIRST_ITEM("first_item"); + + private final Component name; + private final Component description; + + ShulkerItemDisplayType(String id) { + String key = "cloth_config.better_shulkers.item_display_type.%s".formatted(id); + this.name = Component.translatable(key); + this.description = Component.translatable("%s.description".formatted(key)); + } + + public Component getDisplayName() { + return name; + } + + public Component getDescription() { + return description; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/config/TooltipPreviewMode.java b/src/main/java/sh/grimmer/bettershulkers/config/TooltipPreviewMode.java new file mode 100644 index 0000000..63aac35 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/config/TooltipPreviewMode.java @@ -0,0 +1,30 @@ +package sh.grimmer.bettershulkers.config; + +import com.google.gson.annotations.SerializedName; +import net.minecraft.network.chat.Component; + +public enum TooltipPreviewMode { + @SerializedName("always") + ALWAYS("always"), + @SerializedName("when_filled") + WHEN_FILLED("when_filled"), + @SerializedName("never") + NEVER("never"); + + private final Component name; + private final Component description; + + TooltipPreviewMode(String id) { + String key = "cloth_config.better_shulkers.tooltip_preview.%s".formatted(id); + this.name = Component.translatable(key); + this.description = Component.translatable("%s.description".formatted(key)); + } + + public Component getDisplayName() { + return name; + } + + public Component getDescription() { + return description; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/data/ShulkerBoxTracker.java b/src/main/java/sh/grimmer/bettershulkers/data/ShulkerBoxTracker.java new file mode 100644 index 0000000..b9aa1ad --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/data/ShulkerBoxTracker.java @@ -0,0 +1,29 @@ +package sh.grimmer.bettershulkers.data; + +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; + +import org.jetbrains.annotations.Nullable; + +public final class ShulkerBoxTracker { + + @Nullable + private static ShulkerBoxBlockEntity lastOpened; + + private ShulkerBoxTracker() { + } + + @Nullable + public static ShulkerBoxBlockEntity getLastOpened() { + return lastOpened; + } + + public static void setLastOpened(@Nullable ShulkerBoxBlockEntity blockEntity) { + lastOpened = blockEntity; + } + + public static ShulkerBoxBlockEntity consumeLastOpened() { + ShulkerBoxBlockEntity be = lastOpened; + lastOpened = null; + return be; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/integration/ClothConfigScreen.java b/src/main/java/sh/grimmer/bettershulkers/integration/ClothConfigScreen.java new file mode 100644 index 0000000..d580cb6 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/integration/ClothConfigScreen.java @@ -0,0 +1,115 @@ +package sh.grimmer.bettershulkers.integration; + +import me.shedaniel.clothconfig2.api.ConfigBuilder; +import me.shedaniel.clothconfig2.api.ConfigCategory; +import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; +import net.minecraft.ChatFormatting; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.config.BetterShulkersConfig; +import sh.grimmer.bettershulkers.config.ShulkerItemDisplayType; +import sh.grimmer.bettershulkers.config.TooltipPreviewMode; + +import java.util.Optional; + +public class ClothConfigScreen { + + public static Screen create(Screen parent) { + BetterShulkersConfig cfg = BetterShulkers.CONFIG; + + ConfigBuilder builder = ConfigBuilder.create() + .setParentScreen(parent) + .setTitle(Component.translatable("cloth_config.better_shulkers.settings")) + .setSavingRunnable(BetterShulkers::saveConfig); + + ConfigEntryBuilder eb = builder.entryBuilder(); + + ConfigCategory tooltips = builder.getOrCreateCategory( + Component.translatable("cloth_config.better_shulkers.category.tooltips")); + + tooltips.addEntry(eb + .startEnumSelector(t("tooltip_preview"), TooltipPreviewMode.class, cfg.tooltipPreview) + .setTooltip(d("tooltip_preview")) + .setDefaultValue(TooltipPreviewMode.WHEN_FILLED) + .setSaveConsumer(v -> cfg.tooltipPreview = v) + .setEnumNameProvider(v -> ((TooltipPreviewMode) v).getDisplayName()) + .setTooltipSupplier(v -> Optional.of(new Component[]{ + d("tooltip_preview"), + Component.translatable("cloth_config.better_shulkers.tooltip_preview.selected", + v.getDisplayName().copy().withStyle(ChatFormatting.GREEN), + v.getDescription().copy().withStyle(ChatFormatting.GREEN)) + })) + .build()); + + ConfigCategory hints = builder.getOrCreateCategory( + Component.translatable("cloth_config.better_shulkers.category.hints")); + + hints.addEntry(eb + .startBooleanToggle(t("show_item_hint"), cfg.showItemHint) + .setTooltip(d("show_item_hint")) + .setDefaultValue(true) + .setSaveConsumer(v -> cfg.showItemHint = v) + .build()); + + hints.addEntry(eb + .startBooleanToggle(t("show_block_hint"), cfg.showBlockHint) + .setTooltip(d("show_block_hint")) + .setDefaultValue(true) + .setSaveConsumer(v -> cfg.showBlockHint = v) + .build()); + + hints.addEntry(eb + .startEnumSelector(t("item_display_type"), ShulkerItemDisplayType.class, cfg.itemDisplayType) + .setTooltip(d("item_display_type")) + .setDefaultValue(ShulkerItemDisplayType.SINGLE_TYPE) + .setSaveConsumer(v -> cfg.itemDisplayType = v) + .setEnumNameProvider(v -> ((ShulkerItemDisplayType) v).getDisplayName()) + .setTooltipSupplier(v -> Optional.of(new Component[]{ + d("item_display_type"), + Component.translatable("cloth_config.better_shulkers.item_display_type.selected", + v.getDisplayName().copy().withStyle(ChatFormatting.GREEN), + v.getDescription().copy().withStyle(ChatFormatting.GREEN)) + })) + .build()); + + hints.addEntry(eb + .startBooleanToggle(t("show_labels"), cfg.showLabels) + .setTooltip(d("show_labels")) + .setDefaultValue(true) + .setSaveConsumer(v -> cfg.showLabels = v) + .build()); + + hints.addEntry(eb + .startBooleanToggle(t("hide_model_behind_hint"), cfg.hideModelBehindHint) + .setTooltip(d("hide_model_behind_hint")) + .setDefaultValue(false) + .setSaveConsumer(v -> cfg.hideModelBehindHint = v) + .build()); + + hints.addEntry(eb + .startIntField(t("hint_item_scale"), cfg.hintItemScale) + .setTooltip(d("hint_item_scale")) + .setMin(50).setMax(200) + .setDefaultValue(100) + .setSaveConsumer(v -> cfg.hintItemScale = v) + .build()); + + hints.addEntry(eb + .startBooleanToggle(t("show_fill_bar"), cfg.showFillBar) + .setTooltip(d("show_fill_bar")) + .setDefaultValue(true) + .setSaveConsumer(v -> cfg.showFillBar = v) + .build()); + + return builder.build(); + } + + private static Component t(String key) { + return Component.translatable("cloth_config.better_shulkers." + key); + } + + private static Component d(String key) { + return Component.translatable("cloth_config.better_shulkers." + key + ".description"); + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/integration/ModMenuIntegration.java b/src/main/java/sh/grimmer/bettershulkers/integration/ModMenuIntegration.java new file mode 100644 index 0000000..d3611cc --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/integration/ModMenuIntegration.java @@ -0,0 +1,30 @@ +package sh.grimmer.bettershulkers.integration; + +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; +import net.fabricmc.loader.api.FabricLoader; +import sh.grimmer.bettershulkers.BetterShulkers; + +public class ModMenuIntegration implements ModMenuApi { + + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + if (isClothConfigAvailable()) { + return ClothConfigScreen::create; + } + return parent -> null; + } + + private static boolean isClothConfigAvailable() { + if (FabricLoader.getInstance().isModLoaded("cloth-config2")) { + try { + Class.forName("me.shedaniel.clothconfig2.api.ConfigBuilder"); + BetterShulkers.LOGGER.info("Cloth Config detected, config screen enabled"); + return true; + } catch (Exception e) { + BetterShulkers.LOGGER.warn("Failed to load Cloth Config", e); + } + } + return false; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/interfaces/BsShulkerBoxRenderState.java b/src/main/java/sh/grimmer/bettershulkers/interfaces/BsShulkerBoxRenderState.java new file mode 100644 index 0000000..716371f --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/interfaces/BsShulkerBoxRenderState.java @@ -0,0 +1,20 @@ +package sh.grimmer.bettershulkers.interfaces; + +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.util.FormattedCharSequence; + +import org.jetbrains.annotations.Nullable; + +public interface BsShulkerBoxRenderState { + + @Nullable + FormattedCharSequence betterShulkers$getLabel(); + + void betterShulkers$setLabel(@Nullable FormattedCharSequence label); + + @Nullable + ItemStackRenderState betterShulkers$getDisplayItem(); + + void betterShulkers$setDisplayItem(@Nullable ItemStackRenderState displayItem); + +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/BlockItemMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/BlockItemMixin.java new file mode 100644 index 0000000..aa17c5b --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/BlockItemMixin.java @@ -0,0 +1,106 @@ +package sh.grimmer.bettershulkers.mixin; + +import net.minecraft.core.NonNullList; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemContainerContents; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.ShulkerBoxBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.core.component.DataComponents; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.config.TooltipPreviewMode; +import sh.grimmer.bettershulkers.tooltip.ContainerTooltip; +import sh.grimmer.bettershulkers.util.ShulkerBoxHelper; + +import java.util.Optional; + +@Mixin(BlockItem.class) +public abstract class BlockItemMixin extends Item { + + @Shadow + @Final + private Block block; + + public BlockItemMixin(Properties properties) { + super(properties); + } + + @Override + public Optional getTooltipImage(ItemStack stack) { + if (block instanceof ShulkerBoxBlock && BetterShulkers.CONFIG.tooltipPreview != TooltipPreviewMode.NEVER) { + ItemContainerContents contents = stack.getOrDefault(DataComponents.CONTAINER, ItemContainerContents.EMPTY); + if (BetterShulkers.CONFIG.tooltipPreview == TooltipPreviewMode.WHEN_FILLED && contents.stream().allMatch(ItemStack::isEmpty)) { + return super.getTooltipImage(stack); + } + NonNullList items = NonNullList.withSize(27, ItemStack.EMPTY); + contents.copyInto(items); + return Optional.of(new ContainerTooltip(9, 3, items)); + } + return super.getTooltipImage(stack); + } + + @Override + public boolean isBarVisible(ItemStack stack) { + if (BetterShulkers.CONFIG.showFillBar && block instanceof ShulkerBoxBlock) { + NonNullList items = ShulkerBoxHelper.getItems(stack); + return items.stream().anyMatch(s -> !s.isEmpty()); + } + return super.isBarVisible(stack); + } + + @Override + public int getBarWidth(ItemStack stack) { + if (BetterShulkers.CONFIG.showFillBar && block instanceof ShulkerBoxBlock) { + NonNullList items = ShulkerBoxHelper.getItems(stack); + long occupied = items.stream().filter(s -> !s.isEmpty()).count(); + return Math.round((float) occupied / (float) items.size() * 13.0F); + } + return super.getBarWidth(stack); + } + + @Override + public int getBarColor(ItemStack stack) { + if (BetterShulkers.CONFIG.showFillBar && block instanceof ShulkerBoxBlock) { + NonNullList items = ShulkerBoxHelper.getItems(stack); + long occupied = items.stream().filter(s -> !s.isEmpty()).count(); + float fraction = (float) occupied / (float) items.size(); + return Mth.hsvToRgb((1.0F - fraction) / 3.0F, 1.0F, 1.0F); + } + return super.getBarColor(stack); + } + + @Inject(method = "place", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;gameEvent(Lnet/minecraft/core/Holder;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/gameevent/GameEvent$Context;)V", shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD) + private void onPlace(BlockPlaceContext ctx, CallbackInfoReturnable cir, BlockPlaceContext actualCtx) { + if (!BetterShulkers.CONFIG.showBlockHint) { + return; + } + Level level = actualCtx.getLevel(); + if (!level.isClientSide()) { + return; + } + BlockEntity be = level.getBlockEntity(actualCtx.getClickedPos()); + if (!(be instanceof ShulkerBoxBlockEntity shulkerBe)) { + return; + } + ItemStack item = actualCtx.getItemInHand(); + if (!ShulkerBoxHelper.isShulkerBox(item)) { + return; + } + shulkerBe.applyComponentsFromItemStack(item); + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ClientTooltipComponentMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ClientTooltipComponentMixin.java new file mode 100644 index 0000000..d9009ed --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ClientTooltipComponentMixin.java @@ -0,0 +1,21 @@ +package sh.grimmer.bettershulkers.mixin; + +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import sh.grimmer.bettershulkers.tooltip.ContainerTooltip; +import sh.grimmer.bettershulkers.tooltip.ContainerTooltipRenderer; + +@Mixin(ClientTooltipComponent.class) +public interface ClientTooltipComponentMixin { + + @Inject(method = "create(Lnet/minecraft/world/inventory/tooltip/TooltipComponent;)Lnet/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent;", at = @At("HEAD"), cancellable = true) + private static void onCreate(TooltipComponent component, CallbackInfoReturnable cir) { + if (component instanceof ContainerTooltip tooltip) { + cir.setReturnValue(new ContainerTooltipRenderer(tooltip)); + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ItemStackMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ItemStackMixin.java new file mode 100644 index 0000000..92192c2 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ItemStackMixin.java @@ -0,0 +1,46 @@ +package sh.grimmer.bettershulkers.mixin; + +import net.minecraft.core.component.DataComponentHolder; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.TooltipDisplay; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.config.TooltipPreviewMode; + +import java.util.function.Consumer; + +@Mixin(ItemStack.class) +public abstract class ItemStackMixin implements DataComponentHolder { + + @Shadow + public abstract Item getItem(); + + @Shadow + public abstract void addToTooltip(DataComponentType dataComponentType, Item.TooltipContext tooltipContext, TooltipDisplay tooltipDisplay, Consumer consumer, TooltipFlag tooltipFlag); + + @Inject(method = "addToTooltip", at = @At(value = "HEAD"), cancellable = true) + public void onAddToTooltip(DataComponentType type, Item.TooltipContext ctx, TooltipDisplay display, Consumer consumer, TooltipFlag flag, CallbackInfo ci) { + if (type != DataComponents.CONTAINER) { + return; + } + if (!(getItem() instanceof BlockItem blockItem)) { + return; + } + if (!(blockItem.getBlock() instanceof net.minecraft.world.level.block.ShulkerBoxBlock)) { + return; + } + if (BetterShulkers.CONFIG.tooltipPreview != TooltipPreviewMode.NEVER) { + ci.cancel(); + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxBlockMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxBlockMixin.java new file mode 100644 index 0000000..4da0c04 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxBlockMixin.java @@ -0,0 +1,35 @@ +package sh.grimmer.bettershulkers.mixin; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.ShulkerBoxBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.data.ShulkerBoxTracker; + +@Mixin(ShulkerBoxBlock.class) +public class ShulkerBoxBlockMixin { + + @Inject(method = "useWithoutItem", at = @At("HEAD")) + private void onUse(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult, CallbackInfoReturnable cir) { + if (!BetterShulkers.CONFIG.showBlockHint) { + return; + } + if (!level.isClientSide()) { + return; + } + BlockEntity be = level.getBlockEntity(pos); + if (be instanceof ShulkerBoxBlockEntity shulkerBe) { + ShulkerBoxTracker.setLastOpened(shulkerBe); + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxMenuMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxMenuMixin.java new file mode 100644 index 0000000..0531278 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxMenuMixin.java @@ -0,0 +1,33 @@ +package sh.grimmer.bettershulkers.mixin; + +import com.llamalad7.mixinextras.sugar.Local; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.inventory.ShulkerBoxMenu; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.data.ShulkerBoxTracker; + +@Mixin(ShulkerBoxMenu.class) +public class ShulkerBoxMenuMixin { + + @ModifyVariable(method = "(ILnet/minecraft/world/entity/player/Inventory;Lnet/minecraft/world/Container;)V", at = @At("HEAD"), ordinal = 0, argsOnly = true) + private static Container onInit(Container container, @Local(argsOnly = true) int containerId) { + if (!BetterShulkers.CONFIG.showBlockHint) { + return container; + } + if (!(container instanceof SimpleContainer)) { + return container; + } + ShulkerBoxBlockEntity lastOpened = ShulkerBoxTracker.getLastOpened(); + if (lastOpened == null) { + return container; + } + lastOpened.clearContent(); + ShulkerBoxTracker.setLastOpened(null); + return lastOpened; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxRenderStateMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxRenderStateMixin.java new file mode 100644 index 0000000..b1c209b --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxRenderStateMixin.java @@ -0,0 +1,44 @@ +package sh.grimmer.bettershulkers.mixin; + +import net.minecraft.client.renderer.blockentity.state.ShulkerBoxRenderState; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.util.FormattedCharSequence; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import sh.grimmer.bettershulkers.interfaces.BsShulkerBoxRenderState; + +import org.jetbrains.annotations.Nullable; + +@Mixin(ShulkerBoxRenderState.class) +public class ShulkerBoxRenderStateMixin implements BsShulkerBoxRenderState { + + @Unique + @Nullable + private FormattedCharSequence betterShulkers$label; + + @Unique + @Nullable + private ItemStackRenderState betterShulkers$displayItem; + + @Nullable + @Override + public FormattedCharSequence betterShulkers$getLabel() { + return betterShulkers$label; + } + + @Override + public void betterShulkers$setLabel(@Nullable FormattedCharSequence label) { + this.betterShulkers$label = label; + } + + @Nullable + @Override + public ItemStackRenderState betterShulkers$getDisplayItem() { + return betterShulkers$displayItem; + } + + @Override + public void betterShulkers$setDisplayItem(@Nullable ItemStackRenderState displayItem) { + this.betterShulkers$displayItem = displayItem; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxRendererMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxRendererMixin.java new file mode 100644 index 0000000..74e6c7f --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxRendererMixin.java @@ -0,0 +1,51 @@ +package sh.grimmer.bettershulkers.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.ShulkerBoxRenderer; +import net.minecraft.client.renderer.blockentity.state.ShulkerBoxRenderState; +import net.minecraft.client.renderer.feature.ModelFeatureRenderer; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.client.renderer.state.CameraRenderState; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.world.phys.Vec3; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.interfaces.BsShulkerBoxRenderState; +import sh.grimmer.bettershulkers.render.ShulkerHintData; +import sh.grimmer.bettershulkers.render.ShulkerHintRenderer; +import sh.grimmer.bettershulkers.util.ItemRenderHelper; + +@Mixin(ShulkerBoxRenderer.class) +public abstract class ShulkerBoxRendererMixin implements BlockEntityRenderer { + + @Inject(method = "extractRenderState(Lnet/minecraft/world/level/block/entity/ShulkerBoxBlockEntity;Lnet/minecraft/client/renderer/blockentity/state/ShulkerBoxRenderState;FLnet/minecraft/world/phys/Vec3;Lnet/minecraft/client/renderer/feature/ModelFeatureRenderer$CrumblingOverlay;)V", at = @At("HEAD")) + private void onExtractRenderState(ShulkerBoxBlockEntity be, ShulkerBoxRenderState state, float partialTick, Vec3 vec, ModelFeatureRenderer.CrumblingOverlay overlay, CallbackInfo ci) { + if (!(state instanceof BsShulkerBoxRenderState bsState)) { + throw new IllegalStateException("ShulkerBoxRenderState does not implement BsShulkerBoxRenderState"); + } + + if (!BetterShulkers.CONFIG.showBlockHint) { + bsState.betterShulkers$setLabel(null); + bsState.betterShulkers$setDisplayItem(null); + return; + } + + ShulkerHintData hintData = ShulkerHintData.fromShulkerBox(be.getItems(), be.getCustomName()); + bsState.betterShulkers$setLabel(hintData.getLabelFormatted()); + + ItemStack displayItem = ShulkerHintRenderer.createMarkedStack(hintData.getDisplayItem()); + ItemStackRenderState renderState = ItemRenderHelper.createRenderState(be.getLevel(), be.getBlockPos(), displayItem); + bsState.betterShulkers$setDisplayItem(renderState); + } + + @Inject(method = "submit(Lnet/minecraft/client/renderer/blockentity/state/ShulkerBoxRenderState;Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/SubmitNodeCollector;Lnet/minecraft/client/renderer/state/CameraRenderState;)V", at = @At("RETURN")) + private void onSubmit(ShulkerBoxRenderState state, PoseStack poseStack, SubmitNodeCollector collector, CameraRenderState camera, CallbackInfo ci) { + ShulkerHintRenderer.submitBlockHint(state, poseStack, collector, camera); + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxScreenMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxScreenMixin.java new file mode 100644 index 0000000..3143208 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxScreenMixin.java @@ -0,0 +1,49 @@ +package sh.grimmer.bettershulkers.mixin; + +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.gui.screens.inventory.ShulkerBoxScreen; +import net.minecraft.core.component.DataComponentMap; +import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.ShulkerBoxMenu; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import sh.grimmer.bettershulkers.BetterShulkers; + +@Mixin(ShulkerBoxScreen.class) +public abstract class ShulkerBoxScreenMixin extends AbstractContainerScreen { + + public ShulkerBoxScreenMixin(ShulkerBoxMenu menu, Inventory inventory, Component title) { + super(menu, inventory, title); + } + + @Inject(method = "", at = @At("RETURN")) + private void onInit(ShulkerBoxMenu menu, Inventory inventory, Component component, CallbackInfo ci) { + if (!BetterShulkers.CONFIG.showBlockHint) { + return; + } + + if (!(menu.container instanceof ShulkerBoxBlockEntity shulkerBe)) { + return; + } + + if (component.getContents() instanceof TranslatableContents translatable) { + if (translatable.getKey().equals("container.shulkerBox")) { + return; + } + } + + DataComponentMap components = shulkerBe.collectComponents(); + DataComponentMap updated = DataComponentMap.builder() + .addAll(components) + .set(DataComponents.CUSTOM_NAME, component) + .build(); + shulkerBe.applyComponents(updated, DataComponentPatch.EMPTY); + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxSpecialRendererMixin.java b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxSpecialRendererMixin.java new file mode 100644 index 0000000..7d26722 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/mixin/ShulkerBoxSpecialRendererMixin.java @@ -0,0 +1,48 @@ +package sh.grimmer.bettershulkers.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.special.ShulkerBoxSpecialRenderer; +import net.minecraft.client.renderer.special.SpecialModelRenderer; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.render.ShulkerHintData; +import sh.grimmer.bettershulkers.render.ShulkerHintRenderer; +import sh.grimmer.bettershulkers.util.ShulkerBoxHelper; + +import org.jetbrains.annotations.Nullable; + +@Mixin(ShulkerBoxSpecialRenderer.class) +public abstract class ShulkerBoxSpecialRendererMixin implements SpecialModelRenderer { + + @Shadow + public abstract void submit(ItemDisplayContext ctx, PoseStack poseStack, SubmitNodeCollector collector, int light, int overlay, boolean bl, int k); + + @Nullable + @Override + public ShulkerHintData extractArgument(ItemStack stack) { + return ShulkerHintData.fromShulkerBox(ShulkerBoxHelper.getItems(stack), ShulkerBoxHelper.getCustomName(stack)); + } + + @Override + public void submit(@Nullable ShulkerHintData data, ItemDisplayContext ctx, PoseStack poseStack, SubmitNodeCollector collector, int light, int overlay, boolean bl, int k) { + boolean isGui = ctx == ItemDisplayContext.GUI; + + boolean shouldHideModel = BetterShulkers.CONFIG.hideModelBehindHint + && isGui + && data != null + && data.getDisplayItem() != null; + + if (!shouldHideModel) { + submit(ctx, poseStack, collector, light, overlay, bl, k); + } + + if (BetterShulkers.CONFIG.showItemHint && data != null) { + float scale = isGui ? BetterShulkers.CONFIG.hintItemScale / 100F : 1F; + ShulkerHintRenderer.submitItemHint(data, poseStack, collector, light, scale); + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/render/ShulkerHintData.java b/src/main/java/sh/grimmer/bettershulkers/render/ShulkerHintData.java new file mode 100644 index 0000000..f3050ac --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/render/ShulkerHintData.java @@ -0,0 +1,68 @@ +package sh.grimmer.bettershulkers.render; + +import net.minecraft.core.NonNullList; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.item.ItemStack; +import sh.grimmer.bettershulkers.BetterShulkers; +import sh.grimmer.bettershulkers.util.ShulkerBoxHelper; + +import org.jetbrains.annotations.Nullable; + +public class ShulkerHintData { + + @Nullable + private Component label; + @Nullable + private ItemStack displayItem; + + public ShulkerHintData(@Nullable Component label, @Nullable ItemStack displayItem) { + this.label = label; + this.displayItem = displayItem; + } + + public ShulkerHintData() { + } + + @Nullable + public Component getLabel() { + return label; + } + + @Nullable + public FormattedCharSequence getLabelFormatted() { + return label != null ? label.getVisualOrderText() : null; + } + + @Nullable + public ItemStack getDisplayItem() { + return displayItem; + } + + public void setLabel(@Nullable Component label) { + this.label = label; + } + + public void setDisplayItem(@Nullable ItemStack displayItem) { + this.displayItem = displayItem; + } + + public static ShulkerHintData fromShulkerBox(NonNullList contents, @Nullable Component name) { + ShulkerHintData data = new ShulkerHintData(); + data.setDisplayItem(determineDisplayItem(contents)); + if (BetterShulkers.CONFIG.showLabels) { + data.setLabel(name); + } + return data; + } + + @Nullable + private static ItemStack determineDisplayItem(NonNullList contents) { + return switch (BetterShulkers.CONFIG.itemDisplayType) { + case NONE -> null; + case SINGLE_TYPE -> ShulkerBoxHelper.getSingleTypeItem(contents); + case BULK -> ShulkerBoxHelper.getBulkItem(contents); + case FIRST_ITEM -> contents.stream().filter(s -> !s.isEmpty()).findFirst().orElse(null); + }; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/render/ShulkerHintRenderer.java b/src/main/java/sh/grimmer/bettershulkers/render/ShulkerHintRenderer.java new file mode 100644 index 0000000..5e03c01 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/render/ShulkerHintRenderer.java @@ -0,0 +1,108 @@ +package sh.grimmer.bettershulkers.render; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Axis; +import com.mojang.serialization.Codec; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.blockentity.state.ShulkerBoxRenderState; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.client.renderer.state.CameraRenderState; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.core.Direction; +import net.minecraft.core.component.DataComponentPatch; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.item.ItemStack; +import sh.grimmer.bettershulkers.interfaces.BsShulkerBoxRenderState; +import sh.grimmer.bettershulkers.util.ItemRenderHelper; + +import org.jetbrains.annotations.Nullable; + +public final class ShulkerHintRenderer { + + private static final DataComponentType SHULKER_RENDER_MARKER = DataComponentType.builder().persistent(Codec.BOOL).build(); + + private ShulkerHintRenderer() { + } + + public static void submitBlockHint(ShulkerBoxRenderState renderState, PoseStack poseStack, SubmitNodeCollector collector, CameraRenderState camera) { + if (!(renderState instanceof BsShulkerBoxRenderState bsState)) { + throw new IllegalStateException("ShulkerBoxRenderState does not implement BsShulkerBoxRenderState"); + } + submitHint( + renderState.direction, renderState.progress, + bsState.betterShulkers$getDisplayItem(), bsState.betterShulkers$getLabel(), + renderState.lightCoords, poseStack, collector, 1F + ); + } + + public static void submitItemHint(ShulkerHintData hintData, PoseStack poseStack, SubmitNodeCollector collector, int light, float itemScale) { + ItemStackRenderState renderState = ItemRenderHelper.createRenderState( + Minecraft.getInstance().level, null, + createMarkedStack(hintData.getDisplayItem()) + ); + submitHint(Direction.UP, 0F, renderState, hintData.getLabelFormatted(), light, poseStack, collector, itemScale); + } + + private static void submitHint( + Direction direction, float progress, + @Nullable ItemStackRenderState displayItem, @Nullable FormattedCharSequence label, + int lightCoords, PoseStack poseStack, SubmitNodeCollector collector, float itemScale + ) { + Minecraft mc = Minecraft.getInstance(); + + poseStack.pushPose(); + poseStack.translate(0.5D, 0.5D, 0.5D); + poseStack.mulPose(direction.getRotation()); + poseStack.translate(0D, 0.5D, 0D); + poseStack.translate(0F, progress * 0.5F, 0F); + poseStack.rotateAround(Axis.YP.rotationDegrees(-270F * progress), 0F, 1F, 0F); + poseStack.rotateAround(Axis.XP.rotationDegrees(-90F), 1F, 0F, 0F); + + if (displayItem != null) { + poseStack.pushPose(); + poseStack.rotateAround(Axis.YP.rotationDegrees(180F), 0F, 1F, 0F); + if (label != null) { + poseStack.translate(0F, 2F / 16F, 0F); + poseStack.scale(12F / 16F, 12F / 16F, 12F / 16F); + } + if (itemScale != 1F) { + poseStack.scale(itemScale, itemScale, itemScale); + } + displayItem.submit(poseStack, collector, lightCoords, OverlayTexture.NO_OVERLAY, 0); + poseStack.popPose(); + } + + if (label != null) { + poseStack.pushPose(); + if (displayItem != null) { + poseStack.translate(0F, -6F / 16F, 0F); + } + int width = mc.font.width(label); + float textScale = Math.min(0.8F / width, 0.02F); + poseStack.scale(textScale, textScale, textScale); + poseStack.translate(0F, mc.font.lineHeight / 2F, 0F); + poseStack.rotateAround(Axis.XP.rotationDegrees(180F), 1F, 0F, 0F); + collector.submitText(poseStack, -width / 2F, 0F, label, false, Font.DisplayMode.POLYGON_OFFSET, lightCoords, 0xFFFFFFFF, 0x00000000, 0xFF000000); + poseStack.popPose(); + } + + poseStack.popPose(); + } + + public static boolean isMarkedStack(ItemStack stack) { + return stack.getComponents().getOrDefault(SHULKER_RENDER_MARKER, false); + } + + @Nullable + public static ItemStack createMarkedStack(@Nullable ItemStack source) { + if (source == null) { + return null; + } + ItemStack copy = source.copy(); + copy.applyComponents(DataComponentPatch.builder().set(SHULKER_RENDER_MARKER, true).build()); + return copy; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/tooltip/ContainerTooltip.java b/src/main/java/sh/grimmer/bettershulkers/tooltip/ContainerTooltip.java new file mode 100644 index 0000000..8b809fb --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/tooltip/ContainerTooltip.java @@ -0,0 +1,30 @@ +package sh.grimmer.bettershulkers.tooltip; + +import net.minecraft.core.NonNullList; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.ItemStack; + +public class ContainerTooltip implements TooltipComponent { + + private final int width; + private final int height; + private final NonNullList items; + + public ContainerTooltip(int width, int height, NonNullList items) { + this.width = width; + this.height = height; + this.items = items; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public NonNullList getItems() { + return items; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/tooltip/ContainerTooltipRenderer.java b/src/main/java/sh/grimmer/bettershulkers/tooltip/ContainerTooltipRenderer.java new file mode 100644 index 0000000..ebee0f0 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/tooltip/ContainerTooltipRenderer.java @@ -0,0 +1,99 @@ +package sh.grimmer.bettershulkers.tooltip; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.core.NonNullList; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.ItemStack; +import sh.grimmer.bettershulkers.BetterShulkers; + +public class ContainerTooltipRenderer implements ClientTooltipComponent { + + public static final Identifier TEXTURE = Identifier.fromNamespaceAndPath(BetterShulkers.MOD_ID, "textures/gui/container/slot.png"); + + private static final int MARGIN_Y = 4; + private static final int BORDER = 1; + private static final int TEX_SIZE = 32; + private static final int SLOT_W = 18; + private static final int SLOT_H = 18; + + private final int gridWidth; + private final int gridHeight; + private final NonNullList items; + + public ContainerTooltipRenderer(ContainerTooltip tooltip) { + this.gridWidth = tooltip.getWidth(); + this.gridHeight = tooltip.getHeight(); + this.items = tooltip.getItems(); + } + + @Override + public int getHeight(Font font) { + return gridHeight * SLOT_H + 2 * BORDER + MARGIN_Y; + } + + @Override + public int getWidth(Font font) { + return gridWidth * SLOT_W + 2; + } + + @Override + public void renderImage(Font font, int tooltipX, int tooltipY, int i1, int i2, GuiGraphics gfx) { + int slot = 0; + for (int y = 0; y < gridHeight; y++) { + for (int x = 0; x < gridWidth; x++) { + int px = tooltipX + x * SLOT_W + BORDER; + int py = tooltipY + y * SLOT_H + BORDER; + renderSlot(px, py, slot++, font, gfx); + } + } + renderBorder(tooltipX, tooltipY, gfx); + } + + private void renderSlot(int x, int y, int slotIndex, Font font, GuiGraphics gfx) { + ItemStack stack = slotIndex < items.size() ? items.get(slotIndex) : ItemStack.EMPTY; + blit(gfx, x, y, Sprite.SLOT); + gfx.renderItem(stack, x + BORDER, y + BORDER, slotIndex); + gfx.renderItemDecorations(font, stack, x + BORDER, y + BORDER); + } + + private void renderBorder(int x, int y, GuiGraphics gfx) { + blit(gfx, x, y, Sprite.CORNER); + blit(gfx, x + gridWidth * SLOT_W + BORDER, y, Sprite.CORNER); + + for (int i = 0; i < gridWidth; i++) { + blit(gfx, x + BORDER + i * SLOT_W, y, Sprite.HORIZONTAL); + blit(gfx, x + BORDER + i * SLOT_W, y + gridHeight * SLOT_H + 1, Sprite.HORIZONTAL); + } + + for (int i = 0; i < gridHeight; i++) { + blit(gfx, x, y + i * SLOT_H + BORDER, Sprite.VERTICAL); + blit(gfx, x + gridWidth * SLOT_W + BORDER, y + i * SLOT_H + BORDER, Sprite.VERTICAL); + } + + blit(gfx, x, y + gridHeight * SLOT_H + 1, Sprite.CORNER); + blit(gfx, x + gridWidth * SLOT_W + BORDER, y + gridHeight * SLOT_H + 1, Sprite.CORNER); + } + + private void blit(GuiGraphics gfx, int x, int y, Sprite sprite) { + gfx.blit(RenderPipelines.GUI_TEXTURED, TEXTURE, x, y, (float) sprite.u, (float) sprite.v, sprite.w, sprite.h, TEX_SIZE, TEX_SIZE); + } + + enum Sprite { + SLOT(0, 0, SLOT_W, SLOT_H), + HORIZONTAL(0, SLOT_H, SLOT_W, BORDER), + VERTICAL(SLOT_W, 0, BORDER, SLOT_H), + CORNER(SLOT_W, SLOT_H, BORDER, BORDER); + + final int u, v, w, h; + + Sprite(int u, int v, int w, int h) { + this.u = u; + this.v = v; + this.w = w; + this.h = h; + } + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/util/ItemRenderHelper.java b/src/main/java/sh/grimmer/bettershulkers/util/ItemRenderHelper.java new file mode 100644 index 0000000..6369c79 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/util/ItemRenderHelper.java @@ -0,0 +1,28 @@ +package sh.grimmer.bettershulkers.util; + +import it.unimi.dsi.fastutil.HashCommon; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.core.BlockPos; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +import org.jetbrains.annotations.Nullable; + +public final class ItemRenderHelper { + + private ItemRenderHelper() { + } + + @Nullable + public static ItemStackRenderState createRenderState(Level level, @Nullable BlockPos pos, @Nullable ItemStack stack) { + if (stack == null) { + return null; + } + ItemStackRenderState state = new ItemStackRenderState(); + int seed = pos == null ? 0 : HashCommon.long2int(pos.asLong()); + Minecraft.getInstance().getItemModelResolver().updateForTopItem(state, stack, ItemDisplayContext.FIXED, level, null, seed); + return state; + } +} diff --git a/src/main/java/sh/grimmer/bettershulkers/util/ShulkerBoxHelper.java b/src/main/java/sh/grimmer/bettershulkers/util/ShulkerBoxHelper.java new file mode 100644 index 0000000..8be8484 --- /dev/null +++ b/src/main/java/sh/grimmer/bettershulkers/util/ShulkerBoxHelper.java @@ -0,0 +1,77 @@ +package sh.grimmer.bettershulkers.util; + +import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ItemContainerContents; +import net.minecraft.world.level.block.ShulkerBoxBlock; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; + +import org.jetbrains.annotations.Nullable; +import java.util.LinkedHashMap; +import java.util.Map; + +public final class ShulkerBoxHelper { + + private ShulkerBoxHelper() { + } + + public static NonNullList getItems(ItemStack stack) { + NonNullList items = NonNullList.withSize(ShulkerBoxBlockEntity.CONTAINER_SIZE, ItemStack.EMPTY); + ItemContainerContents contents = stack.getOrDefault(DataComponents.CONTAINER, ItemContainerContents.EMPTY); + contents.copyInto(items); + return items; + } + + @Nullable + public static Component getCustomName(ItemStack stack) { + return stack.get(DataComponents.CUSTOM_NAME); + } + + @Nullable + public static ItemStack getBulkItem(NonNullList contents) { + Map itemCounts = new LinkedHashMap<>(); + for (ItemStack itemStack : contents) { + if (itemStack.isEmpty()) { + continue; + } + itemCounts.merge(itemStack.getItem(), itemStack.getCount(), Integer::sum); + } + return itemCounts.entrySet().stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .map(ItemStack::new) + .orElse(null); + } + + @Nullable + public static ItemStack getSingleTypeItem(NonNullList contents) { + boolean exactSame = true; + ItemStack renderItem = null; + for (ItemStack itemStack : contents) { + if (itemStack.isEmpty()) { + continue; + } + if (renderItem == null) { + renderItem = itemStack; + continue; + } + if (exactSame && ItemStack.isSameItemSameComponents(renderItem, itemStack)) { + continue; + } + if (ItemStack.isSameItem(renderItem, itemStack)) { + exactSame = false; + } else { + return null; + } + } + return exactSame ? renderItem : (renderItem != null ? new ItemStack(renderItem.getItem()) : null); + } + + public static boolean isShulkerBox(ItemStack stack) { + return stack.getItem() instanceof BlockItem blockItem && blockItem.getBlock() instanceof ShulkerBoxBlock; + } +} diff --git a/src/main/resources/assets/better_shulkers/lang/en_us.json b/src/main/resources/assets/better_shulkers/lang/en_us.json new file mode 100644 index 0000000..950dfb8 --- /dev/null +++ b/src/main/resources/assets/better_shulkers/lang/en_us.json @@ -0,0 +1,39 @@ +{ + "cloth_config.better_shulkers.settings": "Better Shulkers Settings", + + "cloth_config.better_shulkers.category.tooltips": "Tooltips", + "cloth_config.better_shulkers.tooltip_preview": "Show Tooltip Preview", + "cloth_config.better_shulkers.tooltip_preview.description": "When to show the grid preview of items inside shulker boxes.", + "cloth_config.better_shulkers.tooltip_preview.selected": "Selected: %s - %s", + "cloth_config.better_shulkers.tooltip_preview.always": "Always", + "cloth_config.better_shulkers.tooltip_preview.always.description": "Always show the grid, even for empty shulker boxes.", + "cloth_config.better_shulkers.tooltip_preview.when_filled": "When Filled", + "cloth_config.better_shulkers.tooltip_preview.when_filled.description": "Only show the grid when the shulker box contains at least one item.", + "cloth_config.better_shulkers.tooltip_preview.never": "Never", + "cloth_config.better_shulkers.tooltip_preview.never.description": "Never show the grid preview.", + + "cloth_config.better_shulkers.category.hints": "Item Hints", + "cloth_config.better_shulkers.show_item_hint": "Show Item Hints in GUI", + "cloth_config.better_shulkers.show_item_hint.description": "Renders item and label information on the shulker box lid in inventory and other GUIs.", + "cloth_config.better_shulkers.show_block_hint": "Show Item Hints in World", + "cloth_config.better_shulkers.show_block_hint.description": "Renders item and label information on the lid of shulker boxes placed as blocks in the world.", + "cloth_config.better_shulkers.item_display_type": "Item Display Type", + "cloth_config.better_shulkers.item_display_type.description": "How the mod should determine which item to show on the item hints.", + "cloth_config.better_shulkers.item_display_type.selected": "Selected: %s - %s", + "cloth_config.better_shulkers.item_display_type.none": "None", + "cloth_config.better_shulkers.item_display_type.none.description": "Don't show any item", + "cloth_config.better_shulkers.item_display_type.single_type": "Single Type", + "cloth_config.better_shulkers.item_display_type.single_type.description": "If the shulker box only contains one type of item, show that item", + "cloth_config.better_shulkers.item_display_type.bulk": "Bulk", + "cloth_config.better_shulkers.item_display_type.bulk.description": "Show the item that's most common in the shulker box", + "cloth_config.better_shulkers.item_display_type.first_item": "First Item", + "cloth_config.better_shulkers.item_display_type.first_item.description": "Show the first item in the shulker box", + "cloth_config.better_shulkers.show_labels": "Show Labels", + "cloth_config.better_shulkers.show_labels.description": "If this is enabled, the mod will show the custom name of the Shulker Box on the lid.", + "cloth_config.better_shulkers.hide_model_behind_hint": "Hide Hint Background in GUI", + "cloth_config.better_shulkers.hide_model_behind_hint.description": "Hide the shulker-like background of item hints in inventory and other GUIs.", + "cloth_config.better_shulkers.hint_item_scale": "Item Hints Scale", + "cloth_config.better_shulkers.hint_item_scale.description": "The scale (in %) of the item hint icon in inventory and other GUIs.", + "cloth_config.better_shulkers.show_fill_bar": "Show Fill Bar", + "cloth_config.better_shulkers.show_fill_bar.description": "If this is enabled, shulker boxes in the inventory and other GUIs will show a fill bar indicating how full they are." +} diff --git a/src/main/resources/assets/better_shulkers/lang/fr_fr.json b/src/main/resources/assets/better_shulkers/lang/fr_fr.json new file mode 100644 index 0000000..f6bfb6b --- /dev/null +++ b/src/main/resources/assets/better_shulkers/lang/fr_fr.json @@ -0,0 +1,39 @@ +{ + "cloth_config.better_shulkers.settings": "Parametres Better Shulkers", + + "cloth_config.better_shulkers.category.tooltips": "Info-bulles", + "cloth_config.better_shulkers.tooltip_preview": "Afficher l'apercu du contenu", + "cloth_config.better_shulkers.tooltip_preview.description": "Quand afficher la grille d'apercu des objets dans les shulker boxes.", + "cloth_config.better_shulkers.tooltip_preview.selected": "Selectionne : %s - %s", + "cloth_config.better_shulkers.tooltip_preview.always": "Toujours", + "cloth_config.better_shulkers.tooltip_preview.always.description": "Toujours afficher la grille, meme pour les shulker boxes vides.", + "cloth_config.better_shulkers.tooltip_preview.when_filled": "Si remplie", + "cloth_config.better_shulkers.tooltip_preview.when_filled.description": "Afficher la grille uniquement si la shulker box contient au moins un objet.", + "cloth_config.better_shulkers.tooltip_preview.never": "Jamais", + "cloth_config.better_shulkers.tooltip_preview.never.description": "Ne jamais afficher la grille d'apercu.", + + "cloth_config.better_shulkers.category.hints": "Indices visuels", + "cloth_config.better_shulkers.show_item_hint": "Indices visuels en interface", + "cloth_config.better_shulkers.show_item_hint.description": "Affiche l'objet et le nom sur le couvercle des shulker boxes dans l'inventaire et les autres interfaces.", + "cloth_config.better_shulkers.show_block_hint": "Indices visuels dans le monde", + "cloth_config.better_shulkers.show_block_hint.description": "Affiche l'objet et le nom sur le couvercle des shulker boxes posees en tant que blocs dans le monde.", + "cloth_config.better_shulkers.item_display_type": "Type d'affichage d'objet", + "cloth_config.better_shulkers.item_display_type.description": "Comment le mod determine quel objet afficher sur les indices visuels.", + "cloth_config.better_shulkers.item_display_type.selected": "Selectionne : %s - %s", + "cloth_config.better_shulkers.item_display_type.none": "Aucun", + "cloth_config.better_shulkers.item_display_type.none.description": "N'afficher aucun objet", + "cloth_config.better_shulkers.item_display_type.single_type": "Type unique", + "cloth_config.better_shulkers.item_display_type.single_type.description": "Si la shulker box ne contient qu'un seul type d'objet, l'afficher", + "cloth_config.better_shulkers.item_display_type.bulk": "Majoritaire", + "cloth_config.better_shulkers.item_display_type.bulk.description": "Afficher l'objet le plus present dans la shulker box", + "cloth_config.better_shulkers.item_display_type.first_item": "Premier objet", + "cloth_config.better_shulkers.item_display_type.first_item.description": "Afficher le premier objet de la shulker box", + "cloth_config.better_shulkers.show_labels": "Afficher les noms", + "cloth_config.better_shulkers.show_labels.description": "Affiche le nom personnalise de la Shulker Box sur le couvercle.", + "cloth_config.better_shulkers.hide_model_behind_hint": "Masquer le fond de l'indice en interface", + "cloth_config.better_shulkers.hide_model_behind_hint.description": "Masque le fond en forme de shulker derriere les indices visuels dans l'inventaire et les autres interfaces.", + "cloth_config.better_shulkers.hint_item_scale": "Echelle des indices", + "cloth_config.better_shulkers.hint_item_scale.description": "L'echelle (en %) de l'icone d'indice dans l'inventaire et les autres interfaces.", + "cloth_config.better_shulkers.show_fill_bar": "Barre de remplissage", + "cloth_config.better_shulkers.show_fill_bar.description": "Affiche une barre de remplissage sur les shulker boxes dans l'inventaire et les autres interfaces." +} diff --git a/src/main/resources/assets/better_shulkers/textures/gui/container/slot.png b/src/main/resources/assets/better_shulkers/textures/gui/container/slot.png new file mode 100644 index 0000000..0651733 Binary files /dev/null and b/src/main/resources/assets/better_shulkers/textures/gui/container/slot.png differ diff --git a/src/main/resources/assets/minecraft/models/item/template_shulker_box.json b/src/main/resources/assets/minecraft/models/item/template_shulker_box.json new file mode 100644 index 0000000..ad71c29 --- /dev/null +++ b/src/main/resources/assets/minecraft/models/item/template_shulker_box.json @@ -0,0 +1,36 @@ +{ + "parent": "builtin/entity", + "gui_light": "front", + "display": { + "gui": { + "rotation": [90, 0, 0], + "translation": [0, 0, 0], + "scale": [1, 1, 1] + }, + "ground": { + "rotation": [0, 0, 0], + "translation": [0, 3, 0], + "scale": [0.25, 0.25, 0.25] + }, + "head": { + "rotation": [0, 180, 0], + "translation": [0, 0, 0], + "scale": [1, 1, 1] + }, + "fixed": { + "rotation": [0, 180, 0], + "translation": [0, 0, 0], + "scale": [0.5, 0.5, 0.5] + }, + "thirdperson_righthand": { + "rotation": [75, 315, 0], + "translation": [0, 2.5, 0], + "scale": [0.375, 0.375, 0.375] + }, + "firstperson_righthand": { + "rotation": [0, 315, 0], + "translation": [0, 0, 0], + "scale": [0.4, 0.4, 0.4] + } + } +} diff --git a/src/main/resources/better_shulkers.accesswidener b/src/main/resources/better_shulkers.accesswidener new file mode 100644 index 0000000..9566435 --- /dev/null +++ b/src/main/resources/better_shulkers.accesswidener @@ -0,0 +1,5 @@ +accessWidener v1 named +accessible method net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity getItems ()Lnet/minecraft/core/NonNullList; +accessible method net/minecraft/world/level/block/entity/ShulkerBoxBlockEntity setItems (Lnet/minecraft/core/NonNullList;)V +accessible field net/minecraft/world/inventory/ShulkerBoxMenu container Lnet/minecraft/world/Container; +mutable field net/minecraft/client/gui/screens/Screen title Lnet/minecraft/network/chat/Component; diff --git a/src/main/resources/better_shulkers.mixins.json b/src/main/resources/better_shulkers.mixins.json new file mode 100644 index 0000000..6fc27a1 --- /dev/null +++ b/src/main/resources/better_shulkers.mixins.json @@ -0,0 +1,21 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "sh.grimmer.bettershulkers.mixin", + "compatibilityLevel": "JAVA_21", + "client": [ + "BlockItemMixin", + "ClientTooltipComponentMixin", + "ItemStackMixin", + "ShulkerBoxBlockMixin", + "ShulkerBoxMenuMixin", + "ShulkerBoxRendererMixin", + "ShulkerBoxRenderStateMixin", + "ShulkerBoxScreenMixin", + "ShulkerBoxSpecialRendererMixin" + ], + "mixins": [], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..3ec8cb5 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,36 @@ +{ + "schemaVersion": 1, + "id": "better_shulkers", + "version": "${mod_version}", + "name": "Better Shulkers", + "description": "Enhances shulker boxes with tooltips, item hints, labels and a fill bar.", + "authors": [ + "Grimmer" + ], + "contact": { + "sources": "https://git.grimmer.sh/grimmer/better-shulkers" + }, + "license": "LGPL-3.0-only", + "icon": "icon.png", + "environment": "*", + "entrypoints": { + "main": [ + "sh.grimmer.bettershulkers.BetterShulkers" + ], + "modmenu": [ + "sh.grimmer.bettershulkers.integration.ModMenuIntegration" + ] + }, + "mixins": [ + "better_shulkers.mixins.json" + ], + "depends": { + "fabricloader": ">=${fabric_loader_version}", + "minecraft": "${minecraft_version}" + }, + "suggests": { + "modmenu": ">=${modmenu_version}", + "cloth-config2": ">=${cloth_config_version}" + }, + "accessWidener": "better_shulkers.accesswidener" +} diff --git a/src/main/resources/icon.png b/src/main/resources/icon.png new file mode 100644 index 0000000..f0cf3b5 Binary files /dev/null and b/src/main/resources/icon.png differ