first commit

This commit is contained in:
themaster1970sf 2026-06-20 23:05:36 +03:00
commit f531f2b09b
25 changed files with 1157 additions and 0 deletions

9
.gitattributes vendored Normal file
View file

@ -0,0 +1,9 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf

40
.gitignore vendored Normal file
View file

@ -0,0 +1,40 @@
# gradle
.gradle/
build/
out/
classes/
# eclipse
*.launch
# idea
.idea/
*.iml
*.ipr
*.iws
# vscode
.settings/
.vscode/
bin/
.classpath
.project
# macos
*.DS_Store
# fabric
run/
# java
hs_err_*.log
replay_*.log
*.hprof
*.jfr

121
LICENSE Normal file
View file

@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

64
README.md Normal file
View file

@ -0,0 +1,64 @@
<a href="https://modrinth.com/mod/betterhidehotbar"><img src="https://raw.githubusercontent.com/intergrav/devins-badges/refs/heads/v3/assets/compact/available/modrinth_vector.svg" alt="Available on Modrinth"></a>
<a href="https://www.curseforge.com/minecraft/mc-mods/better-hide-hotbar"><img src="https://raw.githubusercontent.com/intergrav/devins-badges/refs/heads/v3/assets/compact/available/curseforge_vector.svg" alt="Available on CurseForge"></a>
# Better Hide Hotbar Mod
Простой и легковесный клиентский модификатор для Minecraft (Fabric), предназначенный для точечного скрытия элементов игрового интерфейса (HUD).
Мод позволяет полностью убрать нижнюю панель предметов, статус-бары и полоску опыта, оставляя при этом важные элементы вроде прицела, чата и руки персонажа нетронутыми. Отлично подходит для создания красивых скриншотов, записи кинематографичных видео (машиним) или для усложненного хардкорного геймплея.
---
## Выбор версии исходного кода
Архитектура игрового интерфейса Майнкрафта сильно менялась в версиях 1.21+. Выберите ветку репозитория, соответствующую вашей версии игры, чтобы посмотреть нужный исходный код миксинов:
* **[Исходный код для Minecraft 1.21.7](https://github.com/themaster1970sf/HideHotbar/tree/1.21.7)** — использует базовое скрытие через `renderMainHud` и `renderStatusBars`.
* **[Исходный код для Minecraft 1.21.11](https://github.com/themaster1970sf/HideHotbar/tree/1.21.11)** — адаптирован под новые маппинги с дополнительным инжектом в метод `renderExperienceBar`.
---
## Функционал
При нажатии на горячую клавишу **F7** (можно переназначить в настройках управления) на экране скрываются/появляются следующие элементы:
* **Хотбар** (горячая панель ячеек предметов).
* **Статус-бары** (здоровье, голод, броня, пузырьки воздуха, щиты).
* **Опыт** (как зеленая полоска прогресса, так и цифра текущего уровня).
**Что ОСТАЕТСЯ видимым:**
* Перекрестие прицела (Crosshair).
* Игровой чат и список игроков на Tab.
* Рука персонажа (и предметы в ней).
* Эффекты зелий в правом верхнем углу экрана.
Если включена функция **unhide-on-damage**, то при уроне хотбар становится видимым (Отключено изначально)
---
## Как собрать проект локально
Если вы хотите собрать `.jar` файл мода из исходного кода:
1. Склонируйте репозиторий и переключитесь на нужную ветку:
```bash
git clone https://github.com/themaster1970sf/HideHotbar.git
cd HideHotbar
git checkout 1.21.11 # или 1.21.7 в зависимости от версии
```
2. Скомпилируйте мод с помощью Gradle:
```bash
./gradlew build
```
3. Готовый `.jar` файл появится в папке `build/libs/`.
---
## Авторы и благодарности
* **Разработчик:** [themaster1970sf](https://github.com/themaster1970sf)
* **Особая благодарность:** [daniil10295](https://github.com/Daniil10295) за помощь в реализации корректного перехвата методов `renderMainHud` для ранних версий 1.21.7, интеграцией modmenu и создании функции **unhide-on-damage**

46
build.gradle Normal file
View file

@ -0,0 +1,46 @@
plugins {
id "fabric-loom" version "1.16-SNAPSHOT"
id "java"
// id "com.modrinth.minotaur" version "2.+"
}
group = "dev.lutsu.hidehotbar"
version = "1.0.6+1.21.7"
repositories {
mavenCentral()
maven { url = "https://maven.fabricmc.net/" }
maven { url = "https://maven.shedaniel.me/" }
maven { url = "https://maven.terraformersmc.com/releases/" }
}
dependencies {
minecraft "com.mojang:minecraft:1.21.7"
mappings "net.fabricmc:yarn:1.21.7+build.1:v2"
modImplementation "net.fabricmc:fabric-loader:0.16.14"
modImplementation "net.fabricmc.fabric-api:fabric-api:0.128.0+1.21.7"
modImplementation("com.terraformersmc:modmenu:15.0.0")
modApi("me.shedaniel.cloth:cloth-config-fabric:19.0.147") {
exclude(group: "net.fabricmc.fabric-api")
}
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(21)
}
tasks.withType(JavaCompile).configureEach {
options.encoding = "UTF-8"
}
tasks.named('processResources', ProcessResources) {
def map = [
"version": project.version
]
inputs.properties(map)
filesMatching("fabric.mod.json") {
expand(map)
}
}

6
gradle.properties Normal file
View file

@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx1G
fabric_loader_version=0.16.14
yarn_mappings=1.21.7+build.1+v2
minecraft_version=1.21.7
fabric_version=0.128.0+1.21.7
loom_version=1.16-SNAPSHOT

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
gradlew vendored Normal file
View file

@ -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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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" "$@"

82
gradlew.bat vendored Normal file
View file

@ -0,0 +1,82 @@
@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, and ensure extensions are enabled
setlocal EnableExtensions
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
"%COMSPEC%" /c exit 1
: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
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute Gradle
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%

12
settings.gradle Normal file
View file

@ -0,0 +1,12 @@
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
mavenCentral()
gradlePluginPortal()
}
}
// Should match your modid
rootProject.name = 'hidehotbar'

View file

@ -0,0 +1,13 @@
package dev.lutsu.hidehotbar;
import dev.lutsu.hidehotbar.config.ToolBarConfig;
import net.fabricmc.api.ModInitializer;
public class HideHotbarMod implements ModInitializer {
public static final String MOD_ID = "hidehotbar";
@Override
public void onInitialize() {
ToolBarConfig.load();
}
}

View file

@ -0,0 +1,79 @@
package dev.lutsu.hidehotbar;
import dev.lutsu.hidehotbar.config.ToolBarConfig;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.text.Text;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.glfw.GLFW;
public class HideHotbarModClient implements ClientModInitializer {
public KeyBinding toggleHudKeyBinding;
@Override
public void onInitializeClient() {
toggleHudKeyBinding = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.hidehotbar.toggle_hud",
GLFW.GLFW_KEY_F7,
"key.categories.hidehotbar"
));
if (ToolBarConfig.unhide_on_restart) {
ToolBarConfig.hid = false;
}
ClientTickEvents.END_CLIENT_TICK.register(this::clientTickListener);
}
protected void clientTickListener(MinecraftClient client){
if (!ToolBarConfig.enabled) { // skip button press when disabled
DisableHotbarAlert(client);
return;
}
while (toggleHudKeyBinding.wasPressed()) {
toggleHotbar(client);
}
if (client.player != null){
float hpPercentage = client.player.getHealth() / client.player.getMaxHealth() * 100;
if (hpPercentage < ToolBarConfig.low_hp_percentage
&& ToolBarConfig.unhide_on_low_hp
&& ToolBarConfig.hid) {
toggleHotbar(client);
}
var foodManager = client.player.getHungerManager();
float hungerPercentage = (float) foodManager.getFoodLevel() / 20 *100;
if (hungerPercentage < ToolBarConfig.low_food_percentage
&& ToolBarConfig.unhide_on_low_food
&& ToolBarConfig.hid) {
toggleHotbar(client);
}
}
}
public static void toggleHotbar(MinecraftClient client) {
ToolBarConfig.hid = !ToolBarConfig.hid;
SendHotbarAlert(client);
}
protected static void SendHotbarAlert(MinecraftClient client) {
if (client.player != null) {
client.player.sendMessage(Text.translatable(
ToolBarConfig.hid
? "hidehotbar.hud_hidden"
: "hidehotbar.hud_shown"
), true);
}
}
protected void DisableHotbarAlert(MinecraftClient client) {
if (client.player != null) {
client.player.sendMessage(Text.translatable("hidehotbar.disabled"), true);
}
}
}

View file

@ -0,0 +1,124 @@
package dev.lutsu.hidehotbar.config;
import me.shedaniel.clothconfig2.api.ConfigBuilder;
import me.shedaniel.clothconfig2.api.ConfigCategory;
import me.shedaniel.clothconfig2.api.ConfigEntryBuilder;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
public class ConfigScreen {
public static Screen create(Screen parent) {
ConfigBuilder builder = ConfigBuilder.create()
.setParentScreen(parent)
.setTitle(Text.translatable("hidehotbar.title.config"));
ConfigEntryBuilder entryBuilder = builder.entryBuilder();
ConfigCategory general = builder.getOrCreateCategory(
Text.translatable("hidehotbar.category.general")
);
general.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.enabled"),
ToolBarConfig.enabled
)
.setDefaultValue(true)
.setSaveConsumer(value -> ToolBarConfig.enabled = value)
.build()
);
general.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.is_hidden"),
ToolBarConfig.hid
)
.setDefaultValue(false)
.setSaveConsumer(value -> ToolBarConfig.hid = value)
.build()
);
ConfigCategory unhide = builder.getOrCreateCategory(
Text.translatable("hidehotbar.category.unhide_if")
);
unhide.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.unhideon.restart"),
ToolBarConfig.unhide_on_restart
)
.setTooltip(Text.translatable("hidehotbar.option.unhideon.damage.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(value -> ToolBarConfig.unhide_on_restart = value)
.build()
);
unhide.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.unhideon.slot_change"),
ToolBarConfig.unhide_on_slot_change
)
.setTooltip(Text.translatable("hidehotbar.option.unhideon.slot_change.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(value -> ToolBarConfig.unhide_on_slot_change = value)
.build()
);
unhide.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.unhideon.damage"),
ToolBarConfig.unhide_on_damage
)
.setTooltip(Text.translatable("hidehotbar.option.unhideon.damage.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(value -> ToolBarConfig.unhide_on_damage = value)
.build()
);
unhide.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.unhideon.low_hp"),
ToolBarConfig.unhide_on_low_hp
)
.setTooltip(Text.translatable("hidehotbar.option.unhideon.low_hp.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(value -> ToolBarConfig.unhide_on_low_hp = value)
.build()
);
unhide.addEntry(
entryBuilder.startIntSlider(
Text.translatable("hidehotbar.option.unhideon.low_hp_level"),
1, 1, 100
).setTooltip(Text.translatable("hidehotbar.option.unhideon.low_hp_level.tooltip"))
.setDefaultValue(20)
.setSaveConsumer(value -> ToolBarConfig.low_hp_percentage = value)
.build()
);
unhide.addEntry(
entryBuilder.startBooleanToggle(
Text.translatable("hidehotbar.option.unhideon.low_food"),
ToolBarConfig.unhide_on_low_food
)
.setTooltip(Text.translatable("hidehotbar.option.unhideon.low_food.tooltip"))
.setDefaultValue(false)
.setSaveConsumer(value -> ToolBarConfig.unhide_on_low_food = value)
.build()
);
unhide.addEntry(
entryBuilder.startIntSlider(
Text.translatable("hidehotbar.option.unhideon.low_food_level"),
ToolBarConfig.low_food_percentage, 1, 100
).setTooltip(Text.translatable("hidehotbar.option.unhideon.low_food_level.tooltip"))
.setDefaultValue(20)
.setSaveConsumer(value -> ToolBarConfig.low_food_percentage = value)
.build()
);
builder.setSavingRunnable(ToolBarConfig::save);
return builder.build();
}
}

View file

@ -0,0 +1,12 @@
package dev.lutsu.hidehotbar.config;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import com.terraformersmc.modmenu.api.ModMenuApi;
public class ModMenuIntegration implements ModMenuApi {
@Override
public ConfigScreenFactory<?> getModConfigScreenFactory() {
return ConfigScreen::create;
}
}

View file

@ -0,0 +1,70 @@
package dev.lutsu.hidehotbar.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.fabricmc.loader.api.FabricLoader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ToolBarConfig {
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.create();
private static final Path CONFIG_FILE =
FabricLoader.getInstance().getConfigDir().resolve("hidehotbar.json");
public static boolean enabled = true;
public static boolean hid = false;
public static boolean unhide_on_restart = true;
public static boolean unhide_on_slot_change = true;
public static boolean unhide_on_damage = false;
public static boolean unhide_on_low_hp = false;
public static boolean unhide_on_low_food = false;
public static int low_hp_percentage = 20;
public static int low_food_percentage = 20;
public static void load() {
if (!Files.exists(CONFIG_FILE)) {
save();
return;
}
try {
ConfigData data = GSON.fromJson(
Files.readString(CONFIG_FILE),
ConfigData.class
);
if (data != null) {
enabled = data.enabled;
hid = data.hid;
}
} catch (Exception e) {
// e.printStackTrace();
}
}
public static void save() {
ConfigData data = new ConfigData();
data.enabled = enabled;
try {
Files.writeString(
CONFIG_FILE,
GSON.toJson(data)
);
} catch (IOException e) {
// e.printStackTrace();
}
}
private static class ConfigData {
boolean enabled = true;
boolean hid = true;
}
}

View file

@ -0,0 +1,28 @@
package dev.lutsu.hidehotbar.mixin;
import dev.lutsu.hidehotbar.HideHotbarModClient;
import dev.lutsu.hidehotbar.config.ToolBarConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
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;
@Mixin(LivingEntity.class)
public class ClientDamageMixin {
@Inject(method = "onDamaged", at = @At("TAIL"))
private void onDamaged(DamageSource source, CallbackInfo ci) {
LivingEntity self = (LivingEntity) (Object) this;
MinecraftClient client = MinecraftClient.getInstance();
if (self != client.player) return;
if (ToolBarConfig.hid && ToolBarConfig.unhide_on_damage) {
ToolBarConfig.hid = false;
}
}
}

View file

@ -0,0 +1,28 @@
package dev.lutsu.hidehotbar.mixin;
import dev.lutsu.hidehotbar.HideHotbarModClient;
import dev.lutsu.hidehotbar.config.ToolBarConfig;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.hud.bar.ExperienceBar;
import net.minecraft.client.render.RenderTickCounter;
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;
@Mixin(ExperienceBar.class)
public class ExperienceBarMixin {
@Inject(method = "renderBar", at = @At("HEAD"), cancellable = true)
private void onRenderBar(DrawContext context, RenderTickCounter tickCounter, CallbackInfo ci) {
if (ToolBarConfig.hid) {
ci.cancel();
}
}
@Inject(method = "renderAddons", at = @At("HEAD"), cancellable = true)
private void onRenderAddons(DrawContext context, RenderTickCounter tickCounter, CallbackInfo ci) {
if (ToolBarConfig.hid) {
ci.cancel();
}
}
}

View file

@ -0,0 +1,28 @@
package dev.lutsu.hidehotbar.mixin;
import dev.lutsu.hidehotbar.HideHotbarModClient;
import dev.lutsu.hidehotbar.config.ToolBarConfig;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.hud.InGameHud;
import net.minecraft.client.render.RenderTickCounter;
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;
@Mixin(InGameHud.class)
public class InGameHudMixin {
@Inject(method = "renderMainHud", at = @At("HEAD"), cancellable = true)
private void onRenderMainHud(DrawContext context, RenderTickCounter tickCounter, CallbackInfo ci) {
if (ToolBarConfig.hid) {
ci.cancel();
}
}
@Inject(method = "renderStatusBars", at = @At("HEAD"), cancellable = true)
private void onRenderStatusBars(DrawContext context, CallbackInfo ci) {
if (ToolBarConfig.hid) {
ci.cancel();
}
}
}

View file

@ -0,0 +1,30 @@
package dev.lutsu.hidehotbar.mixin;
import dev.lutsu.hidehotbar.config.ToolBarConfig;
import net.minecraft.entity.player.PlayerInventory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerInventory.class)
public class PlayerInventoryMixin {
@Shadow private int selectedSlot;
@Unique
private int lastSlot = -1;
@Inject(method = "updateItems", at = @At("HEAD"))
private void onUpdateItems(CallbackInfo ci) {
if (this.selectedSlot != this.lastSlot) {
if (this.lastSlot != -1
&& ToolBarConfig.unhide_on_slot_change
&& ToolBarConfig.hid) {
ToolBarConfig.hid = false;
}
this.lastSlot = this.selectedSlot;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View file

@ -0,0 +1,27 @@
{
"key.categories.hidehotbar": "Hide Hotbar",
"key.hidehotbar.toggle_hud": "Toggle HUD Visibility",
"hidehotbar.hud_hidden": "HUD hidden",
"hidehotbar.hud_shown": "HUD shown",
"hidehotbar.title.config": "Better Hide hotbar configuration",
"hidehotbar.disabled": "Mod is disabled!",
"hidehotbar.category.general": "General",
"hidehotbar.category.unhide_if": "Unhide hotbar conditions",
"hidehotbar.option.enabled": "Enable mod",
"hidehotbar.option.is_hidden": "Hotbar hidden",
"hidehotbar.option.unhideon.restart": "Client restart",
"hidehotbar.option.unhideon.restart.tooltip": "Unhides hotbar after restart",
"hidehotbar.option.unhideon.slot_change": "Slot change",
"hidehotbar.option.unhideon.slot_change.tooltip": "Unhides hotbar if slot changed",
"hidehotbar.option.unhideon.damage": "Damage applied",
"hidehotbar.option.unhideon.damage.tooltip": "Unhides hotbar when damage",
"hidehotbar.option.unhideon.low_hp": "Low health percentage",
"hidehotbar.option.unhideon.low_hp.tooltip": "Unhides hotbar health percentage is too low",
"hidehotbar.option.unhideon.low_hp_level": "Low health percentage is:",
"hidehotbar.option.unhideon.low_hp_level.tooltip": "When should hotbar be unhidden (in %)",
"hidehotbar.option.unhideon.low_food": "Low food percentage",
"hidehotbar.option.unhideon.low_food.tooltip": "Unhides hotbar food percentage is too low",
"hidehotbar.option.unhideon.low_food_level": "Low food percentage is:",
"hidehotbar.option.unhideon.low_food_level.tooltip": "When should hotbar be unhidden (in %)"
}

View file

@ -0,0 +1,26 @@
{
"key.categories.hidehotbar": "Скрыть хотбар",
"key.hidehotbar.toggle_hud": "Переключить видимость HUD",
"hidehotbar.hud_hidden": "HUD скрыт",
"hidehotbar.hud_shown": "HUD показан",
"hidehotbar.title.config": "Конфигурация мода Better Hide hotbar",
"hidehotbar.disabled": "Mod отключен!",
"hidehotbar.category.general": "Основное",
"hidehotbar.category.unhide_if": "Условия показа хотбара",
"hidehotbar.option.enabled": "Включить мод",
"hidehotbar.option.is_hidden": "Спратать хотбар",
"hidehotbar.option.unhideon.restart": "При перезапуске клиента Minecraft",
"hidehotbar.option.unhideon.restart.tooltip": "Показывает хотбар при перезапуске клиента Minecraft",
"hidehotbar.option.unhideon.slot_change": "При изменении слота",
"hidehotbar.option.unhideon.slot_change.tooltip": "Показывает хотбар при изменени слота",
"hidehotbar.option.unhideon.damage": "Показать при уроне",
"hidehotbar.option.unhideon.damage.tooltip": "Показать хотбар если нанесен урон игроку",
"hidehotbar.option.unhideon.low_food": "При низком уровне еды",
"hidehotbar.option.unhideon.low_food.tooltip": "Показать хотбар если уровень еды низкий",
"hidehotbar.option.unhideon.low_food_level": "Низкий уровень еды ниже:",
"hidehotbar.option.unhideon.low_food_level.tooltip": "Процент при котором уровень еды считается низким (in %)",
"hidehotbar.option.unhideon.low_hp": "При низком здоровии",
"hidehotbar.option.unhideon.low_hp.tooltip": "Показать хотбар если здоровье низкое",
"hidehotbar.option.unhideon.low_hp_level": "Низкое здоровье - когда ниже %:",
"hidehotbar.option.unhideon.low_hp_level.tooltip": "Процент при котором здоровье считается низким (в %)"
}

View file

@ -0,0 +1,41 @@
{
"schemaVersion": 1,
"id": "hidehotbar",
"version": "${version}",
"name": "Hide Hotbar",
"description": "Hide hotbar, experience bar, hunger and health with F7 key",
"authors": ["TheMaster1970", "daniil10295"],
"contact": {},
"license": "MIT",
"icon": "assets/hidehotbar/icon.png",
"environment": "*",
"entrypoints": {
"main": [
"dev.lutsu.hidehotbar.HideHotbarMod"
],
"client": [
"dev.lutsu.hidehotbar.HideHotbarModClient"
],
"modmenu": [
"dev.lutsu.hidehotbar.config.ModMenuIntegration"
]
},
"mixins": [
"hidehotbar.mixins.json"
],
"depends": {
"fabricloader": ">=0.16.0",
"minecraft": "~1.21.7 <=1.21.8",
"java": ">=21",
"fabric-api": "*",
"cloth-config2": "*"
},
"custom": {
"modmenu": {
"links": {
"GitHub": "https://github.com/themaster1970sf/HideHotbar",
"Issues": "https://github.com/themaster1970sf/HideHotbar/issues"
}
}
}
}

View file

@ -0,0 +1,14 @@
{
"required": true,
"package": "dev.lutsu.hidehotbar.mixin",
"compatibilityLevel": "JAVA_21",
"mixins": [
"ClientDamageMixin",
"ExperienceBarMixin",
"InGameHudMixin",
"PlayerInventoryMixin"
],
"injectors": {
"defaultRequire": 1
}
}