Compare commits

..

No commits in common. "main" and "v1.1.2.7" have entirely different histories.

31 changed files with 896 additions and 1267 deletions

View file

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

View file

@ -1,17 +1,12 @@
plugins { plugins {
id 'eclipse' id 'eclipse'
id 'idea'
id 'maven-publish' id 'maven-publish'
id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'net.minecraftforge.gradle' version '5.1.+'
id 'org.parchmentmc.librarian.forgegradle' version '1.+'
} }
version = mod_version version = "${mc_version}-${myversion}"
group = mod_group_id group = 'dev.zontreck' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'WatchMyDurability'
base {
archivesName = mod_id
}
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17) java.toolchain.languageVersion = JavaLanguageVersion.of(17)
@ -27,40 +22,18 @@ minecraft {
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md // See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
// //
// Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge // Parchment is an unofficial project maintained by ParchmentMC, separate from MinecraftForge
// Additional setup is needed to use their mappings: https://parchmentmc.org/docs/getting-started // Additional setup is needed to use their mappings: https://github.com/ParchmentMC/Parchment/wiki/Getting-Started
// //
// Use non-default mappings at your own risk. They may not always work. // 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. // Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: mapping_channel, version: mapping_version mappings channel: 'official', version: "${mc_version}"
// 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. // accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Currently, this location cannot be changed from the default.
// 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. // Default run configurations.
// These can be tweaked, removed, or duplicated as needed. // These can be tweaked, removed, or duplicated as needed.
runs { runs {
// applies to all the run configs below client {
configureEach {
workingDirectory project.file('run') workingDirectory project.file('run')
// Recommended logging data for a userdev environment // Recommended logging data for a userdev environment
@ -75,36 +48,66 @@ minecraft {
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug' property 'forge.logging.console.level', 'debug'
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', 'watchmydurability'
mods { mods {
"${mod_id}" { watchmydurability {
source sourceSets.main source sourceSets.main
} }
} }
} }
client {
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
property 'forge.enabledGameTestNamespaces', mod_id
}
server { server {
property 'forge.enabledGameTestNamespaces', mod_id workingDirectory project.file('run')
args '--nogui'
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
property 'forge.enabledGameTestNamespaces', 'watchmydurability'
mods {
watchmydurability {
source sourceSets.main
}
}
} }
// This run config launches GameTestServer and runs all registered gametests, then exits. // This run config launches GameTestServer and runs all registered gametests, then exits.
// By default, the server will crash when no gametests are provided. // 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. // The gametest system is also enabled by default for other run configs under the /test command.
gameTestServer { gameTestServer {
property 'forge.enabledGameTestNamespaces', mod_id workingDirectory project.file('run')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
property 'forge.enabledGameTestNamespaces', 'watchmydurability'
mods {
watchmydurability {
source sourceSets.main
}
}
} }
data { data {
// example of overriding the workingDirectory set in configureEach above workingDirectory project.file('run')
workingDirectory project.file('run-data')
property 'forge.logging.markers', 'REGISTRIES'
property 'forge.logging.console.level', 'debug'
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') args '--mod', 'watchmydurability', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
mods {
watchmydurability {
source sourceSets.main
}
}
} }
} }
} }
@ -116,105 +119,62 @@ repositories {
// Put repositories for dependencies here // Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you // 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 { // flatDir {
// dir 'libs' // dir 'libs'
// } // }
maven { maven {
name = "Aria's Creations Caches" name = "ZNI Creations"
url = "https://maven.zontreck.com/repository/internal" url = "https://maven.zontreck.dev"
}
// 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 { dependencies {
// Specify the version of Minecraft to use. // Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed
// Any artifact can be supplied so long as it has a "userdev" classifier artifact and is a compatible patcher artifact. // that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied.
// The "userdev" classifier will be requested and setup by ForgeGradle. // The userdev artifact is a special name and will get all sorts of transformations applied to it.
// If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"], minecraft "net.minecraftforge:forge:${mc_version}-${forge_version}"
// 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:LibZontreckMod:${libzontreck}") implementation fg.deobf("dev.zontreck:libzontreck:${mc_version}-${libz_version}:dev")
// Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings runtimeOnly fg.deobf("dev.zontreck:libzontreck:${mc_version}-${libz_version}")
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime compileOnly fg.deobf("dev.zontreck:libzontreck:${mc_version}-${libz_version}:dev")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}") // Real mod deobf dependency examples - these get remapped to your current mappings
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}") // 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
// Example mod dependency using a mod jar from ./libs with a flat dir repository // Examples using mod jars from ./libs
// 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}") // 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/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html // http://www.gradle.org/docs/current/userguide/dependency_management.html
} }
// This block of code expands all declared replace properties in the specified resource targets. jar {
// 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 { manifest {
attributes([ attributes([
'Specification-Title' : mod_id, "Specification-Title" : "watchmydurability",
'Specification-Vendor' : mod_authors, "Specification-Vendor" : "Zontreck",
'Specification-Version' : '1', // We are version 1 of ourselves "Specification-Version" : "1", // We are version 1 of ourselves
'Implementation-Title' : project.name, "Implementation-Title" : project.name,
'Implementation-Version' : project.jar.archiveVersion, "Implementation-Version" : project.jar.archiveVersion,
'Implementation-Vendor' : mod_authors, "Implementation-Vendor" : "ZNI Creations",
'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
]) ])
} }
// This is the preferred method to reobfuscate your jar file
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:
// tasks.named('publish').configure {
// dependsOn 'reobfJar'
// }
// Example configuration to allow publishing using the maven-publish plugin // 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')
publishing { publishing {
publications { publications {
register('mavenJava', MavenPublication) { mavenJava(MavenPublication) {
artifact jar artifact jar
} }
} }

View file

@ -3,58 +3,7 @@
org.gradle.jvmargs=-Xmx3G org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false org.gradle.daemon=false
libzontreck=1.10.011524.0045 mc_version=1.18.2
forge_version=40.2.1
## Environment Properties myversion=1.1.2.7
libz_version=1.0.4.9
# 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,6 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

14
gradlew vendored
View file

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

1
gradlew.bat vendored
View file

@ -26,7 +26,6 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%

View file

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

View file

@ -0,0 +1,333 @@
/*
*
* 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,127 +1,143 @@
package dev.zontreck.wmd.checkers; package dev.zontreck.mcmods;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; 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.ChatColor;
import dev.zontreck.libzontreck.chat.HoverTip; import dev.zontreck.libzontreck.chat.ChatColorFactory;
import dev.zontreck.libzontreck.util.ChatHelpers; import dev.zontreck.libzontreck.chat.HoverTip;
import dev.zontreck.wmd.types.ItemRegistry; import dev.zontreck.libzontreck.chat.ChatColor.ColorOptions;
import dev.zontreck.wmd.WatchMyDurability; import dev.zontreck.mcmods.configs.WMDClientConfig;
import dev.zontreck.wmd.configs.WMDClientConfig; import net.minecraft.client.Minecraft;
import dev.zontreck.wmd.utils.client.Helpers; import net.minecraft.core.NonNullList;
import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component;
import net.minecraft.core.NonNullList; import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextComponent;
import net.minecraft.network.chat.Style; import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemStack;
public class CheckInventory extends TimerTask
public class CheckInventory extends Task { {
private static final CheckInventory inst = new CheckInventory();
@Override
public CheckInventory() { public void run() {
super("checkinv", true);
} try {
public static CheckInventory getInstance(){ if(!WatchMyDurability.isInGame)return;
return inst; //WatchMyDurability.LOGGER.info("TICKING CHECK INVENTORY EVENT");
} // Get the player inventory
@Override Inventory inv = Minecraft.getInstance().player.getInventory();
public void run() {
checkList("_armor", inv.armor);
if(!WMDClientConfig.EnableToolWatcher.get()) return; checkList("_items", inv.items);
try { checkList("_offhand", inv.offhand);
if(!WatchMyDurability.isInGame)return;
PushItems("_armor", inv.armor);
PushItems("_items", inv.items);
//WatchMyDurability.LOGGER.info("TICKING CHECK INVENTORY EVENT"); PushItems("_offhand", inv.offhand);
// Get the player inventory } catch (Exception e) {
Inventory inv = Minecraft.getInstance().player.getInventory(); WatchMyDurability.LOGGER.warn(": : : : [ERROR] : : : :");
WatchMyDurability.LOGGER.warn("A error in the WatchMyDurability timer code has occurred. This could happen with hub worlds and the server transfers that occur. If this happened in another instance, please report this error to the developer, along with what you were doing.");
checkList("_armor", inv.armor); }
checkList("_items", inv.items);
checkList("_offhand", inv.offhand);
// Hijack this timer so we dont need to register yet another
if(!WMDClientConfig.EnableHealthAlert.get())return;
PushItems("_armor", inv.armor); Health current = Health.of(Minecraft.getInstance().player);
PushItems("_items", inv.items); if(WatchMyDurability.LastHealth == null)WatchMyDurability.LastHealth = current;
PushItems("_offhand", inv.offhand); else{
} catch (Exception e) { if(current.identical(WatchMyDurability.LastHealth))return;
WatchMyDurability.LOGGER.warn(": : : : [ERROR] : : : :"); }
WatchMyDurability.LOGGER.warn("A error in the WatchMyDurability timer code has occurred. This could happen with hub worlds and the server transfers that occur. If this happened in another instance, please report this error to the developer, along with what you were doing.");
} // Good to proceed
if(current.shouldGiveAlert())
{
} String Msg = ChatColor.doColors("!Dark_Red!!bold!You need to eat!");
Component chat = new TextComponent(Msg);
public void PushItems(String type, List<ItemStack> stack) Minecraft.getInstance().player.displayClientMessage(chat, false);
{
// OK SoundEvent sv = SoundEvents.WOLF_GROWL; // It sounds like a growling stomach
// Push the items into the registry, replacing the existing entry Soundify(sv);
ItemRegistry.purge(type); }
Map<Integer, ItemRegistry.Item> items = new HashMap<Integer, ItemRegistry.Item>();
Integer slotNum = 0; WatchMyDurability.LastHealth=current;
for (ItemStack itemStack : stack) {
ItemRegistry.Item itx = WatchMyDurability.REGISTRY.GetNewItem(itemStack); }
items.put(slotNum, itx); public void PushItems(String type, List<ItemStack> stack)
slotNum++; {
// OK
} // Push the items into the registry, replacing the existing entry
ItemRegistry.purge(type);
ItemRegistry.register(type,items); Map<Integer, ItemRegistry.Item> items = new HashMap<Integer, ItemRegistry.Item>();
} Integer slotNum = 0;
for (ItemStack itemStack : stack) {
public void checkList(String type, NonNullList<ItemStack> stacks){ ItemRegistry.Item itx = WatchMyDurability.REGISTRY.GetNewItem(itemStack);
Integer slotNum = 0;
//boolean ret=false; items.put(slotNum, itx);
for (ItemStack is1 : stacks) { slotNum++;
if(is1.isDamageableItem() && is1.isDamaged() && !ItemRegistry.contains(type, slotNum, WatchMyDurability.REGISTRY.GetNewItem(is1))){
}
int percent = 0;
int max = is1.getMaxDamage(); ItemRegistry.register(type,items);
int val = is1.getDamageValue(); }
int cur = max - val;
percent = cur * 100 / max; public void Soundify(SoundEvent sound)
{
//WatchMyDurability.LOGGER.debug("ITEM DURABILITY: "+cur+"; MAXIMUM: "+max+"; PERCENT: "+percent); //WatchMyDurability.LOGGER.info("PLAY ALERT SOUND");
for (Integer entry : WMDClientConfig.alertPercents.get()) { Minecraft.getInstance().player.playSound(sound, 1.0f, 1.0f);
Integer idx = WMDClientConfig.alertPercents.get().indexOf(entry); }
String entryStr = WMDClientConfig.alertMessages.get().get(idx);
public void checkList(String type, NonNullList<ItemStack> stacks){
if(percent <= entry){ Integer slotNum = 0;
String replaced = ChatColor.doColors(WMDClientConfig.WMD_PREFIX.get()) + ChatColor.DARK_RED + entryStr.replaceAll("!item!", is1.getDisplayName().getString()); //boolean ret=false;
WatchMyDurability.LOGGER.info("Enqueue alert for an item. Playing sound for item: "+is1.getDisplayName().getString()); for (ItemStack is1 : stacks) {
if(is1.isDamageableItem() && is1.isDamaged() && !ItemRegistry.contains(type, slotNum, WatchMyDurability.REGISTRY.GetNewItem(is1))){
SoundEvent theSound = SoundEvents.ITEM_BREAK;
Helpers.Soundify(theSound); int percent = 0;
int max = is1.getMaxDamage();
int val = is1.getDamageValue();
int cur = max - val;
MutableComponent X = Component.literal(replaced); percent = cur * 100 / max;
HoverEvent he = HoverTip.getItem(is1); //WatchMyDurability.LOGGER.debug("ITEM DURABILITY: "+cur+"; MAXIMUM: "+max+"; PERCENT: "+percent);
Style s = Style.EMPTY.withFont(Style.DEFAULT_FONT).withHoverEvent(he); for (Integer entry : WMDClientConfig.alertPercents.get()) {
X=X.withStyle(s); Integer idx = WMDClientConfig.alertPercents.get().indexOf(entry);
String entryStr = WMDClientConfig.alertMessages.get().get(idx);
Minecraft.getInstance().player.displayClientMessage(X, false); if(percent <= entry){
break; // Rule applies, break out of this loop, move to next item. String replaced = WatchMyDurability.WMDPrefix + 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);
slotNum ++;
}
//return ret;
} MutableComponent X = new TextComponent(replaced);
} HoverEvent he = HoverTip.getItem(is1);
Style s = Style.EMPTY.withFont(Style.DEFAULT_FONT).withHoverEvent(he);
X=X.withStyle(s);
Minecraft.getInstance().player.displayClientMessage(X, false);
break; // Rule applies, break out of this loop, move to next item.
}
}
}
slotNum ++;
}
//return ret;
}
}

View file

@ -1,36 +1,36 @@
package dev.zontreck.wmd.types; package dev.zontreck.mcmods;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
public class Health { public class Health {
public float maximum; public float maximum;
public float current; public float current;
public int asPercent() public int asPercent()
{ {
return (int)Math.round(Math.abs((current * 100 / maximum))); return (int)Math.round(Math.abs((current * 100 / maximum)));
} }
public Health lastHealthState; public Health lastHealthState;
public static Health of(Player player){ public static Health of(Player player){
Health obj = new Health(); Health obj = new Health();
obj.current = player.getHealth(); obj.current = player.getHealth();
obj.maximum = player.getMaxHealth(); obj.maximum = player.getMaxHealth();
return obj; return obj;
} }
public boolean shouldGiveAlert() public boolean shouldGiveAlert()
{ {
if(asPercent()<=50){ if(asPercent()<=50){
return true; return true;
}else return false; }else return false;
} }
public boolean identical(Health other) public boolean identical(Health other)
{ {
if(other.current == current && other.maximum == maximum)return true; if(other.current == current && other.maximum == maximum)return true;
else return false; else return false;
} }
} }

View file

@ -1,89 +1,88 @@
package dev.zontreck.wmd.types; package dev.zontreck.mcmods;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import dev.zontreck.wmd.WatchMyDurability; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemStack;
public class ItemRegistry {
public class ItemRegistry { public class Item {
public class Item { public String Name;
public String Name; public int PercentDamaged;
public int PercentDamaged; public int Count;
public int Count;
public boolean Compare(Item other)
public boolean Compare(Item other) {
{ if(other.Name.equals(Name) && Count == other.Count){
if(other.Name.equals(Name) && Count == other.Count){ if(PercentDamaged != other.PercentDamaged) return false;
if(PercentDamaged != other.PercentDamaged) return false; else return true;
else return true; }else return false;
}else return false; }
} }
}
public class Health {
public class Health { }
}
public Map<String,Map<Integer, Item>> CachedItems;
public Map<String,Map<Integer, Item>> CachedItems; public ItemRegistry()
public ItemRegistry() {
{ CachedItems = new HashMap<String,Map<Integer,Item>>();
CachedItems = new HashMap<String,Map<Integer,Item>>(); }
}
public static void Initialize()
public static void Initialize() {
{ WatchMyDurability.REGISTRY = new ItemRegistry();
WatchMyDurability.REGISTRY = new ItemRegistry(); }
}
public static void purge(String type) {
public static void purge(String type) { if(WatchMyDurability.REGISTRY.CachedItems.containsKey(type))
if(WatchMyDurability.REGISTRY.CachedItems.containsKey(type)) WatchMyDurability.REGISTRY.CachedItems.remove(type);
WatchMyDurability.REGISTRY.CachedItems.remove(type); }
}
public Item GetNewItem(ItemStack itemStack) {
public Item GetNewItem(ItemStack itemStack) { Item x = new Item();
Item x = new Item(); x.Name = itemStack.getDisplayName().getString();
x.Name = itemStack.getDisplayName().getString(); if(itemStack.isDamageableItem() && itemStack.isDamaged()){
if(itemStack.isDamageableItem() && itemStack.isDamaged()){ int max = itemStack.getMaxDamage();
int max = itemStack.getMaxDamage(); int val = itemStack.getDamageValue();
int val = itemStack.getDamageValue(); int cur = max-val;
int cur = max-val; int percent = cur * 100 /max;
int percent = cur * 100 /max; x.PercentDamaged=percent;
x.PercentDamaged=percent; }
}
x.Count = itemStack.getCount();
x.Count = itemStack.getCount(); //WatchMyDurability.LOGGER.debug("ITEM: "+x.Name + "; "+x.PercentDamaged+"; "+x.Type+"; "+x.Count);
//WatchMyDurability.LOGGER.debug("ITEM: "+x.Name + "; "+x.PercentDamaged+"; "+x.Type+"; "+x.Count); return x;
return x; }
}
public static void register(String type, Map<Integer, Item> items) {
public static void register(String type, Map<Integer, Item> items) {
WatchMyDurability.REGISTRY.CachedItems.put(type, items);
WatchMyDurability.REGISTRY.CachedItems.put(type, items); }
}
public static boolean contains(String type, Integer slot, Item getNewItem) {
public static boolean contains(String type, Integer slot, Item getNewItem) { ItemRegistry reg = WatchMyDurability.REGISTRY;
ItemRegistry reg = WatchMyDurability.REGISTRY; if(reg.CachedItems.containsKey(type)){
if(reg.CachedItems.containsKey(type)){ //WatchMyDurability.LOGGER.debug("Registry contains "+type);
//WatchMyDurability.LOGGER.debug("Registry contains "+type); Map<Integer,Item> items = reg.CachedItems.get(type);
Map<Integer,Item> items = reg.CachedItems.get(type); if(items.containsKey(slot)){
if(items.containsKey(slot)){ //WatchMyDurability.LOGGER.debug("ItemRegistry contains slot: "+slot);
//WatchMyDurability.LOGGER.debug("ItemRegistry contains slot: "+slot); Item x = items.get(slot);
Item x = items.get(slot); if(x.Compare(getNewItem)){
if(x.Compare(getNewItem)){ //WatchMyDurability.LOGGER.debug("Items are identical!");
//WatchMyDurability.LOGGER.debug("Items are identical!"); // Items are identical
// Items are identical return true;
return true; }else {
}else { //WatchMyDurability.LOGGER.debug("ITEMS ARE NOT IDENTICAL");
//WatchMyDurability.LOGGER.debug("ITEMS ARE NOT IDENTICAL"); return false;
return false; }
} }else return false;
}else return false;
}
}
return false;
return false; }
}
}
}

View file

@ -1,144 +1,122 @@
package dev.zontreck.wmd; package dev.zontreck.mcmods;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import dev.zontreck.ariaslib.util.DelayedExecutorService; import dev.zontreck.libzontreck.chat.ChatColor;
import dev.zontreck.libzontreck.chat.ChatColor; import dev.zontreck.mcmods.configs.WMDClientConfig;
import dev.zontreck.wmd.checkers.CheckHealth; import net.minecraft.client.Minecraft;
import dev.zontreck.wmd.checkers.CheckHunger; import net.minecraft.client.User;
import dev.zontreck.wmd.checkers.CheckInventory; import net.minecraftforge.common.MinecraftForge;
import dev.zontreck.wmd.commands.ModCommands; import net.minecraftforge.eventbus.api.IEventBus;
import dev.zontreck.wmd.configs.WMDClientConfig; import net.minecraftforge.eventbus.api.SubscribeEvent;
import dev.zontreck.wmd.networking.ModMessages; import net.minecraftforge.fml.ModLoadingContext;
import dev.zontreck.wmd.types.Health; import net.minecraftforge.fml.common.Mod;
import dev.zontreck.wmd.types.Hunger; import net.minecraftforge.fml.config.ModConfig.Type;
import dev.zontreck.wmd.types.ItemRegistry; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraft.client.Minecraft; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraft.client.User; import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.client.event.ClientPlayerNetworkEvent.LoggedInEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.client.event.ClientPlayerNetworkEvent.LoggedOutEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod; import java.util.Timer;
import net.minecraftforge.fml.config.ModConfig.Type;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import org.slf4j.Logger;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.event.server.ServerStartingEvent; // The value here should match an entry in the META-INF/mods.toml file
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @Mod(WatchMyDurability.MODID)
import net.minecraftforge.client.event.ClientPlayerNetworkEvent; public class WatchMyDurability
{
import java.util.Timer; // Define mod id in a common place for everything to reference
public static final String MODID = "watchmydurability";
import org.slf4j.Logger; // Directly reference a slf4j logger
public static final Logger LOGGER = LogUtils.getLogger();
// The value here should match an entry in the META-INF/mods.toml file
@Mod(WatchMyDurability.MODID) /// DO NOT USE FROM ANY THIRD PARTY PACKAGES
public class WatchMyDurability public static User CurrentUser = null; // This is initialized by the client
{ public static boolean isInGame = false; // This locks the timer thread
// Define mod id in a common place for everything to reference public static ItemRegistry REGISTRY;
public static final String MODID = "watchmydurability"; public static Health LastHealth;
// Directly reference a slf4j logger public static String WMDPrefix;
public static final Logger LOGGER = LogUtils.getLogger();
/// DO NOT USE FROM ANY THIRD PARTY PACKAGES
public static User CurrentUser = null; // This is initialized by the client public WatchMyDurability()
public static boolean isInGame = false; // This locks the timer thread {
public static ItemRegistry REGISTRY; WatchMyDurability.WMDPrefix = ChatColor.doColors("!Dark_Gray![!Bold!!Dark_Green!WMD!Reset!!Dark_Gray!]!reset!");
public static Health LastHealth;
public static Hunger LastHunger; IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
public static boolean WMD_SERVER_AVAILABLE =false; // Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);
ModLoadingContext.get().registerConfig(Type.CLIENT, WMDClientConfig.SPEC, "watchmydurability-client.toml");
public WatchMyDurability()
{ //MinecraftForge.EVENT_BUS.register(new HeartsRenderer());
// Register ourselves for server and other game events we are interested in
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); MinecraftForge.EVENT_BUS.register(this);
}
// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup); private void commonSetup(final FMLCommonSetupEvent event)
ModLoadingContext.get().registerConfig(Type.CLIENT, WMDClientConfig.SPEC, "watchmydurability-client.toml"); {
// Some common setup code
// Register ourselves for server and other game events we are interested in //LOGGER.info("HELLO FROM COMMON SETUP");
MinecraftForge.EVENT_BUS.register(this); }
MinecraftForge.EVENT_BUS.register(new ModCommands());
} // You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
private void commonSetup(final FMLCommonSetupEvent event) public void onServerStarting(ServerStartingEvent event)
{ {
// Some common setup code // Do something when the server starts
//LOGGER.info("HELLO FROM COMMON SETUP"); //LOGGER.warn("If this is running on a server, it is doing absolutely nothing, please remove me.");
ModMessages.register(); }
}
// 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)
// You can use SubscribeEvent and let the Event Bus discover methods to call public static class ClientModEvents
@SubscribeEvent {
public void onServerStarting(ServerStartingEvent event) static Timer time = new Timer();
{
// Do something when the server starts @SubscribeEvent
//LOGGER.warn("If this is running on a server, it is doing absolutely nothing, please remove me."); public static void onClientSetup(FMLClientSetupEvent event)
} {
LOGGER.info(WMDPrefix+": : : CLIENT SETUP : : :");
// You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent // Some client setup code
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) //LOGGER.info("HELLO FROM CLIENT SETUP");
public static class ClientModEvents //LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName());
{ WatchMyDurability.CurrentUser = Minecraft.getInstance().getUser();
static Timer time = new Timer();
time.schedule(new CheckInventory(), WMDClientConfig.TimerVal.get()*1000, WMDClientConfig.TimerVal.get()*1000);
@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event) ItemRegistry.Initialize();
{
LOGGER.info(": : : CLIENT SETUP : : :"); }
// Some client setup code }
//LOGGER.info("HELLO FROM CLIENT SETUP");
//LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName()); @Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE)
WatchMyDurability.CurrentUser = Minecraft.getInstance().getUser(); public static class ClientEvents
DelayedExecutorService.setup(); {
@SubscribeEvent
//time.schedule(new CheckInventory(), public static void onJoin(LoggedInEvent event){
//WMDClientConfig.TimerVal.get()*1000, // Joined
//WMDClientConfig.TimerVal.get()*1000); //LOGGER.info("PLAYER LOGGED IN");
LOGGER.info(WMDPrefix+": : : PLAYER LOGGED IN : : :");
ItemRegistry.Initialize(); WatchMyDurability.isInGame=true;
}
}
@SubscribeEvent
} public static void onLeave(LoggedOutEvent event){
//LOGGER.info("PLAYER LOGGED OUT");
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT) LOGGER.info(WMDPrefix+": : : PLAYER LOGGED OUT : : :");
public static class ClientEvents WatchMyDurability.isInGame=false;
{ }
@SubscribeEvent @SubscribeEvent
public static void onJoin(ClientPlayerNetworkEvent.LoggingIn event){ public static void onClone(ClientPlayerNetworkEvent.RespawnEvent event)
// Joined {
//LOGGER.info("PLAYER LOGGED IN"); LOGGER.info(WMDPrefix+": : : : PLAYER RESPAWNED OR MOVED TO A NEW WORLD : : : :");
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(ClientPlayerNetworkEvent.LoggingOut event){
//LOGGER.info("PLAYER LOGGED OUT");
LOGGER.info(": : : PLAYER LOGGED OUT : : :");
WatchMyDurability.isInGame=false;
WatchMyDurability.WMD_SERVER_AVAILABLE=false;
DelayedExecutorService.stop();
}
@SubscribeEvent
public static void onClone(ClientPlayerNetworkEvent.Clone event)
{
LOGGER.info(": : : : PLAYER RESPAWNED OR MOVED TO A NEW WORLD : : : :");
}
}
}

View file

@ -1,78 +1,42 @@
package dev.zontreck.wmd.configs; package dev.zontreck.mcmods.configs;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.minecraft.nbt.CompoundTag; import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec;
public class WMDClientConfig {
public class WMDClientConfig { public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();
public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder(); public static final ForgeConfigSpec SPEC;
public static final ForgeConfigSpec SPEC;
public static ForgeConfigSpec.ConfigValue<List<Integer>> alertPercents;
public static ForgeConfigSpec.ConfigValue<List<Integer>> alertPercents; public static ForgeConfigSpec.ConfigValue<List<String>> alertMessages;
public static ForgeConfigSpec.ConfigValue<List<String>> alertMessages; public static ForgeConfigSpec.ConfigValue<Integer> TimerVal;
public static ForgeConfigSpec.ConfigValue<Integer> TimerVal; //public static ForgeConfigSpec.ConfigValue<Boolean> EnableExtraHearts;
public static ForgeConfigSpec.ConfigValue<Boolean> EnableHealthAlert; public static ForgeConfigSpec.ConfigValue<Boolean> EnableHealthAlert;
public static ForgeConfigSpec.ConfigValue<Boolean> EnableHungerAlert;
public static ForgeConfigSpec.ConfigValue<Boolean> EnableToolWatcher; static{
List<Integer> alerts1 = new ArrayList<>();
alerts1.add(10);
public static ForgeConfigSpec.ConfigValue<String> WMD_PREFIX;
List<String> alerts2 = new ArrayList<>();
static{ alerts2.add("!item! is about to break");
List<Integer> alerts1 = new ArrayList<>();
alerts1.add(10);
BUILDER.push("Alerts");
List<String> alerts2 = new ArrayList<>(); BUILDER.comment("Both of the following lists must have the same number of entries. NOTE: Percents do NOT stack. After the first rule is applied, it will move to the next item, so please make the list ascend, and not descend. Example: 10, 50").define("VERSION", "1.1.1.1");
alerts2.add("!item! is about to break");
alertPercents = BUILDER.comment("The list of alerts you want at what percentages of remaining durability").define("Percents", alerts1);
alertMessages = BUILDER.comment("The messages you want displayed when a alert is triggered. You must have the same amount of messages as alerts").define("Messages", alerts2);
BUILDER.push("Alerts"); TimerVal = BUILDER.comment("How many seconds between timer ticks to check your inventory items?").define("Timer", 5);
BUILDER.comment("Both of the following lists must have the same number of entries. NOTE: Percents do NOT stack. After the first rule is applied, it will move to the next item, so please make the list ascend, and not descend. Example: 10, 50").define("VERSION", "1.1.1.1");
BUILDER.pop();
alertPercents = BUILDER.comment("The list of alerts you want at what percentages of remaining durability").define("Percents", alerts1);
alertMessages = BUILDER.comment("The messages you want displayed when a alert is triggered. You must have the same amount of messages as alerts").define("Messages", alerts2); BUILDER.push("General");
TimerVal = BUILDER.comment("How many seconds between timer ticks to check your inventory items?").define("Timer", 5); //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);
BUILDER.pop();
BUILDER.push("General"); SPEC=BUILDER.build();
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

@ -1,52 +0,0 @@
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

@ -1,50 +0,0 @@
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,14 +0,0 @@
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

@ -1,21 +0,0 @@
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,17 +0,0 @@
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

@ -1,76 +0,0 @@
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

@ -1,130 +0,0 @@
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

@ -1,36 +0,0 @@
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

@ -1,35 +0,0 @@
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

@ -1,45 +0,0 @@
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

@ -1,42 +0,0 @@
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,28 +0,0 @@
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,14 +0,0 @@
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,30 +6,32 @@
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml # The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version # A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. loaderVersion="[40,)" #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. # 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. # Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="${mod_license}" license="GPL-v2"
# A URL to refer people to when problems occur with this mod # A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional #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 # A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory [[mods]] #mandatory
# The modid of the mod # The modid of the mod
modId="${mod_id}" #mandatory modId="watchmydurability" #mandatory
# The version number of the mod # The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
version="${mod_version}" #mandatory # ${file.jarVersion} will substitute the value of the Implementation-Version as read from the mod's JAR file metadata
# A display name for the mod # see the associated build.gradle script for how to populate this completely automatically during a build
displayName="${mod_name}" #mandatory version="1.1.2.7" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/ # 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/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional #updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI # A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional #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 # A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional # logoFile="examplemod.png" #optional
# A text field displayed in the mod UI # A text field displayed in the mod UI
#credits="" #optional credits="zontreck @ ZNI Creations" #optional
# A text field displayed in the mod UI # A text field displayed in the mod UI
authors="${mod_authors}" #optional authors="zontreck" #optional
# Display Test controls the display for your mod in the server connection screen # 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. # 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. # 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.
@ -39,38 +41,36 @@ authors="${mod_authors}" #optional
#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional) #displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional)
# The description text for the mod (multi line!) (#mandatory) # The description text for the mod (multi line!) (#mandatory)
description='''${mod_description}''' 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
'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. # A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.${mod_id}]] #optional [[dependencies.watchmydurability]] #optional
# the modid of the dependency # the modid of the dependency
modId="forge" #mandatory modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified # Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory mandatory=true #mandatory
# The version range of the dependency # The version range of the dependency
versionRange="${forge_version_range}" #mandatory versionRange="[40,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE" ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER # Side this dependency is applied on - BOTH, CLIENT or SERVER
side="BOTH" side="CLIENT"
# Here's another dependency # Here's another dependency
[[dependencies.${mod_id}]] [[dependencies.watchmydurability]]
modId="minecraft" modId="minecraft"
mandatory=true mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version # This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="${minecraft_version_range}" versionRange="[1.18.2,1.19)"
ordering="NONE" ordering="NONE"
side="BOTH" side="CLIENT"
[[dependencies.watchmydurability]]
[[dependencies.${mod_id}]]
modId="libzontreck" modId="libzontreck"
mandatory=true mandatory=true
versionRange="[1.10,1.11)" versionRange="[1.0.4.9,1.0.5.0)"
ordering="NONE" ordering="NONE"
side="BOTH" side="CLIENT"
# 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.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5 KiB

View file

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