Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
tanishisherewithhh committed Apr 11, 2024
1 parent 031c8af commit 3ed5a37
Show file tree
Hide file tree
Showing 31 changed files with 540 additions and 484 deletions.
144 changes: 73 additions & 71 deletions src/main/java/com/tanishisherewith/dynamichud/newTrial/DynamicHUD.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@
import java.util.List;

public class DynamicHUD implements ClientModInitializer {
public static MinecraftClient MC = MinecraftClient.getInstance();
public static String MOD_ID = "dynamichud";
private static final Logger logger = LoggerFactory.getLogger("DynamicHud");
private static final List<WidgetRenderer> widgetRenderers = new ArrayList<>();
/**
* This is a map to store the list of widgets for each widget file to be saved.
* <p>
* Allows saving widgets across different mods with same save file name.
*/
public static final HashMap<String,List<Widget>> fileMap = new HashMap<>();
public static final HashMap<String, List<Widget>> fileMap = new HashMap<>();
private static final Logger logger = LoggerFactory.getLogger("DynamicHud");
private static final List<WidgetRenderer> widgetRenderers = new ArrayList<>();
public static MinecraftClient MC = MinecraftClient.getInstance();
public static String MOD_ID = "dynamichud";

public static void addWidgetRenderer(WidgetRenderer widgetRenderer) {
widgetRenderers.add(widgetRenderer);
Expand All @@ -52,6 +52,18 @@ public static void printWarn(String msg) {
logger.warn(msg);
}

/**
* Opens the MovableScreen when the specified key is pressed.
*
* @param key The key to listen for
* @param screen The AbstractMoveableScreen instance to use to set the screen
*/
public static void openDynamicScreen(KeyBinding key, AbstractMoveableScreen screen) {
if (key.wasPressed()) {
MC.setScreen(screen);
}
}

@Override
public void onInitializeClient() {
printInfo("Initialising DynamicHud");
Expand All @@ -67,62 +79,62 @@ public void onInitializeClient() {
FabricLoader.getInstance()
.getEntrypointContainers("dynamicHud", DynamicHudIntegration.class)
.forEach(entrypoint -> {
ModMetadata metadata = entrypoint.getProvider().getMetadata();
String modId = metadata.getId();
AbstractMoveableScreen screen;
try {
DynamicHudIntegration DHIntegration = entrypoint.getEntrypoint();
DHIntegration.init();

File widgetsFile = DHIntegration.getWidgetsFile();

if(widgetsFile.exists()) {
WidgetManager.loadWidgets(widgetsFile);
}else{
DHIntegration.addWidgets();
}
DHIntegration.initAfter();

screen = DHIntegration.getMovableScreen();

KeyBinding binding = DHIntegration.getKeyBind();

DHIntegration.registerCustomWidgets();

WidgetRenderer widgetRenderer = DHIntegration.getWidgetRenderer();
addWidgetRenderer(widgetRenderer);

List<Widget> widgets = fileMap.get(widgetsFile.getName());

if(widgets == null) {
fileMap.put(widgetsFile.getName(), widgetRenderer.getWidgets());
}else{
widgetRenderer.getWidgets().addAll(widgets);
fileMap.put(widgetsFile.getName(), widgetRenderer.getWidgets());
}

//Register events for rendering, saving, loading, and opening the hudEditor
ClientTickEvents.START_CLIENT_TICK.register((client)-> {
openDynamicScreen(binding, screen);
ModMetadata metadata = entrypoint.getProvider().getMetadata();
String modId = metadata.getId();
AbstractMoveableScreen screen;
try {
DynamicHudIntegration DHIntegration = entrypoint.getEntrypoint();
DHIntegration.init();

File widgetsFile = DHIntegration.getWidgetsFile();

if (widgetsFile.exists()) {
WidgetManager.loadWidgets(widgetsFile);
} else {
DHIntegration.addWidgets();
}
DHIntegration.initAfter();

screen = DHIntegration.getMovableScreen();

KeyBinding binding = DHIntegration.getKeyBind();

DHIntegration.registerCustomWidgets();

WidgetRenderer widgetRenderer = DHIntegration.getWidgetRenderer();
addWidgetRenderer(widgetRenderer);

List<Widget> widgets = fileMap.get(widgetsFile.getName());

if (widgets == null) {
fileMap.put(widgetsFile.getName(), widgetRenderer.getWidgets());
} else {
widgetRenderer.getWidgets().addAll(widgets);
fileMap.put(widgetsFile.getName(), widgetRenderer.getWidgets());
}

//Register events for rendering, saving, loading, and opening the hudEditor
ClientTickEvents.START_CLIENT_TICK.register((client) -> {
openDynamicScreen(binding, screen);
});

// Save during exiting a world, server or Minecraft itself
// Also saved when a resource pack is reloaded.
ServerLifecycleEvents.SERVER_STOPPING.register(server -> saveWidgetsSafely(widgetsFile, fileMap.get(widgetsFile.getName())));
ServerLifecycleEvents.END_DATA_PACK_RELOAD.register((server, resourceManager, s) -> saveWidgetsSafely(widgetsFile, fileMap.get(widgetsFile.getName())));
ServerPlayConnectionEvents.DISCONNECT.register((handler, packetSender) -> saveWidgetsSafely(widgetsFile, fileMap.get(widgetsFile.getName())));
Runtime.getRuntime().addShutdownHook(new Thread(() -> saveWidgetsSafely(widgetsFile, fileMap.get(widgetsFile.getName()))));

printInfo(String.format("Integration of mod %s was successful", modId));
} catch (Throwable e) {
if (e instanceof IOException) {
logger.warn("An error has occurred while loading widgets of mod {}", modId, e);
} else {
logger.warn("Mod {} has incorrect implementation of DynamicHUD", modId, e);
}
}
});

// Save during exiting a world, server or Minecraft itself
// Also saved when a resource pack is reloaded.
ServerLifecycleEvents.SERVER_STOPPING.register(server -> saveWidgetsSafely(widgetsFile,fileMap.get(widgetsFile.getName())));
ServerLifecycleEvents.END_DATA_PACK_RELOAD.register((server, resourceManager, s) -> saveWidgetsSafely(widgetsFile,fileMap.get(widgetsFile.getName())));
ServerPlayConnectionEvents.DISCONNECT.register((handler, packetSender) -> saveWidgetsSafely(widgetsFile,fileMap.get(widgetsFile.getName())));
Runtime.getRuntime().addShutdownHook(new Thread(() -> saveWidgetsSafely(widgetsFile,fileMap.get(widgetsFile.getName()))));

printInfo(String.format("Integration of mod %s was successful",modId));
} catch (Throwable e) {
if(e instanceof IOException){
logger.warn("An error has occurred while loading widgets of mod {}", modId,e);
}else {
logger.warn("Mod {} has incorrect implementation of DynamicHUD", modId, e);
}
}
});

ServerLifecycleEvents.SERVER_STOPPING.register(server -> GlobalConfig.HANDLER.save());
ServerLifecycleEvents.END_DATA_PACK_RELOAD.register((server, resourceManager, s) -> GlobalConfig.HANDLER.save());
ServerPlayConnectionEvents.DISCONNECT.register((handler, packetSender) -> GlobalConfig.HANDLER.save());
Expand All @@ -131,24 +143,14 @@ public void onInitializeClient() {

HudRenderCallback.EVENT.register(new HudRender());
}

private void saveWidgetsSafely(File widgetsFile, List<Widget> widgets) {
try {
WidgetManager.saveWidgets(widgetsFile,widgets);
WidgetManager.saveWidgets(widgetsFile, widgets);
} catch (IOException e) {
logger.error("Failed to save widgets. Widgets passed: {}", widgets);
throw new RuntimeException(e);
}
}
/**
* Opens the MovableScreen when the specified key is pressed.
*
* @param key The key to listen for
* @param screen The AbstractMoveableScreen instance to use to set the screen
*/
public static void openDynamicScreen(KeyBinding key, AbstractMoveableScreen screen) {
if (key.wasPressed()) {
MC.setScreen(screen);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public interface DynamicHudIntegration {
/**
* Initializes the DynamicHud integration.
* <p>
* Suggested to be used to initialize {@link com.tanishisherewith.dynamichud.newTrial.utils.DynamicValueRegistry} and widgets with their respective values
* Suggested to be used to initialize {@link com.tanishisherewith.dynamichud.newTrial.utils.DynamicValueRegistry} and widgets with their respective values
* </p>
*/
void init();
Expand All @@ -76,15 +76,17 @@ public interface DynamicHudIntegration {
/**
* To register custom widgets. This method can be overridden by implementations.
*/
default void registerCustomWidgets(){}
default void registerCustomWidgets() {
}

/**
* Performs any necessary initialization after the widgets have been added. This method can be overridden by implementations.
* <p>
* Suggested to be used to initialize a {@link WidgetRenderer} object with the added widgets.
* Suggested to be used to initialize a {@link WidgetRenderer} object with the added widgets.
* </p>
*/
default void initAfter(){}
default void initAfter() {
}

/**
* Returns the file where widgets are to be saved and loaded from.
Expand All @@ -94,6 +96,7 @@ default void initAfter(){}
default File getWidgetsFile() {
return WIDGETS_FILE;
}

/**
* Returns the keybind to open the {@link AbstractMoveableScreen} instance.
*
Expand All @@ -116,7 +119,7 @@ default KeyBinding getKeyBind() {
*
* @return The widget renderer.
*/
default WidgetRenderer getWidgetRenderer(){
default WidgetRenderer getWidgetRenderer() {
return new WidgetRenderer(WidgetManager.getWidgets());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@ public class DynamicHudTest implements DynamicHudIntegration {
TextWidget Example2Widget;
DynamicValueRegistry registry;
WidgetRenderer renderer;

@Override
public void init() {
//Global registry
DynamicValueRegistry.registerGlobal("FPS",() -> "FPS: "+ DynamicHUD.MC.getCurrentFps());
DynamicValueRegistry.registerGlobal("FPS", () -> "FPS: " + DynamicHUD.MC.getCurrentFps());

//Local registry
registry = new DynamicValueRegistry(DynamicHUD.MOD_ID);
registry.registerLocal("FPS",()-> "FPS C-DVR: "+ DynamicHUD.MC.getCurrentFps());
registry.registerLocal("FPS", () -> "FPS C-DVR: " + DynamicHUD.MC.getCurrentFps());

textWidget = new TextWidget.Builder()
textWidget = new TextWidget.Builder()
.setX(300)
.setY(100)
.setDraggable(true)
Expand All @@ -36,7 +37,7 @@ public void init() {
.shouldScale(false)
.build();

Example2Widget = new TextWidget.Builder()
Example2Widget = new TextWidget.Builder()
.setX(200)
.setY(100)
.setDraggable(true)
Expand All @@ -53,7 +54,8 @@ public void addWidgets() {
WidgetManager.addWidget(textWidget);
WidgetManager.addWidget(Example2Widget);
}
public void initAfter(){

public void initAfter() {
List<Widget> widgets = WidgetManager.getWidgetsForMod(DynamicHUD.MOD_ID);

renderer = new WidgetRenderer(widgets);
Expand All @@ -64,7 +66,8 @@ public void initAfter(){

@Override
public AbstractMoveableScreen getMovableScreen() {
return new AbstractMoveableScreen(Text.literal("Editor"), renderer) {};
return new AbstractMoveableScreen(Text.literal("Editor"), renderer) {
};
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,28 @@

import com.tanishisherewith.dynamichud.newTrial.screens.AbstractMoveableScreen;
import com.tanishisherewith.dynamichud.newTrial.utils.DynamicValueRegistry;
import com.tanishisherewith.dynamichud.newTrial.utils.contextmenu.Option;
import com.tanishisherewith.dynamichud.newTrial.widget.Widget;
import com.tanishisherewith.dynamichud.newTrial.widget.WidgetManager;
import com.tanishisherewith.dynamichud.newTrial.widget.WidgetRenderer;
import com.tanishisherewith.dynamichud.newTrial.widgets.TextWidget;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.gui.screen.TitleScreen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.gui.screen.option.OptionsScreen;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.text.Text;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL;

import java.io.File;
import java.util.List;

public class DynamicHudTestTWO implements DynamicHudIntegration {
TextWidget exampleWidget;
WidgetRenderer renderer;

@Override
public void init() {
//Global registry
DynamicValueRegistry.registerGlobal("CPS",() -> "NOT FPS");
DynamicValueRegistry.registerGlobal("CPS", () -> "NOT FPS");


exampleWidget = new TextWidget.Builder()
Expand All @@ -51,14 +49,15 @@ public KeyBinding getKeyBind() {

@Override
public File getWidgetsFile() {
return new File(FILE_DIRECTORY,"widgets_new.nbt");
return new File(FILE_DIRECTORY, "widgets_new.nbt");
}

@Override
public void addWidgets() {
WidgetManager.addWidget(exampleWidget);
}
public void initAfter(){

public void initAfter() {
List<Widget> widgets = WidgetManager.getWidgetsForMod("CustomMod");

renderer = new WidgetRenderer(widgets);
Expand All @@ -69,7 +68,8 @@ public void initAfter(){

@Override
public AbstractMoveableScreen getMovableScreen() {
return new AbstractMoveableScreen(Text.literal("Editor 2"), renderer) {};
return new AbstractMoveableScreen(Text.literal("Editor 2"), renderer) {
};
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
public class HudRender implements HudRenderCallback {
@Override
public void onHudRender(DrawContext drawContext, float tickDelta) {
for(WidgetRenderer widgetRenderer: DynamicHUD.getWidgetRenderers()){
widgetRenderer.renderWidgets(drawContext,-120,-120);
for (WidgetRenderer widgetRenderer : DynamicHUD.getWidgetRenderers()) {
widgetRenderer.renderWidgets(drawContext, -120, -120);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,26 @@
import net.minecraft.util.Identifier;

public class GlobalConfig {
private static GlobalConfig INSTANCE = new GlobalConfig();
public static ConfigClassHandler<GlobalConfig> HANDLER = ConfigClassHandler.createBuilder(GlobalConfig.class)
.id(new Identifier("dynamichud", "dynamichud_config"))
.serializer(config -> GsonConfigSerializerBuilder.create(config)
.setPath(FabricLoader.getInstance().getConfigDir().resolve("dynamichud.json5"))
.setJson5(true)
.build())
.build();

private static final GlobalConfig INSTANCE = new GlobalConfig();
/**
* Common scale for all widgets. Set by the user using YACL.
*/
@SerialEntry
public float scale = 1.0f;

public static GlobalConfig get() {
return INSTANCE;
}

public Screen createYACLGUI() {
return YetAnotherConfigLib.createBuilder()
return YetAnotherConfigLib.createBuilder()
.title(Text.literal("DynamicHUD config screen."))
.category(ConfigCategory.createBuilder()
.name(Text.literal("General"))
Expand All @@ -39,14 +42,11 @@ public Screen createYACLGUI() {
.name(Text.literal("Scale"))
.description(OptionDescription.of(Text.literal("Set scale for all widgets.")))
.binding(1.0f, () -> this.scale, newVal -> this.scale = newVal)
.controller(floatOption -> FloatSliderControllerBuilder.create(floatOption).range(0.1f,2.5f).step(0.1f))
.controller(floatOption -> FloatSliderControllerBuilder.create(floatOption).range(0.1f, 2.5f).step(0.1f))
.build())
.build())
.build())
.build()
.generateScreen(null);
}
public static GlobalConfig get(){
return INSTANCE;
}
}
Loading

0 comments on commit 3ed5a37

Please sign in to comment.