Compare commits

..

23 commits

Author SHA1 Message Date
68aac66094 Update ChestGUI to new LibZontreck API 2024-01-15 00:56:27 -07:00
dbd34125f8 Fix non-functional reset button 2024-01-10 03:48:53 -07:00
b6d5c0c502 Fix non-functional reset button 2024-01-10 03:46:34 -07:00
bf2d5c83d9 Add a basic config gui to WMD when the jar is on the server 2024-01-10 03:31:48 -07:00
131cd673f8 Restructure some stuff 2024-01-09 14:57:08 -07:00
d3cbcc3f36 Rename package! 2024-01-09 14:52:40 -07:00
bb135ebd65 Update libz reference 2024-01-07 17:39:52 -07:00
bdaa4328f4 Update repository 2024-01-07 17:35:49 -07:00
a4a961afcb Update LibZ version 2024-01-02 18:09:34 -07:00
ec14da3bfa Update LibZ version 2023-12-18 15:33:14 -07:00
1c8d56f5ae Move hearts render over to Aria's Essentials 2023-12-15 23:56:35 -07:00
80720c7fbf Get hearts working again 2023-12-15 23:53:57 -07:00
bbf4e41abc Start re-adding the extra hearts function 2023-12-15 19:41:18 -07:00
f1fce3fbaa Update libzontreck version 2023-12-14 22:19:05 -07:00
1b369a0db5 Update libzontreck version 2023-12-14 22:15:55 -07:00
d002986525 Finish updating to 1.20 2023-11-19 08:19:21 -07:00
5d62d175af Add a hunger watcher instead of just health 2023-11-19 08:00:37 -07:00
0b94cbbc2f Mod is now functional on 1.20, but hunger watch is not functional 2023-11-19 07:07:42 -07:00
928e57c104 Start updating to 1.20 2023-11-19 06:14:32 -07:00
b45e9c3fec Update to 1.19.3, update DelayedExecutorService references. 2023-05-15 22:06:21 -07:00
8289bdecaf Patch for mods.toml to support 1.19 (oops) 2023-04-22 03:47:29 -07:00
574faa7b8d Push update for 1.19.4 2023-04-22 03:31:22 -07:00
9f8b5582f1 Update WMD to new LibZontreck API 2023-03-06 02:26:39 -07:00
31 changed files with 1270 additions and 899 deletions

View file

@ -3,7 +3,7 @@ HOW TO BUILD
On your platform of choice
```
gradlew clean jar
gradlew clean build
```

View file

@ -1,12 +1,17 @@
plugins {
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.minecraftforge.gradle' version '5.1.+'
id 'net.minecraftforge.gradle' version '[6.0,6.2)'
id 'org.parchmentmc.librarian.forgegradle' version '1.+'
}
version = "${mc_version}-${myversion}"
group = 'dev.zontreck' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'WatchMyDurability'
version = mod_version
group = mod_group_id
base {
archivesName = mod_id
}
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
@ -22,18 +27,40 @@ minecraft {
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
//
// Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge
// Additional setup is needed to use their mappings: https://github.com/ParchmentMC/Parchment/wiki/Getting-Started
// Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started
//
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'official', version: "${mc_version}"
mappings channel: mapping_channel, version: mapping_version
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Currently, this location cannot be changed from the default.
// When true, this property will have all Eclipse/IntelliJ IDEA run configurations run the "prepareX" task for the given run configuration before launching the game.
// In most cases, it is not necessary to enable.
// enableEclipsePrepareRuns = true
// enableIdeaPrepareRuns = true
// This property allows configuring Gradle's ProcessResources task(s) to run on IDE output locations before launching the game.
// It is REQUIRED to be set to true for this template to function.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
copyIdeResources = true
// When true, this property will add the folder name of all declared run configurations to generated IDE run configurations.
// The folder name can be set on a run configuration using the "folderName" property.
// By default, the folder name of a run configuration is the name of the Gradle project containing it.
// generateRunFolders = true
// This property enables access transformers for use in development.
// They will be applied to the Minecraft artifact.
// The access transformer file can be anywhere in the project.
// However, it must be at "META-INF/accesstransformer.cfg" in the final mod jar to be loaded by Forge.
// This default location is a best practice to automatically put the file in the right place in the final jar.
// See https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ for more information.
accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
// applies to all the run configs below
configureEach {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
@ -48,66 +75,36 @@ minecraft {
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', 'watchmydurability'
mods {
watchmydurability {
"${mod_id}" {
source sourceSets.main
}
}
}
client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', mod_id
}
server {
workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
property 'forge.enabledGameTestNamespaces', 'watchmydurability'
mods {
watchmydurability {
source sourceSets.main
}
}
property 'forge.enabledGameTestNamespaces', mod_id
args '--nogui'
}
// This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided.
// The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer {
workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
property 'forge.enabledGameTestNamespaces', 'watchmydurability'
mods {
watchmydurability {
source sourceSets.main
}
}
property 'forge.enabledGameTestNamespaces', mod_id
}
data {
workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
// example of overriding the workingDirectory set in configureEach above
workingDirectory project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', 'watchmydurability', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
mods {
watchmydurability {
source sourceSets.main
}
}
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
}
}
}
@ -119,62 +116,105 @@ repositories {
// Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
maven {
name = "ZNI Creations"
url = "https://maven.zontreck.dev"
name = "Aria's Creations Caches"
url = "https://maven.zontreck.com/repository/internal"
}
// Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
flatDir {
dir 'libs'
}
//maven {
// name = "CurseMaven"
// url = "https://cursemaven.com"
//}
maven {
name = "zontreck Maven"
url = "https://maven.zontreck.com/repository/zontreck"
}
}
dependencies {
// Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed
// that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft "net.minecraftforge:forge:${mc_version}-${forge_version}"
// Specify the version of Minecraft to use.
// Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact.
// The "userdev" classifier will be requested and setup by ForgeGradle.
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"],
// then special handling is done to allow a setup of a vanilla dependency without the use of an external repository.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
implementation fg.deobf("dev.zontreck:libzontreck:${mc_version}-${libz_version}:dev")
runtimeOnly fg.deobf("dev.zontreck:libzontreck:${mc_version}-${libz_version}")
compileOnly fg.deobf("dev.zontreck:libzontreck:${mc_version}-${libz_version}:dev")
implementation fg.deobf("dev.zontreck:LibZontreckMod:${libzontreck}")
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
// Real mod deobf dependency examples - these get remapped to your current mappings
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}:api") // Adds JEI API as a compile dependency
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency
// implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency
// Examples using mod jars from ./libs
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info...
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
jar {
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
// When "copyIdeResources" is enabled, this will also run before the game launches in IDE environments.
// See https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
tasks.named('processResources', ProcessResources).configure {
var replaceProperties = [
minecraft_version: minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version: forge_version, forge_version_range: forge_version_range,
loader_version_range: loader_version_range,
mod_id: mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors: mod_authors, mod_description: mod_description,
]
inputs.properties replaceProperties
filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) {
expand replaceProperties + [project: project]
}
}
// Example for how to get properties into the manifest for reading at runtime.
tasks.named('jar', Jar).configure {
manifest {
attributes([
"Specification-Title" : "watchmydurability",
"Specification-Vendor" : "Zontreck",
"Specification-Version" : "1", // We are version 1 of ourselves
"Implementation-Title" : project.name,
"Implementation-Version" : project.jar.archiveVersion,
"Implementation-Vendor" : "ZNI Creations",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
'Specification-Title' : mod_id,
'Specification-Vendor' : mod_authors,
'Specification-Version' : '1', // We are version 1 of ourselves
'Implementation-Title' : project.name,
'Implementation-Version' : project.jar.archiveVersion,
'Implementation-Vendor' : mod_authors,
'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
// This is the preferred method to reobfuscate your jar file
finalizedBy 'reobfJar'
}
// Example configuration to allow publishing using the maven-publish plugin
// This is the preferred method to reobfuscate your jar file
jar.finalizedBy('reobfJar')
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing
// publish.dependsOn('reobfJar')
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing:
// tasks.named('publish').configure {
// dependsOn 'reobfJar'
// }
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
mavenJava(MavenPublication) {
register('mavenJava', MavenPublication) {
artifact jar
}
}

View file

@ -3,7 +3,58 @@
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
mc_version=1.18.2
forge_version=40.2.1
myversion=1.1.2.7
libz_version=1.0.4.9
libzontreck=1.10.011524.0045
## Environment Properties
# The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=1.20.1
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[1.20.1,1.21)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=47.2.0
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[47,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[47,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=parchment
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=2023.09.03-1.20.1
## Mod Properties
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=watchmydurability
# The human-readable display name for the mod.
mod_name=WatchMyDurability
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=GPLv3
# The mod version. See https://semver.org/
mod_version=1.2.011524.0055
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=dev.zontreck
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=zontreck
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Watches the durability tools, and or your hunger.

Binary file not shown.

View file

@ -1,5 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

14
gradlew vendored
View file

@ -1,5 +1,5 @@
#!/bin/sh
#
#
# Copyright © 2015-2021 the original authors.
#
@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@ -80,10 +80,10 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
@ -143,12 +143,16 @@ fi
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
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=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac

1
gradlew.bat vendored
View file

@ -26,6 +26,7 @@ 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%

View file

@ -1,6 +1,10 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven { url = 'https://maven.minecraftforge.net/' }
maven { url = "https://maven.zontreck.com/repository/internal" }
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0'
}

View file

@ -1,333 +0,0 @@
/*
*
* DISCLAIMER: This code was taken from Mantle, and will be modified to fit the needs of this mod, such as adding more heat options. This code is subject to Mantle's license of MIT.
* Despite this code being taken from, and modified/updated to be modern, all textures are my own creation
* This disclaimer is here to give credit where credit is due. The author(s) of mantle have done a absolutely fantastic job. And if Mantle gets updated this shall be removed along with future plans of extra hearts and color options.
*
*
*/
package dev.zontreck.mcmods.gui;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import dev.zontreck.mcmods.WatchMyDurability;
import dev.zontreck.mcmods.configs.WMDClientConfig;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.client.event.RenderGuiOverlayEvent;
import net.minecraftforge.client.gui.overlay.ForgeGui;
import net.minecraftforge.client.gui.overlay.GuiOverlayManager;
import net.minecraftforge.client.gui.overlay.NamedGuiOverlay;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import java.util.Random;
public class HeartsRenderer {
private static final ResourceLocation ICON_HEARTS = new ResourceLocation(WatchMyDurability.MODID,
"textures/gui/hearts.png");
private static final ResourceLocation ICON_ABSORB = new ResourceLocation(WatchMyDurability.MODID,
"textures/gui/absorb.png");
private static final ResourceLocation ICON_VANILLA = GuiComponent.GUI_ICONS_LOCATION;
private final Minecraft mc = Minecraft.getInstance();
private int playerHealth = 0;
private int lastPlayerHealth = 0;
private long healthUpdateCounter = 0;
private long lastSystemTime = 0;
private final Random rand = new Random();
private int regen;
/**
* Draws a texture to the screen
*
* @param matrixStack Matrix stack instance
* @param x X position
* @param y Y position
* @param textureX Texture X
* @param textureY Texture Y
* @param width Width to draw
* @param height Height to draw
*/
private void blit(PoseStack matrixStack, int x, int y, int textureX, int textureY, int width, int height) {
Minecraft.getInstance().gui.blit(matrixStack, x, y, textureX, textureY, width, height);
}
/* HUD */
/**
* Event listener
*
* @param event Event instance
*/
@SubscribeEvent(priority = EventPriority.LOW)
public void renderHealthbar(RenderGuiOverlayEvent.Pre event) {
NamedGuiOverlay ActualOverlay = GuiOverlayManager.findOverlay(new ResourceLocation("minecraft:player_health"));
if (ActualOverlay == null) {
if (GuiOverlayManager.getOverlays() == null) {
WatchMyDurability.LOGGER.info("Overlays non existent?!");
}
for (NamedGuiOverlay overlay : GuiOverlayManager.getOverlays()) {
// Next print
// LibZontreck.LOGGER.info("GUI OVERLAY: "+overlay.id().getPath());
if (overlay.id().getPath().equals("player_health")) {
ActualOverlay = overlay;
break;
}
}
}
if (event.isCanceled() || !WMDClientConfig.EnableExtraHearts.get() || event.getOverlay() != ActualOverlay) {
return;
}
// ensure its visible
if (!(mc.gui instanceof ForgeGui gui) || mc.options.hideGui || !gui.shouldDrawSurvivalElements()) {
return;
}
Entity renderViewEnity = this.mc.getCameraEntity();
if (!(renderViewEnity instanceof Player player)) {
return;
}
gui.setupOverlayRenderState(true, false);
this.mc.getProfiler().push("health");
// extra setup stuff from us
int left_height = gui.leftHeight;
int width = this.mc.getWindow().getGuiScaledWidth();
int height = this.mc.getWindow().getGuiScaledHeight();
int updateCounter = this.mc.gui.getGuiTicks();
// start default forge/mc rendering
// changes are indicated by comment
int health = Mth.ceil(player.getHealth());
boolean highlight = this.healthUpdateCounter > (long) updateCounter
&& (this.healthUpdateCounter - (long) updateCounter) / 3L % 2L == 1L;
if (health < this.playerHealth && player.invulnerableTime > 0) {
this.lastSystemTime = Util.getMillis();
this.healthUpdateCounter = (updateCounter + 20);
} else if (health > this.playerHealth && player.invulnerableTime > 0) {
this.lastSystemTime = Util.getMillis();
this.healthUpdateCounter = (updateCounter + 10);
}
if (Util.getMillis() - this.lastSystemTime > 1000L) {
this.playerHealth = health;
this.lastPlayerHealth = health;
this.lastSystemTime = Util.getMillis();
}
this.playerHealth = health;
int healthLast = this.lastPlayerHealth;
AttributeInstance attrMaxHealth = player.getAttribute(Attributes.MAX_HEALTH);
float healthMax = attrMaxHealth == null ? 0 : (float) attrMaxHealth.getValue();
float absorb = Mth.ceil(player.getAbsorptionAmount());
// CHANGE: simulate 10 hearts max if there's more, so vanilla only renders one
// row max
healthMax = Math.min(healthMax, 20f);
health = Math.min(health, 20);
absorb = Math.min(absorb, 20);
int healthRows = Mth.ceil((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed(updateCounter * 312871L);
int left = width / 2 - 91;
int top = height - left_height;
// change: these are unused below, unneeded? should these adjust the Forge
// variable?
// left_height += (healthRows * rowHeight);
// if (rowHeight != 10) left_height += 10 - rowHeight;
this.regen = -1;
if (player.hasEffect(MobEffects.REGENERATION)) {
this.regen = updateCounter % 25;
}
assert this.mc.level != null;
final int TOP = 9 * (this.mc.level.getLevelData().isHardcore() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (player.hasEffect(MobEffects.POISON))
MARGIN += 36;
else if (player.hasEffect(MobEffects.WITHER))
MARGIN += 72;
float absorbRemaining = absorb;
PoseStack matrixStack = event.getPoseStack();
for (int i = Mth.ceil((healthMax + absorb) / 2.0F) - 1; i >= 0; --i) {
int row = Mth.ceil((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += this.rand.nextInt(2);
if (i == this.regen)
y -= 2;
this.blit(matrixStack, x, y, BACKGROUND, TOP, 9, 9);
if (highlight) {
if (i * 2 + 1 < healthLast) {
this.blit(matrixStack, x, y, MARGIN + 54, TOP, 9, 9); // 6
} else if (i * 2 + 1 == healthLast) {
this.blit(matrixStack, x, y, MARGIN + 63, TOP, 9, 9); // 7
}
}
if (absorbRemaining > 0.0F) {
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F) {
this.blit(matrixStack, x, y, MARGIN + 153, TOP, 9, 9); // 17
absorbRemaining -= 1.0F;
} else {
this.blit(matrixStack, x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
} else {
if (i * 2 + 1 < health) {
this.blit(matrixStack, x, y, MARGIN + 36, TOP, 9, 9); // 4
} else if (i * 2 + 1 == health) {
this.blit(matrixStack, x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
}
this.renderExtraHearts(matrixStack, left, top, player);
this.renderExtraAbsorption(matrixStack, left, top - rowHeight, player);
RenderSystem.setShaderTexture(0, ICON_VANILLA);
gui.leftHeight += 10;
if (absorb > 0) {
gui.leftHeight += 10;
}
event.setCanceled(true);
RenderSystem.disableBlend();
this.mc.getProfiler().pop();
MinecraftForge.EVENT_BUS
.post(new RenderGuiOverlayEvent.Post(mc.getWindow(), matrixStack, event.getPartialTick(), ActualOverlay));
}
/**
* Gets the texture from potion effects
*
* @param player Player instance
* @return Texture offset for potion effects
*/
private int getPotionOffset(Player player) {
int potionOffset = 0;
MobEffectInstance potion = player.getEffect(MobEffects.WITHER);
if (potion != null) {
potionOffset = 18;
}
potion = player.getEffect(MobEffects.POISON);
if (potion != null) {
potionOffset = 9;
}
assert this.mc.level != null;
if (this.mc.level.getLevelData().isHardcore()) {
potionOffset += 27;
}
return potionOffset;
}
/**
* Renders the health above 10 hearts
*
* @param matrixStack Matrix stack instance
* @param xBasePos Health bar top corner
* @param yBasePos Health bar top corner
* @param player Player instance
*/
private void renderExtraHearts(PoseStack matrixStack, int xBasePos, int yBasePos, Player player) {
int potionOffset = this.getPotionOffset(player);
// Extra hearts
RenderSystem.setShaderTexture(0, ICON_HEARTS);
int hp = Mth.ceil(player.getHealth());
this.renderCustomHearts(matrixStack, xBasePos, yBasePos, potionOffset, hp, false);
}
/**
* Renders the absorption health above 10 hearts
*
* @param matrixStack Matrix stack instance
* @param xBasePos Health bar top corner
* @param yBasePos Health bar top corner
* @param player Player instance
*/
private void renderExtraAbsorption(PoseStack matrixStack, int xBasePos, int yBasePos, Player player) {
int potionOffset = this.getPotionOffset(player);
// Extra hearts
RenderSystem.setShaderTexture(0, ICON_ABSORB);
int absorb = Mth.ceil(player.getAbsorptionAmount());
this.renderCustomHearts(matrixStack, xBasePos, yBasePos, potionOffset, absorb, true);
}
/**
* Gets the texture offset from the regen effect
*
* @param i Heart index
* @param offset Current offset
*/
private int getYRegenOffset(int i, int offset) {
return i + offset == this.regen ? -2 : 0;
}
/**
* Shared logic to render custom hearts
*
* @param matrixStack Matrix stack instance
* @param xBasePos Health bar top corner
* @param yBasePos Health bar top corner
* @param potionOffset Offset from the potion effect
* @param count Number to render
* @param absorb If true, render absorption hearts
*/
private void renderCustomHearts(PoseStack matrixStack, int xBasePos, int yBasePos, int potionOffset, int count,
boolean absorb) {
int regenOffset = absorb ? 10 : 0;
for (int iter = 0; iter < count / 20; iter++) {
int renderHearts = (count - 20 * (iter + 1)) / 2;
int heartIndex = iter % 11;
if (renderHearts > 10) {
renderHearts = 10;
}
for (int i = 0; i < renderHearts; i++) {
int y = this.getYRegenOffset(i, regenOffset);
if (absorb) {
this.blit(matrixStack, xBasePos + 8 * i, yBasePos + y, 0, 54, 9, 9);
}
this.blit(matrixStack, xBasePos + 8 * i, yBasePos + y, 18 * heartIndex, potionOffset, 9, 9);
}
if (count % 2 == 1 && renderHearts < 10) {
int y = this.getYRegenOffset(renderHearts, regenOffset);
if (absorb) {
this.blit(matrixStack, xBasePos + 8 * renderHearts, yBasePos + y, 0, 54, 9, 9);
}
this.blit(matrixStack, xBasePos + 8 * renderHearts, yBasePos + y, 9 + 18 * heartIndex, potionOffset, 9, 9);
}
}
}
}

View file

@ -1,11 +1,21 @@
package dev.zontreck.mcmods;
package dev.zontreck.wmd;
import com.mojang.logging.LogUtils;
import dev.zontreck.ariaslib.util.DelayedExecutorService;
import dev.zontreck.libzontreck.chat.ChatColor;
import dev.zontreck.mcmods.configs.WMDClientConfig;
import dev.zontreck.wmd.checkers.CheckHealth;
import dev.zontreck.wmd.checkers.CheckHunger;
import dev.zontreck.wmd.checkers.CheckInventory;
import dev.zontreck.wmd.commands.ModCommands;
import dev.zontreck.wmd.configs.WMDClientConfig;
import dev.zontreck.wmd.networking.ModMessages;
import dev.zontreck.wmd.types.Health;
import dev.zontreck.wmd.types.Hunger;
import dev.zontreck.wmd.types.ItemRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.User;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
@ -17,8 +27,6 @@ import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent.LoggedInEvent;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent.LoggedOutEvent;
import java.util.Timer;
@ -38,13 +46,13 @@ public class WatchMyDurability
public static boolean isInGame = false; // This locks the timer thread
public static ItemRegistry REGISTRY;
public static Health LastHealth;
public static String WMDPrefix;
public static Hunger LastHunger;
public static boolean WMD_SERVER_AVAILABLE =false;
public WatchMyDurability()
{
WatchMyDurability.WMDPrefix = ChatColor.doColors("!Dark_Gray![!Bold!!Dark_Green!WMD!Reset!!Dark_Gray!]!reset!");
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
@ -52,17 +60,19 @@ public class WatchMyDurability
modEventBus.addListener(this::commonSetup);
ModLoadingContext.get().registerConfig(Type.CLIENT, WMDClientConfig.SPEC, "watchmydurability-client.toml");
//MinecraftForge.EVENT_BUS.register(new HeartsRenderer());
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
MinecraftForge.EVENT_BUS.register(new ModCommands());
}
private void commonSetup(final FMLCommonSetupEvent event)
{
// Some common setup code
//LOGGER.info("HELLO FROM COMMON SETUP");
ModMessages.register();
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
public void onServerStarting(ServerStartingEvent event)
@ -72,7 +82,7 @@ public class WatchMyDurability
}
// You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public static class ClientModEvents
{
static Timer time = new Timer();
@ -80,42 +90,54 @@ public class WatchMyDurability
@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event)
{
LOGGER.info(WMDPrefix+": : : CLIENT SETUP : : :");
LOGGER.info(": : : CLIENT SETUP : : :");
// Some client setup code
//LOGGER.info("HELLO FROM CLIENT SETUP");
//LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName());
WatchMyDurability.CurrentUser = Minecraft.getInstance().getUser();
DelayedExecutorService.setup();
time.schedule(new CheckInventory(), WMDClientConfig.TimerVal.get()*1000, WMDClientConfig.TimerVal.get()*1000);
//time.schedule(new CheckInventory(),
//WMDClientConfig.TimerVal.get()*1000,
//WMDClientConfig.TimerVal.get()*1000);
ItemRegistry.Initialize();
}
}
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public static class ClientEvents
{
@SubscribeEvent
public static void onJoin(LoggedInEvent event){
public static void onJoin(ClientPlayerNetworkEvent.LoggingIn event){
// Joined
//LOGGER.info("PLAYER LOGGED IN");
LOGGER.info(WMDPrefix+": : : PLAYER LOGGED IN : : :");
LOGGER.info(": : : PLAYER LOGGED IN : : :");
WatchMyDurability.isInGame=true;
DelayedExecutorService.start();
DelayedExecutorService.getInstance().scheduleRepeating(CheckInventory.getInstance(), WMDClientConfig.TimerVal.get());
DelayedExecutorService.getInstance().scheduleRepeating(CheckHealth.getInstance(), WMDClientConfig.TimerVal.get());
DelayedExecutorService.getInstance().scheduleRepeating(CheckHunger.getInstance(), WMDClientConfig.TimerVal.get());
}
@SubscribeEvent
public static void onLeave(LoggedOutEvent event){
public static void onLeave(ClientPlayerNetworkEvent.LoggingOut event){
//LOGGER.info("PLAYER LOGGED OUT");
LOGGER.info(WMDPrefix+": : : PLAYER LOGGED OUT : : :");
LOGGER.info(": : : PLAYER LOGGED OUT : : :");
WatchMyDurability.isInGame=false;
WatchMyDurability.WMD_SERVER_AVAILABLE=false;
DelayedExecutorService.stop();
}
@SubscribeEvent
public static void onClone(ClientPlayerNetworkEvent.RespawnEvent event)
public static void onClone(ClientPlayerNetworkEvent.Clone event)
{
LOGGER.info(WMDPrefix+": : : : PLAYER RESPAWNED OR MOVED TO A NEW WORLD : : : :");
LOGGER.info(": : : : PLAYER RESPAWNED OR MOVED TO A NEW WORLD : : : :");
}
}

View file

@ -0,0 +1,52 @@
package dev.zontreck.wmd.checkers;
import dev.zontreck.ariaslib.terminal.Task;
import dev.zontreck.libzontreck.chat.ChatColor;
import dev.zontreck.wmd.types.Health;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.configs.WMDClientConfig;
import dev.zontreck.wmd.utils.client.Helpers;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
public class CheckHealth extends Task
{
private static CheckHealth inst = new CheckHealth();
public static CheckHealth getInstance()
{
return inst;
}
public CheckHealth() {
super("CheckHealth", true);
}
@Override
public void run() {
// Hijack this timer so we dont need to register yet another
if(!WMDClientConfig.EnableHealthAlert.get())return;
Health current = Health.of(Minecraft.getInstance().player);
if(WatchMyDurability.LastHealth == null)WatchMyDurability.LastHealth = current;
else{
if(current.identical(WatchMyDurability.LastHealth))return;
}
// Good to proceed
if(current.shouldGiveAlert())
{
String Msg = ChatColor.doColors("!Dark_Red!!bold!You need to eat!");
Component chat = Component.literal(Msg);
Minecraft.getInstance().player.displayClientMessage(chat, false);
SoundEvent sv = SoundEvents.WARDEN_ROAR; // It sounds like a growling stomach
Helpers.Soundify(sv);
}
WatchMyDurability.LastHealth=current;
}
}

View file

@ -0,0 +1,50 @@
package dev.zontreck.wmd.checkers;
import dev.zontreck.ariaslib.terminal.Task;
import dev.zontreck.libzontreck.chat.ChatColor;
import dev.zontreck.wmd.types.Hunger;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.configs.WMDClientConfig;
import dev.zontreck.wmd.utils.client.Helpers;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
public class CheckHunger extends Task
{
private static CheckHunger inst = new CheckHunger();
public static CheckHunger getInstance()
{
return inst;
}
public CheckHunger()
{
super("CheckHunger", true);
}
@Override
public void run() {
if(!WMDClientConfig.EnableHungerAlert.get()) return;
Hunger current = Hunger.of(Minecraft.getInstance().player);
if(WatchMyDurability.LastHunger == null)WatchMyDurability.LastHunger = new Hunger();
if(current.identical()) return;
if(current.shouldGiveAlert())
{
String Msg = ChatColor.doColors("!Dark_Red!!bold!You need to eat!");
Component chat = Component.literal(Msg);
Minecraft.getInstance().player.displayClientMessage(chat, false);
SoundEvent sv = SoundEvents.WARDEN_ROAR; // It sounds like a growling stomach
Helpers.Soundify(sv);
}
WatchMyDurability.LastHunger = current;
}
}

View file

@ -1,36 +1,47 @@
package dev.zontreck.mcmods;
package dev.zontreck.wmd.checkers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import dev.zontreck.ariaslib.terminal.Task;
import dev.zontreck.libzontreck.chat.ChatColor;
import dev.zontreck.libzontreck.chat.ChatColorFactory;
import dev.zontreck.libzontreck.chat.HoverTip;
import dev.zontreck.libzontreck.chat.ChatColor.ColorOptions;
import dev.zontreck.mcmods.configs.WMDClientConfig;
import dev.zontreck.libzontreck.util.ChatHelpers;
import dev.zontreck.wmd.types.ItemRegistry;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.configs.WMDClientConfig;
import dev.zontreck.wmd.utils.client.Helpers;
import net.minecraft.client.Minecraft;
import net.minecraft.core.NonNullList;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
public class CheckInventory extends TimerTask
{
public class CheckInventory extends Task {
private static final CheckInventory inst = new CheckInventory();
public CheckInventory() {
super("checkinv", true);
}
public static CheckInventory getInstance(){
return inst;
}
@Override
public void run() {
if(!WMDClientConfig.EnableToolWatcher.get()) return;
try {
if(!WatchMyDurability.isInGame)return;
//WatchMyDurability.LOGGER.info("TICKING CHECK INVENTORY EVENT");
// Get the player inventory
Inventory inv = Minecraft.getInstance().player.getInventory();
@ -49,27 +60,6 @@ public class CheckInventory extends TimerTask
}
// Hijack this timer so we dont need to register yet another
if(!WMDClientConfig.EnableHealthAlert.get())return;
Health current = Health.of(Minecraft.getInstance().player);
if(WatchMyDurability.LastHealth == null)WatchMyDurability.LastHealth = current;
else{
if(current.identical(WatchMyDurability.LastHealth))return;
}
// Good to proceed
if(current.shouldGiveAlert())
{
String Msg = ChatColor.doColors("!Dark_Red!!bold!You need to eat!");
Component chat = new TextComponent(Msg);
Minecraft.getInstance().player.displayClientMessage(chat, false);
SoundEvent sv = SoundEvents.WOLF_GROWL; // It sounds like a growling stomach
Soundify(sv);
}
WatchMyDurability.LastHealth=current;
}
public void PushItems(String type, List<ItemStack> stack)
@ -90,12 +80,6 @@ public class CheckInventory extends TimerTask
ItemRegistry.register(type,items);
}
public void Soundify(SoundEvent sound)
{
//WatchMyDurability.LOGGER.info("PLAY ALERT SOUND");
Minecraft.getInstance().player.playSound(sound, 1.0f, 1.0f);
}
public void checkList(String type, NonNullList<ItemStack> stacks){
Integer slotNum = 0;
//boolean ret=false;
@ -114,15 +98,15 @@ public class CheckInventory extends TimerTask
String entryStr = WMDClientConfig.alertMessages.get().get(idx);
if(percent <= entry){
String replaced = WatchMyDurability.WMDPrefix + ChatColor.DARK_RED + entryStr.replaceAll("!item!", is1.getDisplayName().getString());
String replaced = ChatColor.doColors(WMDClientConfig.WMD_PREFIX.get()) + ChatColor.DARK_RED + entryStr.replaceAll("!item!", is1.getDisplayName().getString());
WatchMyDurability.LOGGER.info("Enqueue alert for an item. Playing sound for item: "+is1.getDisplayName().getString());
SoundEvent theSound = SoundEvents.ITEM_BREAK;
Soundify(theSound);
Helpers.Soundify(theSound);
MutableComponent X = new TextComponent(replaced);
MutableComponent X = Component.literal(replaced);
HoverEvent he = HoverTip.getItem(is1);
Style s = Style.EMPTY.withFont(Style.DEFAULT_FONT).withHoverEvent(he);

View file

@ -0,0 +1,14 @@
package dev.zontreck.wmd.commands;
import dev.zontreck.wmd.commands.impl.SettingsCommand;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
public class ModCommands
{
@SubscribeEvent
public void register(final RegisterCommandsEvent event)
{
SettingsCommand.register(event.getDispatcher());
}
}

View file

@ -0,0 +1,21 @@
package dev.zontreck.wmd.commands.impl;
import com.mojang.brigadier.CommandDispatcher;
import dev.zontreck.wmd.networking.ModMessages;
import dev.zontreck.wmd.networking.packets.s2c.RequestClientConfig;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
public class SettingsCommand
{
public static void register(CommandDispatcher<CommandSourceStack> dispatcher)
{
dispatcher.register(Commands.literal("wmdsettings").executes(c->settingsPrompt(c.getSource())));
}
public static int settingsPrompt(CommandSourceStack sender)
{
ModMessages.sendToPlayer(new RequestClientConfig(), sender.getPlayer());
return 0;
}
}

View file

@ -1,8 +1,9 @@
package dev.zontreck.mcmods.configs;
package dev.zontreck.wmd.configs;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.nbt.CompoundTag;
import net.minecraftforge.common.ForgeConfigSpec;
public class WMDClientConfig {
@ -12,8 +13,12 @@ public class WMDClientConfig {
public static ForgeConfigSpec.ConfigValue<List<Integer>> alertPercents;
public static ForgeConfigSpec.ConfigValue<List<String>> alertMessages;
public static ForgeConfigSpec.ConfigValue<Integer> TimerVal;
//public static ForgeConfigSpec.ConfigValue<Boolean> EnableExtraHearts;
public static ForgeConfigSpec.ConfigValue<Boolean> EnableHealthAlert;
public static ForgeConfigSpec.ConfigValue<Boolean> EnableHungerAlert;
public static ForgeConfigSpec.ConfigValue<Boolean> EnableToolWatcher;
public static ForgeConfigSpec.ConfigValue<String> WMD_PREFIX;
static{
List<Integer> alerts1 = new ArrayList<>();
@ -33,10 +38,41 @@ public class WMDClientConfig {
BUILDER.pop();
BUILDER.push("General");
//EnableExtraHearts = BUILDER.comment("Whether to enable the extra hearts rendering").define("compress_hearts", false);
EnableHealthAlert = BUILDER.comment("The following was added for a friend. If you need reminders to eat in order to heal, turn the below option on").define("watchMyHunger", false);
EnableHealthAlert = BUILDER.comment("The following was added for a friend. If you need reminders to eat in order to heal, turn the below option on").define("watchMyHealth", false);
EnableHungerAlert = BUILDER.comment("This is a newer setting to watch your hunger status instead of your hunger to alert when you need to eat").define("watchMyHunger", false);
EnableToolWatcher = BUILDER.comment("Enable watching tool durability").define("watchDurability", true);
BUILDER.pop();
BUILDER.push("Messages");
WMD_PREFIX = BUILDER.comment("The prefix string for WMD").define("prefix", "!Dark_Gray![!Bold!!Dark_Green!WMD!Reset!!Dark_Gray!]!Reset!");
SPEC=BUILDER.build();
}
public static CompoundTag serialize()
{
CompoundTag ret = new CompoundTag();
ret.putBoolean("watchMyHealth", EnableHealthAlert.get());
ret.putBoolean("watchMyHunger", EnableHungerAlert.get());
ret.putBoolean("watchDurability", EnableToolWatcher.get());
return ret;
}
public static void deserialize(CompoundTag tag)
{
EnableHealthAlert.set(tag.getBoolean("watchMyHealth"));
EnableHealthAlert.save();
EnableHungerAlert.set(tag.getBoolean("watchMyHunger"));
EnableHungerAlert.save();
EnableToolWatcher.set(tag.getBoolean("watchDurability"));
EnableToolWatcher.save();
}
}

View file

@ -0,0 +1,17 @@
package dev.zontreck.wmd.events;
import dev.zontreck.libzontreck.LibZontreck;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.networking.packets.s2c.WMDServerAvailable;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
public class EventHandler
{
@SubscribeEvent
public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event)
{
WMDServerAvailable avail = new WMDServerAvailable();
avail.send(event.getEntity().getUUID());
}
}

View file

@ -0,0 +1,76 @@
package dev.zontreck.wmd.networking;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.networking.packets.c2s.ClientConfigResponse;
import dev.zontreck.wmd.networking.packets.s2c.*;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;
public class ModMessages
{
private static SimpleChannel channel;
private static int PACKET_ID = 0;
private static int id()
{
return PACKET_ID++;
}
public static void register()
{
SimpleChannel net = NetworkRegistry.ChannelBuilder.named(new ResourceLocation(WatchMyDurability.MODID, "messages"))
.networkProtocolVersion(()->"1.0")
.clientAcceptedVersions(s->true)
.serverAcceptedVersions(s->true)
.simpleChannel();
channel = net;
net.messageBuilder(WMDServerAvailable.class, id(), NetworkDirection.PLAY_TO_CLIENT)
.encoder(WMDServerAvailable::toBytes)
.decoder(WMDServerAvailable::new)
.consumerMainThread(WMDServerAvailable::handle)
.add();
net.messageBuilder(S2CResetConfig.class, id(), NetworkDirection.PLAY_TO_CLIENT)
.encoder(S2CResetConfig::toBytes)
.decoder(S2CResetConfig::new)
.consumerMainThread(S2CResetConfig::handle)
.add();
net.messageBuilder(RequestClientConfig.class, id(), NetworkDirection.PLAY_TO_CLIENT)
.encoder(RequestClientConfig::toBytes)
.decoder(RequestClientConfig::new)
.consumerMainThread(RequestClientConfig::handle)
.add();
net.messageBuilder(ClientConfigResponse.class, id(), NetworkDirection.PLAY_TO_SERVER)
.encoder(ClientConfigResponse::toBytes)
.decoder(ClientConfigResponse::new)
.consumerMainThread(ClientConfigResponse::handle)
.add();
net.messageBuilder(PushClientConfigUpdate.class, id(), NetworkDirection.PLAY_TO_CLIENT)
.encoder(PushClientConfigUpdate::toBytes)
.decoder(PushClientConfigUpdate::new)
.consumerMainThread(PushClientConfigUpdate::handle)
.add();
}
public static <MSG> void sendToServer(MSG message){
channel.sendToServer(message);
}
public static <MSG> void sendToPlayer(MSG message, ServerPlayer player)
{
channel.send(PacketDistributor.PLAYER.with(()->player), message);
}
public static <MSG> void sendToAll(MSG message)
{
channel.send(PacketDistributor.ALL.noArg(), message);
}
}

View file

@ -0,0 +1,130 @@
package dev.zontreck.wmd.networking.packets.c2s;
import dev.zontreck.libzontreck.chat.ChatColor;
import dev.zontreck.libzontreck.chestgui.ChestGUI;
import dev.zontreck.libzontreck.chestgui.ChestGUIButton;
import dev.zontreck.libzontreck.chestgui.ChestGUIIdentifier;
import dev.zontreck.libzontreck.items.ModItems;
import dev.zontreck.libzontreck.lore.LoreContainer;
import dev.zontreck.libzontreck.lore.LoreEntry;
import dev.zontreck.libzontreck.util.ServerUtilities;
import dev.zontreck.libzontreck.vectors.Vector2i;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.configs.WMDClientConfig;
import dev.zontreck.wmd.networking.ModMessages;
import dev.zontreck.wmd.networking.packets.s2c.PushClientConfigUpdate;
import dev.zontreck.wmd.networking.packets.s2c.RequestClientConfig;
import dev.zontreck.wmd.networking.packets.s2c.S2CResetConfig;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraftforge.network.NetworkEvent;
import java.util.UUID;
import java.util.function.Supplier;
public class ClientConfigResponse {
public CompoundTag tag;
public UUID id;
public ClientConfigResponse(FriendlyByteBuf buf) {
tag = buf.readAnySizeNbt();
id = buf.readUUID();
}
public ClientConfigResponse(UUID playerID) {
tag = WMDClientConfig.serialize();
id = playerID;
}
public void toBytes(FriendlyByteBuf buf) {
buf.writeNbt(tag);
buf.writeUUID(id);
}
public void handle(Supplier<NetworkEvent.Context> supplier) {
NetworkEvent.Context ctx = supplier.get();
ctx.enqueueWork(() -> {
// Open config editor for player
boolean enableHealth = tag.getBoolean("watchMyHealth");
boolean enableHunger = tag.getBoolean("watchMyHunger");
boolean enableDurability = tag.getBoolean("watchDurability");
ServerPlayer player = ServerUtilities.getPlayerByID(id.toString());
try {
ChestGUI prompt = ChestGUI.builder().withGUIId(new ChestGUIIdentifier("wmdsettings")).withPlayer(player.getUUID()).withTitle("WMD Settings");
ItemStack wtd = new ItemStack(Items.DIAMOND_PICKAXE, 1);
wtd.setHoverName(Component.literal("Watch Tool Durability"));
prompt.withButton(new ChestGUIButton(wtd, (stack, container, lore) -> {
var wd = !tag.getBoolean("watchDurability");
tag.putBoolean("watchDurability", wd);
ModMessages.sendToPlayer(new PushClientConfigUpdate(tag), player);
lore.miscData.loreData.get(0).text = ChatColor.doColors("!Dark_Green!Status: " + (wd ? "!Dark_Green!Enabled" : "!Dark_Red!Disabled"));
lore.commitLore();
}, new Vector2i(0, 0))
.withInfo(new LoreEntry.Builder().text(ChatColor.doColors("!Dark_Green!Status: " + (enableDurability ? "!Dark_Green!Enabled" : "!Dark_Red!Disabled"))).build())
);
ItemStack wmhunger = new ItemStack(Items.APPLE, 1);
wmhunger.setHoverName(Component.literal("Watch My Hunger"));
prompt.withButton(new ChestGUIButton(wmhunger, (stack, container, lore) -> {
var eh = !tag.getBoolean("watchMyHunger");
tag.putBoolean("watchMyHunger", eh);
ModMessages.sendToPlayer(new PushClientConfigUpdate(tag), player);
lore.miscData.loreData.get(0).text = ChatColor.doColors("!Dark_Green!Status: " + (eh ? "!Dark_Green!Enabled" : "!Dark_Red!Disabled"));
lore.commitLore();
}, new Vector2i(0, 1))
.withInfo(new LoreEntry.Builder().text(ChatColor.doColors("!Dark_Green!Status: " + (enableHunger ? "!Dark_Green!Enabled" : "!Dark_Red!Disabled"))).build())
);
ItemStack wmhealth = new ItemStack(Items.PUFFERFISH, 1);
wmhealth.setHoverName(Component.literal("Watch My Health"));
prompt.withButton(new ChestGUIButton(wmhealth, (stack, container, lore) -> {
var eh = !tag.getBoolean("watchMyHealth");
tag.putBoolean("watchMyHealth", eh);
ModMessages.sendToPlayer(new PushClientConfigUpdate(tag), player);
lore.miscData.loreData.get(0).text = ChatColor.doColors("!Dark_Green!Status: " + (eh ? "!Dark_Green!Enabled" : "!Dark_Red!Disabled"));
lore.commitLore();
}, new Vector2i(0, 2))
.withInfo(new LoreEntry.Builder().text(ChatColor.doColors("!Dark_Green!Status: " + (enableHealth ? "!Dark_Green!Enabled" : "!Dark_Red!Disabled"))).build())
);
prompt.withButton(new ChestGUIButton(ModItems.CHESTGUI_RESET.get(), "Reset", (stack, container, lore) -> {
ModMessages.sendToPlayer(new S2CResetConfig(), ServerUtilities.getPlayerByID(id.toString()));
prompt.close();
ModMessages.sendToPlayer(new RequestClientConfig(), player);
}, new Vector2i(2, 4)));
prompt.hasReset = false;
prompt.open();
} catch (Exception e) {
WatchMyDurability.LOGGER.error(e.getMessage());
e.printStackTrace();
}
});
}
}

View file

@ -0,0 +1,36 @@
package dev.zontreck.wmd.networking.packets.s2c;
import dev.zontreck.wmd.configs.WMDClientConfig;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import java.util.function.Supplier;
public class PushClientConfigUpdate
{
public CompoundTag tag;
public PushClientConfigUpdate(FriendlyByteBuf buf)
{
tag = buf.readAnySizeNbt();
}
public PushClientConfigUpdate(CompoundTag tag)
{
this.tag=tag;
}
public void toBytes(FriendlyByteBuf buf)
{
buf.writeNbt(tag);
}
public void handle(Supplier<NetworkEvent.Context> supplier)
{
NetworkEvent.Context ctx = supplier.get();
ctx.enqueueWork(()->{
WMDClientConfig.deserialize(tag);
});
}
}

View file

@ -0,0 +1,35 @@
package dev.zontreck.wmd.networking.packets.s2c;
import dev.zontreck.wmd.networking.ModMessages;
import dev.zontreck.wmd.networking.packets.c2s.ClientConfigResponse;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import java.util.function.Supplier;
public class RequestClientConfig
{
public RequestClientConfig(FriendlyByteBuf buf)
{
}
public RequestClientConfig(){
}
public void toBytes(FriendlyByteBuf buf){
}
public void handle(Supplier<NetworkEvent.Context> supplier)
{
NetworkEvent.Context ctx = supplier.get();
ctx.enqueueWork(()->{
ClientConfigResponse reply = new ClientConfigResponse(Minecraft.getInstance().player.getUUID());
ModMessages.sendToServer(reply);
});
}
}

View file

@ -0,0 +1,45 @@
package dev.zontreck.wmd.networking.packets.s2c;
import dev.zontreck.wmd.configs.WMDClientConfig;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import java.util.function.Supplier;
public class S2CResetConfig
{
public S2CResetConfig(FriendlyByteBuf buf)
{
}
public S2CResetConfig()
{
}
public void toBytes(FriendlyByteBuf buf)
{
}
public void handle(Supplier<NetworkEvent.Context> supplier)
{
NetworkEvent.Context ctx = supplier.get();
ctx.enqueueWork(()->
{
WMDClientConfig.WMD_PREFIX.set(WMDClientConfig.WMD_PREFIX.getDefault());
WMDClientConfig.WMD_PREFIX.save();
WMDClientConfig.EnableHealthAlert.set(WMDClientConfig.EnableHealthAlert.getDefault());
WMDClientConfig.EnableHealthAlert.save();
WMDClientConfig.EnableHungerAlert.set(WMDClientConfig.EnableHungerAlert.getDefault());
WMDClientConfig.EnableHealthAlert.save();
WMDClientConfig.EnableToolWatcher.set(WMDClientConfig.EnableToolWatcher.getDefault());
WMDClientConfig.EnableToolWatcher.save();
});
}
}

View file

@ -0,0 +1,42 @@
package dev.zontreck.wmd.networking.packets.s2c;
import dev.zontreck.libzontreck.util.ServerUtilities;
import dev.zontreck.wmd.WatchMyDurability;
import dev.zontreck.wmd.networking.ModMessages;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import java.util.UUID;
import java.util.function.Supplier;
public class WMDServerAvailable
{
public WMDServerAvailable(FriendlyByteBuf buf)
{
}
public WMDServerAvailable()
{
}
public void toBytes(FriendlyByteBuf buf)
{
}
public void handle(Supplier<NetworkEvent.Context> supplier)
{
NetworkEvent.Context ctx = supplier.get();
ctx.enqueueWork(()->{
WatchMyDurability.WMD_SERVER_AVAILABLE =true;
});
}
public void send(UUID ID)
{
ModMessages.sendToPlayer(this, ServerUtilities.getPlayerByID(ID.toString()));
}
}

View file

@ -1,4 +1,4 @@
package dev.zontreck.mcmods;
package dev.zontreck.wmd.types;
import net.minecraft.world.entity.player.Player;

View file

@ -0,0 +1,28 @@
package dev.zontreck.wmd.types;
import dev.zontreck.wmd.WatchMyDurability;
import net.minecraft.world.entity.player.Player;
public class Hunger
{
public boolean needsToEat;
public static Hunger of(Player player)
{
Hunger hunger = new Hunger();
hunger.needsToEat = player.getFoodData().needsFood();
return hunger;
}
public boolean shouldGiveAlert()
{
if(needsToEat && !WatchMyDurability.LastHunger.needsToEat) return true;
else return false;
}
public boolean identical()
{
if(needsToEat == WatchMyDurability.LastHunger.needsToEat) return true;
return false;
}
}

View file

@ -1,8 +1,9 @@
package dev.zontreck.mcmods;
package dev.zontreck.wmd.types;
import java.util.HashMap;
import java.util.Map;
import dev.zontreck.wmd.WatchMyDurability;
import net.minecraft.world.item.ItemStack;
public class ItemRegistry {

View file

@ -0,0 +1,14 @@
package dev.zontreck.wmd.utils.client;
import net.minecraft.client.Minecraft;
import net.minecraft.sounds.SoundEvent;
public class Helpers
{
public static void Soundify(SoundEvent sound)
{
//WatchMyDurability.LOGGER.info("PLAY ALERT SOUND");
Minecraft.getInstance().player.playSound(sound, 1.0f, 1.0f);
}
}

View file

@ -6,32 +6,30 @@
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="[40,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
loaderVersion="${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="GPL-v2"
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="watchmydurability" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
# ${file.jarVersion} will substitute the value of the Implementation-Version as read from the mod's JAR file metadata
# see the associated build.gradle script for how to populate this completely automatically during a build
version="1.1.2.7" #mandatory
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="Watch My Durability" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://mcforge.readthedocs.io/en/latest/gettingstarted/autoupdate/
displayName="${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
credits="zontreck @ ZNI Creations" #optional
#credits="" #optional
# A text field displayed in the mod UI
authors="zontreck" #optional
authors="${mod_authors}" #optional
# Display Test controls the display for your mod in the server connection screen
# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod.
# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod.
@ -41,36 +39,38 @@ authors="zontreck" #optional
#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional)
# The description text for the mod (multi line!) (#mandatory)
description='''
This mod watches durability of an item.
This is most useful for armor or weapons to alert you to the fact that your armor or weapon might break soon.
Edit the config file to customize the alerts
'''
description='''${mod_description}'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.watchmydurability]] #optional
[[dependencies.${mod_id}]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="[40,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
versionRange="${forge_version_range}" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT or SERVER
side="CLIENT"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.watchmydurability]]
[[dependencies.${mod_id}]]
modId="minecraft"
mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[1.18.2,1.19)"
versionRange="${minecraft_version_range}"
ordering="NONE"
side="CLIENT"
[[dependencies.watchmydurability]]
side="BOTH"
[[dependencies.${mod_id}]]
modId="libzontreck"
mandatory=true
versionRange="[1.0.4.9,1.0.5.0)"
versionRange="[1.10,1.11)"
ordering="NONE"
side="CLIENT"
side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5 KiB

View file

@ -1,8 +1,8 @@
{
"pack": {
"description": "Watch My Durability Resources",
"pack_format": 9,
"forge:resource_pack_format": 9,
"forge:data_pack_format": 9
"description": {
"text": "${mod_id} resources"
},
"pack_format": 15
}
}