Compare commits

...
16 Commits
Author SHA1 Message Date
retuci0 86594f1ca3 v2.9 2026-01-18 22:53:21 +01:00
retuci0 f074f05c51 v2.8 2026-01-17 17:12:54 +01:00
retuci0 436b79fd2b v2.7 2026-01-17 00:33:24 +01:00
retuci0 9afaa4e0c8 v2.6 2026-01-11 11:12:44 +01:00
retuci0 f794457538 v2.5 2026-01-06 18:09:52 +01:00
retuci0 ec3e633cec v2.4 2026-01-05 22:16:01 +01:00
retuci0 8f17bd8e67 v2.3 - sputnik rename 2026-01-04 17:46:51 +01:00
retuci0 dc2429918e v2.2 2026-01-04 11:40:06 +01:00
retuci0 94a9b1dade v2.1 2026-01-02 13:59:08 +01:00
retuci0 48899f85f9 v2.0.1 2026-01-01 18:29:46 +01:00
retuci0 347ec658bb v2.0 2025-12-31 00:44:36 +01:00
retuci0 a9cf6dd924 v1.9.1 2025-12-28 00:58:08 +01:00
retuci0 8e44dda9cf v1.9 2025-12-26 22:45:43 +01:00
retuci0 2329476fe4 v1.8 2025-12-22 18:54:02 +01:00
retuci0 6b2ec0e69a v1.7.1 2025-12-14 21:31:58 +01:00
retuci0 6fa409d60a v1.7 2025-12-10 19:26:51 +01:00
455 changed files with 16073 additions and 4827 deletions

No files matched your search

-4
View File
@@ -42,9 +42,5 @@ replay_*.log
# otros
todo.txt
test.java
cambios.md
# no está terminado
src/main/java/me/retucio/camtweaks/module/modules/TooltipsPlus.java
remappedSrc/
+26 -7
View File
@@ -1,23 +1,23 @@
# jenny's mod 2 100% real
mod para Minecraft Fabric 1.21.10 que añade algunas cosas QOL, mayormente relacionadas a la cámara.
mod para Minecraft Fabric 1.21.11 que añade algunas cosas QOL, mayormente relacionadas a la cámara.
## instalación
### para gente normal:
1. ir a [lanzamientos](https://github.com/retuci0/camera-tweaks/releases)
1. ir a [lanzamientos](https://github.com/retuci0/sputnik/releases)
2. selecionar la versión más reciente
3. descargar el .jar
4. moverlo a tu directorio de mods (probablemente `%appdata%/.minecraft/mods`)
asegúrate de tener una version de Minecraft y Fabric compatibles con el mod (MC `1.21.10`; Fabric `0.138.3`)
asegúrate de tener una version de Minecraft y Fabric compatibles con el mod (MC `1.21.11`; Fabric `0.17.3`)
es posible que haya problemas al usarlo junto a otros mods, especialmente junto a otros clientes, pues pueden conflictar entre ellos.
### para frikis de 200 de iq
1. clona el respositorio (`git clone https://github.com/retuci0/camera-tweaks`)
2. entra al directorio del repositorio (`cd camera-tweaks`)
1. clona el respositorio (`git clone https://github.com/retuci0/sputnik`)
2. entra al directorio del repositorio (`cd sputnik`)
3. `gradlew build` para Windows o `chmod +x gradlew` + `./gradlew build` para Linux (Mac es Linux)
4. el resultado estará en `/build/libs/camtweaks-X.X.jar` (el que no lleva "sources" en el nombre)
4. el resultado estará en `/build/libs/sputnik-X.X.jar` (el que no lleva "sources" en el nombre)
## uso
@@ -54,6 +54,7 @@ algunos módulos tienen teclas asignadas por defecto, asígnales `ESC` para desa
<img src="screenshots/fullbright.png" alt="fullbright en modo gamma cambiando el color de los shaders">
<img src="screenshots/hud.png" alt="HUD">
<img src="screenshots/hudeditor.png" alt="editor de HUD">
<img src="screenshots/colorpicker.png" alt="selector de colores">
## contibuciones
@@ -65,4 +66,22 @@ no sé, haz lo que quieras con esto, es puta basura xd
aunque estaría guay que acreditases
pero bueno
pero bueno
## descargo de responsabilidad
me importa una puta mierda lo que pase al usar este mod en servers donde es baneable y así.
## mods recomendados
> mods que recomiendo usar junto a este:
- [fabric api (necesario)](https://modrinth.com/mod/fabric-api/): necesario para el mod
- [sodium](https://modrinth.com/mod/sodium): mejora el rendimiento general del juego
- [viafabricplus](https://modrinth.com/mod/viafabricplus): te permite conectarte a servidores que tengan una versión distinta a la de tu cliente
- [xaero's world map](https://modrinth.com/mod/xaeros-world-map/) y [xaero's minimap](https://modrinth.com/mod/xaeros-minimap/): mapa chulo
- [mod menu](https://modrinth.com/mod/modmenu): lista de los mods instalados, y sus ajustes
- [iris](https://modrinth.com/mod/iris): shaders
- [lambdynamiclights](https://modrinth.com/mod/lambdynamiclights): iluminación dinámica
- [appleskin](https://modrinth.com/mod/appleskin/): información relacionada con la comida
- [baritone (desactualizado)](https://github.com/cabaletta/baritone): google maps para juego de cubos
+15 -26
View File
@@ -1,6 +1,6 @@
plugins {
id 'fabric-loom' version "${loom_version}"
id 'maven-publish'
id 'fabric-loom' version "${loom_version}"
id 'maven-publish'
}
version = project.mod_version
@@ -11,26 +11,25 @@ base {
}
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
maven {
name = "FDD Maven"
url = "https://maven.firstdark.dev/releases"
}
}
dependencies {
// To change the versions see the gradle.properties file
// mc
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_api_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
// otros
include(modImplementation "dev.firstdark.discordrpc:discord-rpc:1.0.3")
}
loom {
accessWidenerPath = file("src/main/resources/camtweaks.accesswidener")
accessWidenerPath = file("src/main/resources/sputnik.accesswidener")
}
processResources {
@@ -46,11 +45,6 @@ tasks.withType(JavaCompile).configureEach {
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
@@ -59,11 +53,12 @@ jar {
inputs.property "archivesName", project.base.archivesName
from("LICENSE") {
rename { "${it}_${inputs.properties.archivesName}"}
rename {
"${it}_${inputs.properties.archivesName}"
}
}
}
// configure the maven publication
publishing {
publications {
create("mavenJava", MavenPublication) {
@@ -72,11 +67,5 @@ publishing {
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
}
repositories {}
}
+17 -7
View File
@@ -1,19 +1,29 @@
# v1.5
# v2.9
## novedades
sigo vivo (creo)
varios módulos que no quería añadir porque son cheats en toda regla, pero ya total, como la mayoría que he añadido hasta la fecha es baneable
### adiciones
- editor de hud bastante básico pero por lo general funcional (`pág. arriba` por defecto). viene con muchos bugs, ojalá me caiga un rayo.
- categoría de movimiento
#### módulos nuevos:
- packetmine: mina usando paquetes, para minar más rápido o para evitar la animación de minado
- aliviar cpu: evita renderizar objetos en pantalla si la ventana no está seleccionada
- delfín: *ruidos de delfín*
- patinaje: esparce semen allá por donde pisas (haciéndolo más resbaladizo)
- jesús: hermano se cree Jesús (camina sobre el agua)
- info. de bloque: (muestra el contenido nbt de un bloque)
- estampaescrotos: mazo en esteroides
- tenedor mágico: hermano se cree Poseidón (tweaks a la propulsión acuática del tridente)
- elytras: vuela con las elytras (en vez de solo planear)
- barco volador: convierte tu bote de acacia en un caza militar
### arreglos / mejoras
- ya no salta un error al hacer una captura con los módulos `capturas de pantalla` y `chat plus` activos
- ahora la telemetría (abuso de privacidad al usuario de microshit) está desactivado por huevos. si quieres activarlo te jodes.
- ahora ya no puedes abrir interfaces del mod si no estás en un mundo
- mejorada la seguridad de algunas operaciones
- ahora puedes cambiar el título de la ventana en los ajustes del mod
## problemas reconocidos
+12 -5
View File
@@ -1,5 +1,12 @@
meteor client dev team
oyvey client (1.21 port by mioclient)
lennyboi (youtube)
packbar by cattyn on github
shotify mod
Meteor Client: https://github.com/MeteorDevelopment/meteor-client | https://meteorclient.com
OyVey Port: https://github.com/mioclient/oyvey-ported/
Lenny Boi: https://www.youtube.com/@lennyboi7195
Shotify: https://modrinth.com/mod/shotify
No Telemetry: https://modrinth.com/mod/no-telemetry
Trouser Streak: https://github.com/etianl/Trouser-Streak
No More Purple: https://github.com/Pepperoni-Jabroni/NoMorePurple/
bypass-resource-pack: https://github.com/emilyy-dev/bypass-resource-pack
elytra-recast: https://github.com/InLieuOfLuna/elytra-recast/
probablemente más pero como tengo demencia se me olvida
si quieres que te acredite o quite tu código de mi mod, mándame un mensaje en discord (username: retucio) y sin problemas :)
+9 -14
View File
@@ -1,18 +1,13 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
# Fabric Properties
# check these on https://fabricmc.net/develop
minecraft_version=1.21.10
yarn_mappings=1.21.10+build.2
loader_version=0.17.3
loom_version=1.11-SNAPSHOT
minecraft_version=1.21.11
yarn_mappings=1.21.11+build.3
loader_version=0.18.4
loom_version=1.13-SNAPSHOT
# Mod Properties
mod_version=1.5
fabric_api_version=0.140.2+1.21.11
mod_version=2.9
maven_group=me.retucio
archives_base_name=camtweaks
# Dependencies
fabric_version=0.135.0+1.21.10
archives_base_name=sputnik
Binary file not shown.

After

Width:  |  Height:  |  Size: 915 KiB

@@ -1,37 +0,0 @@
package me.retucio.camtweaks.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import net.minecraft.client.gui.screen.ingame.GenericContainerScreen;
import net.minecraft.command.CommandSource;
import net.minecraft.inventory.EnderChestInventory;
import net.minecraft.inventory.Inventories;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.screen.GenericContainerScreenHandler;
import net.minecraft.text.Text;
// accede a los contenidos de tu enderchest
public class EnderChestCommand extends Command {
public EnderChestCommand() {
super("echest", "muestra el contenido de tu enderchest", "ec", "enderchest");
}
@Override
public void build(LiteralArgumentBuilder<CommandSource> builder) {
builder.executes(ctx -> {
mc.execute(() -> { // para evitar llamar setScreen desde el hilo equivocado, que causa crashes
EnderChestInventory enderChestInv = mc.player.getEnderChestInventory();
// llámame imbécil pero no tengo ni idea de por qué no se abre
mc.setScreen(new GenericContainerScreen(
GenericContainerScreenHandler.createGeneric9x3(mc.player.currentScreenHandler.syncId + 1, mc.player.getInventory(), enderChestInv),
mc.player.getInventory(),
Text.translatable("container.enderchest")
));
});
return SUCCESS;
});
}
}
@@ -1,169 +0,0 @@
package me.retucio.camtweaks.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.settings.*;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.frames.ClientSettingsFrame;
import me.retucio.camtweaks.ui.frames.SettingsFrame;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
// se ocupa de guardar, cargar y aplicar ajustes
// pues no me ha dado dolores de cabeza el coso este con los NPE de los cojones...
public class ConfigManager {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final File CONFIG_FILE = new File("camera_tweaks.json");
private static ClientConfig config = null;
// guardar configuraciones
public static void save() {
ensureConfig();
try (FileWriter writer = new FileWriter(CONFIG_FILE)) {
GSON.toJson(config, writer);
CameraTweaks.LOGGER.info("ajustes guardados");
} catch (IOException e) {
e.printStackTrace();
}
}
// cargar configuraciones
public static void load() {
CameraTweaks.LOGGER.info("ajustes cargados");
if (!CONFIG_FILE.exists()) {
ensureConfig();
save();
return;
}
try (FileReader reader = new FileReader(CONFIG_FILE)) {
config = GSON.fromJson(reader, ClientConfig.class);
} catch (IOException e) {
e.printStackTrace();
ensureConfig();
}
}
// aplicar configuraciones cargadas
public static void applyConfig() {
if (CameraTweaks.mc == null || ModuleManager.INSTANCE == null || config == null)
return;
ModuleManager.INSTANCE.getModules().forEach(module -> {
if (config.moduleStates.containsKey(module.getName()))
module.setEnabled(config.moduleStates.get(module.getName())); // estados
module.getSettings().forEach(setting -> applySetting(module, setting));
if (config.settingsFrames.containsKey(module.getName())) {
int[] position = config.settingsFrames.get(module.getName());
ClickGUI.INSTANCE.openSettingsFrame(module, position[0], position[1]);
}
});
ClientSettingsFrame.guiSettings.setEnabled(true);
ClientSettingsFrame.guiSettings.getSettings().forEach(setting -> applySetting(ClientSettingsFrame.guiSettings, setting));
CameraTweaks.LOGGER.info("módulos encendidos cargados");
CameraTweaks.LOGGER.info("ajustes de módulos cargados");
ClientConfig.FrameData moduleFrameData = config.extendableFrames.get("M");
if (moduleFrameData != null) {
ClickGUI.INSTANCE.getModulesFrame().x = moduleFrameData.x();
ClickGUI.INSTANCE.getModulesFrame().y = moduleFrameData.y();
ClickGUI.INSTANCE.getModulesFrame().extended = moduleFrameData.extended();
}
ClientConfig.FrameData guiSettingsData = config.extendableFrames.get("S");
if (guiSettingsData != null) {
ClickGUI.INSTANCE.getGuiSettingsFrame().x = guiSettingsData.x();
ClickGUI.INSTANCE.getGuiSettingsFrame().y = guiSettingsData.y();
ClickGUI.INSTANCE.getGuiSettingsFrame().extended = guiSettingsData.extended();
}
CameraTweaks.LOGGER.info("posiciones de frames cargadas");
ClickGUI.INSTANCE.refreshListButtons();
}
public static ClientConfig getConfig() {
return config;
}
public static void setModuleState(Module module) {
ensureConfig();
config.moduleStates.put(module.getName(), module.isEnabled());
save();
}
public static void setSetting(AbstractSetting setting, Object value) {
ensureConfig();
config.settings.put(setting.getModule().getName() + ":" + setting.getName(), value);
save();
}
public static void setFramePosition(SettingsFrame frame) {
ensureConfig();
config.settingsFrames.put(frame.module.getName(), new int[]{frame.x, frame.y});
save();
}
public static void setExtendableFrame(String key, ClientConfig.FrameData data) {
ensureConfig();
config.extendableFrames.put(key, data);
save();
}
public static void setHudPosition(String id, int x, int y) {
ensureConfig();
config.hudPositions.put(id, new int[]{x, y});
save();
}
public static void setHudVisibility(String id, Boolean visible) {
ensureConfig();
config.hudVisibilities.put(id, visible);
save();
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static void applySetting(Module parent, AbstractSetting setting) {
String id = parent.getName() + ":" + setting.getName();
if (config.settings.containsKey(id)) {
Object value = config.settings.get(id);
switch (setting) {
case BooleanSetting b -> b.setEnabled((boolean) value);
case EnumSetting e -> e.setIndex(value instanceof Double val ? val.intValue() : (int) value);
case NumberSetting n -> n.setValue((double) value);
case StringSetting s -> s.setValue((String) value);
case KeySetting k -> k.setKey(value instanceof Double val ? val.intValue() : (int) value);
case ListSetting l -> {
if (value instanceof Map<?, ?> map) {
Map<Object, Boolean> converted = new HashMap<>();
for (Object option : l.getOptions()) {
Object key = String.valueOf(option);
Object bv = map.get(key);
converted.put(option, bv instanceof Boolean b && b);
}
l.setValues(converted);
}
} default -> {}
}
}
}
private static void ensureConfig() {
if (config == null) config = new ClientConfig();
}
}
@@ -1,9 +0,0 @@
package me.retucio.camtweaks.event.events;
import me.retucio.camtweaks.event.Event;
/**
* @see me.retucio.camtweaks.mixin.ChunkOcclusionDataBuilderMixin#onChunkOcclusion
*/
public class ChunkOcclusionEvent extends Event {}
@@ -1,9 +0,0 @@
package me.retucio.camtweaks.event.events;
import me.retucio.camtweaks.event.Event;
/**
* @see me.retucio.camtweaks.mixin.ClientConnectionMixin#onDisconnect
*/
public class DisconnectEvent extends Event {}
@@ -1,12 +0,0 @@
package me.retucio.camtweaks.event.events;
import me.retucio.camtweaks.event.Event;
/**
* @see me.retucio.camtweaks.mixin.MinecraftClientMixin#onStop
*/
public class ShutdownEvent extends Event {
public ShutdownEvent() {}
}
@@ -1,14 +0,0 @@
package me.retucio.camtweaks.event.events;
import me.retucio.camtweaks.event.Event;
/**
* @see me.retucio.camtweaks.mixin.MinecraftClientMixin#onTickPre
* @see me.retucio.camtweaks.mixin.MinecraftClientMixin#onTickPost
*/
public class TickEvent {
public static class Pre extends Event {}
public static class Post extends Event {}
}
@@ -1,5 +0,0 @@
package me.retucio.camtweaks.event.events.camtweaks;
import me.retucio.camtweaks.event.Event;
public class LoadClickGUIEvent extends Event {}
@@ -1,5 +0,0 @@
package me.retucio.camtweaks.event.events.camtweaks;
import me.retucio.camtweaks.event.Event;
public class LoadCommandManagerEvent extends Event {}
@@ -1,5 +0,0 @@
package me.retucio.camtweaks.event.events.camtweaks;
import me.retucio.camtweaks.event.Event;
public class LoadModuleManagerEvent extends Event {}
@@ -1,19 +0,0 @@
package me.retucio.camtweaks.mixin;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.PortalGUI;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.network.ClientPlayerEntity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(ClientPlayerEntity.class)
public abstract class ClientPlayerEntityMixin {
@ModifyExpressionValue(method = "tickNausea", at = @At(value = "FIELD", target = "Lnet/minecraft/client/MinecraftClient;currentScreen:Lnet/minecraft/client/gui/screen/Screen;"))
private Screen allowScreensInPortals(Screen original) {
if (ModuleManager.INSTANCE.getModuleByClass(PortalGUI.class).isEnabled()) return null;
return original;
}
}
@@ -1,48 +0,0 @@
package me.retucio.camtweaks.mixin;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.Freecam;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.network.ClientPlayerInteractionManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ClientPlayerInteractionManager.class)
public abstract class ClientPlayerInteractionManagerMixin {
@Unique
Freecam freecam;
@Inject(method = "<init>", at = @At("TAIL"))
private void getModules(MinecraftClient client, ClientPlayNetworkHandler networkHandler, CallbackInfo ci) {
freecam = ModuleManager.INSTANCE.getModuleByClass(Freecam.class);
}
// los paquetes ya se cancelan en la clase de Freecam, pero visualmente el bloque sigue apareciendo roto
@Inject(method = "breakBlock", at = @At("HEAD"), cancellable = true)
private void cancelBlockBreaking(BlockPos pos, CallbackInfoReturnable<Boolean> cir) {
if (freecam.isEnabled() && freecam.cancelActionPackets.isEnabled()) cir.setReturnValue(false);
}
@Inject(method = "interactBlock", at = @At("HEAD"), cancellable = true)
private void cancelBlockPlacement(ClientPlayerEntity player, Hand hand, BlockHitResult hitResult, CallbackInfoReturnable<ActionResult> cir) {
if (freecam.isEnabled() && freecam.cancelActionPackets.isEnabled()) cir.setReturnValue(ActionResult.FAIL);
}
@Inject(method = "interactEntity", at = @At("HEAD"), cancellable = true)
private void cancelEntityInteractions(PlayerEntity player, Entity entity, Hand hand, CallbackInfoReturnable<ActionResult> cir) {
if (freecam.isEnabled() && freecam.cancelActionPackets.isEnabled()) cir.setReturnValue(ActionResult.FAIL);
}
}
@@ -1,22 +0,0 @@
package me.retucio.camtweaks.mixin;
import com.llamalad7.mixinextras.injector.ModifyReturnValue;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.TimeChanger;
import net.minecraft.world.dimension.DimensionType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import static me.retucio.camtweaks.CameraTweaks.mc;
@Mixin(DimensionType.class)
public abstract class DimensionTypeMixin {
@ModifyReturnValue(method = "getMoonPhase", at = @At("RETURN"))
private int overrideMoonPhase(int original) {
TimeChanger timeChanger = ModuleManager.INSTANCE.getModuleByClass(TimeChanger.class);
if (timeChanger.isEnabled() && mc.world != null && !timeChanger.moonPhase.is(TimeChanger.MoonPhases.DEFAULT))
return timeChanger.getMoonPhase();
return original;
}
}
@@ -1,47 +0,0 @@
package me.retucio.camtweaks.mixin;
import com.llamalad7.mixinextras.injector.ModifyReturnValue;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.OpenScreenEvent;
import me.retucio.camtweaks.event.events.ShutdownEvent;
import me.retucio.camtweaks.event.events.TickEvent;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import static me.retucio.camtweaks.CameraTweaks.EVENT_BUS;
@Mixin(MinecraftClient.class)
public abstract class MinecraftClientMixin {
@Inject(method = "tick", at = @At("HEAD"))
private void onTickPre(CallbackInfo ci) {
CameraTweaks.INSTANCE.onTick();
EVENT_BUS.post(new TickEvent.Pre());
}
@Inject(method = "tick", at = @At("TAIL"))
private void onTickPost(CallbackInfo ci) {
EVENT_BUS.post(new TickEvent.Post());
}
@Inject(method = "stop", at = @At("HEAD"))
private void onStop(CallbackInfo ci) {
EVENT_BUS.post(new ShutdownEvent());
}
@Inject(method = "setScreen", at = @At("HEAD"), cancellable = true)
private void onOpenScreen(Screen screen, CallbackInfo ci) {
OpenScreenEvent event = EVENT_BUS.post(new OpenScreenEvent(screen));
if (event.isCancelled()) ci.cancel();
}
@Inject(method = "isTelemetryEnabledByApi", at = @At("RETURN"), cancellable = true)
private void disableMicropenisTelemetryShi(CallbackInfoReturnable<Boolean> cir) {
cir.setReturnValue(false);
}
}
@@ -1,40 +0,0 @@
package me.retucio.camtweaks.mixin;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.PerspectivePlus;
import me.retucio.camtweaks.module.modules.TimeChanger;
import net.minecraft.client.render.SkyRendering;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.util.math.MatrixStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(SkyRendering.class)
public abstract class SkyRendererMixin {
@Unique
TimeChanger timeChanger;
@Inject(method = "<init>", at = @At("TAIL"))
private void getModules(CallbackInfo ci) {
timeChanger = ModuleManager.INSTANCE.getModuleByClass(TimeChanger.class);
}
@Inject(method = "renderSun", at = @At("HEAD"), cancellable = true)
private void onRenderSun(float alpha, MatrixStack matrices, CallbackInfo ci) {
if (timeChanger.isEnabled() && !timeChanger.renderSun.isEnabled()) ci.cancel();
}
@Inject(method = "renderMoon", at = @At("HEAD"), cancellable = true)
private void onRenderMoon(int phase, float alpha, MatrixStack matrixStack, CallbackInfo ci) {
if (timeChanger.isEnabled() && !timeChanger.renderMoon.isEnabled()) ci.cancel();
}
@Inject(method = "renderStars", at = @At("HEAD"), cancellable = true)
private void onRenderStars(float brightness, MatrixStack matrices, CallbackInfo ci) {
if (timeChanger.isEnabled() && !timeChanger.renderStars.isEnabled()) ci.cancel();
}
}
@@ -1,70 +0,0 @@
package me.retucio.camtweaks.mixin;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.BlockOutline;
import me.retucio.camtweaks.module.modules.Freecam;
import me.retucio.camtweaks.module.modules.NoRender;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.Frustum;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.WorldRenderer;
import net.minecraft.client.render.state.WorldRenderState;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.math.ColorHelper;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.awt.*;
@Mixin(WorldRenderer.class)
public abstract class WorldRendererMixin {
@ModifyArg(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/WorldRenderer;method_74752(Lnet/minecraft/client/render/Camera;Lnet/minecraft/client/render/Frustum;Z)V"), index = 2)
private boolean renderSetupTerrainModifyArg(boolean spectator) {
return ModuleManager.INSTANCE.getModuleByClass(Freecam.class).isEnabled() || spectator;
}
@Inject(method = "renderTargetBlockOutline", at = @At("HEAD"), cancellable = true)
private void noRenderBlockOutlinesFreecam(VertexConsumerProvider.Immediate immediate, MatrixStack matrices, boolean renderBlockOutline, WorldRenderState renderStates, CallbackInfo ci) {
Freecam freecam = ModuleManager.INSTANCE.getModuleByClass(Freecam.class);
if (freecam.isEnabled() && !freecam.blockOutlines.isEnabled()) ci.cancel();
}
@Inject(method = "hasBlindnessOrDarkness(Lnet/minecraft/client/render/Camera;)Z", at = @At("HEAD"), cancellable = true)
private void hasBlindnessOrDarkness(Camera camera, CallbackInfoReturnable<Boolean> cir) {
NoRender noRender = ModuleManager.INSTANCE.getModuleByClass(NoRender.class);
if (!noRender.isEnabled()) return;
if (!noRender.blindnessEffect.isEnabled() || !noRender.darknessEffect.isEnabled()) cir.setReturnValue(null);
}
@Redirect(method = "renderTargetBlockOutline", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/ColorHelper;withAlpha(II)I"))
private int modifyBlockOutlineColor(int alpha, int rgb) {
BlockOutline outline = ModuleManager.INSTANCE.getModuleByClass(BlockOutline.class);
if (!outline.isEnabled()) return ColorHelper.withAlpha(alpha, rgb);
if (outline.rainbow.isEnabled()) {
float speed = 10001 - outline.rainbowSpeed.getFloatValue(); // 10001 para evitar divisiones por cero
float hue = (System.currentTimeMillis() % (int) speed) / speed;
Color gamingProMax = Color.getHSBColor(hue, 1, 1);
return new Color(
gamingProMax.getRed(),
gamingProMax.getGreen(),
gamingProMax.getBlue(),
outline.alpha.getIntValue()
).getRGB();
} else {
return new Color(
outline.red.getIntValue(),
outline.green.getIntValue(),
outline.blue.getIntValue(),
outline.alpha.getIntValue()
).getRGB();
}
}
}
@@ -1,153 +0,0 @@
package me.retucio.camtweaks.module;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.camtweaks.ToggleModuleEvent;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.EnumSetting;
import me.retucio.camtweaks.module.settings.KeySetting;
import me.retucio.camtweaks.module.settings.AbstractSetting;
import me.retucio.camtweaks.util.ChatUtil;
import net.minecraft.client.MinecraftClient;
import org.lwjgl.glfw.GLFW;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
// clase base para los módulos
public class Module {
// atributos
private String name;
private String description;
private boolean enabled;
private boolean saveSettings = true;
// dejar al usuario elegir si el módulo debería apagarse tras soltar su tecla asignada, o si la tecla debería alternar su estado
protected EnumSetting<KeyModes> keyMode = new EnumSetting<>("modo de tecla", "cómo interpretar la tecla configurada", KeyModes.class, KeyModes.TOGGLE);
protected KeySetting bind = new KeySetting("tecla", "tecla asignada al módulo, ESC para desactivar", GLFW.GLFW_KEY_UNKNOWN);
protected BooleanSetting notify = new BooleanSetting("notificar", "notificar en el chat al activar / desactivar", true);
private final List<AbstractSetting> settings = new ArrayList<>();
protected MinecraftClient mc = MinecraftClient.getInstance();
public Module(String name, String description) {
this.name = name;
this.description = description;
addSettings(bind, keyMode, notify);
}
// ajustes
public List<AbstractSetting> getSettings() {
return settings;
}
@SuppressWarnings("unchecked")
public <S extends AbstractSetting> S addSetting(AbstractSetting setting) {
settings.add(setting);
setting.setModule(this);
return (S) setting; // por convenciencia
}
public void addSettings(AbstractSetting... settings) {
for (AbstractSetting setting : settings) addSetting(setting);
}
// encendido y apagado del módulo
public void toggle() {
enabled = !enabled;
if (enabled) onEnable();
else onDisable();
CameraTweaks.EVENT_BUS.post(new ToggleModuleEvent(this));
}
public void onEnable() {
if (notify.isEnabled()) ChatUtil.info(getName() + " fue activado");
for (Method method : getClass().getDeclaredMethods())
if (method.isAnnotationPresent(SubscribeEvent.class)) {
CameraTweaks.EVENT_BUS.register(this);
break;
}
CameraTweaks.EVENT_BUS.post(new ToggleModuleEvent(this));
}
public void onDisable() {
if (notify.isEnabled()) ChatUtil.info(getName() + " fue desactivado");
if (CameraTweaks.EVENT_BUS.isRegistered(this))
CameraTweaks.EVENT_BUS.unregister(this);
CameraTweaks.EVENT_BUS.post(new ToggleModuleEvent(this));
}
// otros métodos
public void onTick() {}
public void onKey(int key, int action) {}
// getters y setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
if (this.enabled == enabled) return; // para evitar NPEs al cargar ajustes porque soy imbécil
this.enabled = enabled;
if (enabled) onEnable();
else onDisable();
}
public boolean shouldToggleOnBindRelease() {
return keyMode.is(KeyModes.HOLD);
}
public boolean shouldSaveSettings() {
return saveSettings;
}
public void shouldSaveSettings(boolean value) {
this.saveSettings = value;
}
public int getKey() {
return bind.getKey();
}
public void setKey(int key) {
bind.setKey(key);
}
public void assignKey(int key) {
bind.setDefaultKey(key);
bind.setKey(key);
}
public KeySetting getBind() {
return bind;
}
public enum KeyModes {
HOLD("mantener"),
TOGGLE("alternar");
// ojalá hubiera una manera de evitar repetirse con esto pero no la hay (creo) ...
private final String name;
KeyModes(String name) { this.name = name; }
@Override public String toString() { return name; }
}
}
@@ -1,88 +0,0 @@
package me.retucio.camtweaks.module;
import me.retucio.camtweaks.event.EventBus;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.module.modules.*;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
// donde se registran los módulos, y los "listeners" de eventos en cada módulo que lo necesite
public class ModuleManager {
public static ModuleManager INSTANCE;
private final List<Module> modules = new ArrayList<>();
private final EventBus eventBus;
public ModuleManager(EventBus bus) {
this.eventBus = bus;
addModules();
}
// por orden alfabético y todo, flipas
private void addModules() {
modules.add(new AntiInvis());
modules.add(new BlockOutline());
modules.add(new BossbarStack());
modules.add(new ChatPlus());
modules.add(new CritsPlus());
modules.add(new DamageOverlay());
modules.add(new FakePlayer());
modules.add(new Freecam());
modules.add(new Freelook());
modules.add(new Fullbright());
modules.add(new HandView());
modules.add(new HUD());
modules.add(new Nametags());
modules.add(new NoRender());
modules.add(new PerspectivePlus());
modules.add(new PortalGUI());
modules.add(new ScreenshotPlus());
modules.add(new TimeChanger());
// modules.add(new TooltipsPlus());
modules.add(new Zoom());
modules.sort(Comparator.comparing(module -> module.getName().toLowerCase()));
// registrar los "listeners" necesarios
for (Module module : getEnabledModules()) {
for (Method method : module.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(SubscribeEvent.class)) {
eventBus.register(module);
break;
}
}
}
}
// para obtener módulos más fácilmente (por nombre, clase, o la lista completa)
public List<Module> getModules() {
return modules;
}
public List<Module> getEnabledModules() {
List<Module> enabledModules = new ArrayList<>();
for (Module module : modules)
if (module.isEnabled()) enabledModules.add(module);
return enabledModules;
}
public Module getModuleByName(String name) {
for (Module module : modules)
if (module.getName().equalsIgnoreCase(name)) return module;
return null;
}
public <T extends Module> T getModuleByClass(Class<T> clazz) {
for (Module module : modules)
if (clazz.isInstance(module))
return clazz.cast(module);
return null;
}
}
@@ -1,14 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
/** continúa en:
* @see me.retucio.camtweaks.mixin.EntityMixin
*/
public class AntiInvis extends Module {
public AntiInvis() {
super("anti invis", "te permite ver a los jugadores invisibles");
}
}
@@ -1,31 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
/** continúa en:
* @see me.retucio.camtweaks.mixin.WorldRendererMixin
*/
public class BlockOutline extends Module {
public BooleanSetting rainbow = addSetting(new BooleanSetting("RGB", "erre ge be gueiming", false));
public NumberSetting rainbowSpeed = addSetting(new NumberSetting("velocidad", "velocidad de la bandera gay", 2000, 0, 10000, 2));
public NumberSetting red = addSetting(new NumberSetting("rojo", "factor r del rbg", 0, 0, 255, 1));
public NumberSetting green = addSetting(new NumberSetting("verde", "factor g del rgb", 0, 0, 255, 1));
public NumberSetting blue = addSetting(new NumberSetting("azul", "factor b del rbg", 0, 0, 255, 1));
public NumberSetting alpha = addSetting(new NumberSetting("opacidad", "transparencia invertida", 102, 0, 255, 1));
public BlockOutline() {
super("contorno", "customiza el contorno de los bloques");
rainbow.onUpdate(v -> {
rainbowSpeed.setVisible(v);
red.setVisible(!v);
green.setVisible(!v);
blue.setVisible(!v);
});
}
}
@@ -1,38 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
/** continúa en:
* @see me.retucio.camtweaks.mixin.DamageParticleMixin
* @see me.retucio.camtweaks.mixin.DamageParticleFactoryMixin
*/
public class CritsPlus extends Module {
public BooleanSetting rainbow = addSetting(new BooleanSetting("LUCES GAMING", "PARTÍCULAS GAMING", false));
public NumberSetting rainbowSpeed = addSetting(new NumberSetting("velocidad del erre ge be", "qué tan gaming son las luces gaming", 1000, 0, 10000, 2));
public NumberSetting red = addSetting(new NumberSetting("rojo", "comunismo", 0, 0, 255, 1));
public NumberSetting green = addSetting(new NumberSetting("verde", "vox", 0, 0, 255, 1));
public NumberSetting blue = addSetting(new NumberSetting("azul", "metanfetamina", 255, 0, 255, 1));
public NumberSetting alpha = addSetting(new NumberSetting("alpha", "opacidad", 255, 0, 255, 1));
public NumberSetting scale = addSetting(new NumberSetting("escala", "tamaño", 1, 0, 2, 0.05));
public NumberSetting multiplier; // no sé dónde se calcula cuántas partículas aparecen :/
public NumberSetting velocityMultipler = addSetting(new NumberSetting("dispersión", "multiplicador de la velocidad de dispersión", 1, 0, 10, 0.1));
public NumberSetting gravity = addSetting(new NumberSetting("gravedad", "multiplicador de fuerza de gravedad", 1, 0, 10, 0.1));
public NumberSetting maxAge = addSetting(new NumberSetting("vida máxima", "cuánto persiste la partícula", 4, 0, 50, 1));
public BooleanSetting collide = addSetting(new BooleanSetting("colisionar", "colisionar con bloques", false));
public CritsPlus() {
super("críticos", "cambia la apariencia de los críticos al gusto");
rainbow.onUpdate(v -> {
rainbowSpeed.setVisible(v);
red.setVisible(!v);
green.setVisible(!v);
blue.setVisible(!v);
});
}
}
@@ -1,75 +0,0 @@
package me.retucio.camtweaks.module.modules;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.textures.GpuTextureView;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.NumberSetting;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.NativeImageBackedTexture;
import java.awt.*;
/** continúa en:
* @see me.retucio.camtweaks.mixin.OverlayTextureMixin
*/
public class DamageOverlay extends Module {
public NumberSetting red = addSetting(new NumberSetting("rojo", "r o j o", 255, 0, 255, 1));
public NumberSetting green = addSetting(new NumberSetting("verde", "v e r d e", 0, 0, 255, 1));
public NumberSetting blue = addSetting(new NumberSetting("azul", "a z u l", 0, 0, 255, 1));
public NumberSetting alpha = addSetting(new NumberSetting("alpha", "o p a c i d a d", 77, 0, 255, 1));
private NativeImageBackedTexture texture = null;
public DamageOverlay() {
super("superposición de daño", "modifica el color en el que se renderiza la superposición de recibir daño");
NumberSetting[] settings = {red, green, blue, alpha};
for (NumberSetting setting : settings)
setting.onUpdate(v -> reloadOverlayIfReady());
}
@Override
public void onEnable() {
reloadOverlayIfReady();
super.onEnable();
}
@Override
public void onDisable() {
reloadOverlayIfReady();
super.onDisable();
}
private void reloadOverlayIfReady() {
if (texture != null && texture.getImage() != null) reloadOverlay(texture);
}
// recargar el overlay (superposición)
public void reloadOverlay(NativeImageBackedTexture texture) {
if (this.texture == null) this.texture = texture;
int color = isEnabled() ?
new Color(red.getIntValue(), green.getIntValue(), blue.getIntValue(), 255 - alpha.getIntValue()).getRGB()
: new Color(255, 0, 0, 178).getRGB();
NativeImage image = texture.getImage();
for (int y = 0; y < 8; y++)
for (int x = 0; x < 16; x++)
image.setColorArgb(x, y, color);
uploadTexture();
}
// resubir las texturas
private void uploadTexture() {
GpuTextureView overlayTex = RenderSystem.getShaderTexture(33985);
RenderSystem.setShaderTexture(33985, overlayTex);
texture.upload();
GpuTextureView mainTex = RenderSystem.getShaderTexture(33984);
RenderSystem.setShaderTexture(33984, mainTex);
}
}
@@ -1,44 +0,0 @@
package me.retucio.camtweaks.module.modules;
import com.mojang.authlib.GameProfile;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.StringSetting;
import net.minecraft.client.network.OtherClientPlayerEntity;
import net.minecraft.entity.Entity;
import java.util.UUID;
public class FakePlayer extends Module {
public StringSetting name = addSetting(new StringSetting("nombre", "qué nombre asignarle al jugador", "apio boy", 22));
private OtherClientPlayerEntity player = null;
public FakePlayer() {
super("jugador falso", "invoca una entidad de jugador falsa por motivos de testeo");
}
@Override
public void onEnable() {
if (mc.world == null) return;
player = new OtherClientPlayerEntity(mc.world, new GameProfile(UUID.randomUUID(), name.getValue()));
// player.copyPositionAndRotation(mc.player);
player.copyFrom(mc.player);
mc.world.addEntity(player);
super.onEnable();
}
@Override
public void onDisable() {
if (mc.world == null || player == null) return;
player.setRemoved(Entity.RemovalReason.KILLED);
player.onRemoved();
player = null;
super.onDisable();
}
}
@@ -1,139 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.command.CommandManager;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.TickEvent;
import me.retucio.camtweaks.event.events.camtweaks.LoadClickGUIEvent;
import me.retucio.camtweaks.event.events.camtweaks.LoadCommandManagerEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
import me.retucio.camtweaks.module.settings.StringSetting;
import me.retucio.camtweaks.util.ChatUtil;
import me.retucio.camtweaks.util.Colors;
import org.lwjgl.glfw.GLFW;
import java.awt.*;
// módulo no visible solo para los ajustes de la interfaz (y del cliente en general)
public class GUI extends Module {
public BooleanSetting rainbow = addSetting(new BooleanSetting("gaming", "gaming", false));
public NumberSetting rainbowSpeed = addSetting(new NumberSetting("velocidad del gaming", "velocidad, del gaming.",
1000, 0, 10000, 2));
public NumberSetting saturation = addSetting(new NumberSetting("saturación del gaming", "saturación, del gaming",
1, 0, 1, 0.01));
public NumberSetting brightness = addSetting(new NumberSetting("brillo del gaming", "brillo, del gaming",
0.8, 0, 1, 0.01));
public NumberSetting red = addSetting(new NumberSetting("rojo", "cantidad de rojo en el RGB del marco", 70, 0, 255, 1));
public NumberSetting green = addSetting(new NumberSetting("verde", "cantidad de verde en el RGB del marco", 20, 0, 255, 1));
public NumberSetting blue = addSetting(new NumberSetting("azul", "cantidad de azul en el RGB del marco", 210, 0, 255, 1));
public NumberSetting alpha = addSetting(new NumberSetting("alpha", "opacidad del marco", 230, 0, 255, 1));
// números negativos para deslizamiento inverso, 0 para desactivar
public NumberSetting scrollSens = addSetting(new NumberSetting("sensibilidad del scroll", "qué tan sensible es la interfaz a la rueda del ratón",
5, -15, 15, 0.5));
public BooleanSetting scrollBar = addSetting(new BooleanSetting("barra de desplazamiento", "renderizar una barra de desplazamiento a la derecha de la interfaz", true));
public BooleanSetting searchBar = addSetting(new BooleanSetting("barra de búsqueda", "renderizar una barra de búsqueda que filtra resultados en todos los marcos abiertos", true));
public BooleanSetting matchCase = addSetting(new BooleanSetting("distinguir mayúsculas", "la búsqueda es sensible a mayúsculas y minúsculas", false));
// ^^^ no sé de qué sirve porque está todo en minúsculas pero bueno
public BooleanSetting blur = addSetting(new BooleanSetting("desenfoque", "desenfocar el fondo mientras la interfaz está abierta", true));
public StringSetting commandPrefix = addSetting(new StringSetting("prefijo", "prefijo de los comandos", "$", 10));
public StringSetting chatName = addSetting(new StringSetting("nombre", "qué nombre usar en notificaciones por el chat", "smegma", 20));
public BooleanSetting multipleKeybinds = addSetting(new BooleanSetting("teclas multimódulo", "permitir asignar la misma tecla a más de un módulo", false));
private int prevRed, prevGreen, prevBlue;
public GUI() {
super("interfaz", "ajustes de la interfaz, y otros misceláneos");
assignKey(GLFW.GLFW_KEY_RIGHT_SHIFT);
// registrar aquí, porque no se añade a ModuleManager.modules. de lo contrario no podría detectar eventos
CameraTweaks.EVENT_BUS.register(this);
keyMode.setVisible(false);
notify.setVisible(false);
searchBar.onUpdate(v -> matchCase.setVisible(v));
}
@SubscribeEvent
public void onLoadCommandManager(LoadCommandManagerEvent event) {
commandPrefix.onUpdate(prefix -> CommandManager.INSTANCE.setPrefix(prefix));
commandPrefix.setDefaultValue(CommandManager.INSTANCE.getPrefix());
chatName.onUpdate(name -> {
ChatUtil.updatePrefix(name);
ModuleManager.INSTANCE.getModuleByClass(ChatPlus.class).updateClientName();
});
}
// lógica un poco prolija pero bueno
@SubscribeEvent
public void onLoadClickGUI(LoadClickGUIEvent event) {
rainbow.onUpdate(v -> {
if (v) {
prevRed = red.getIntValue();
prevGreen = green.getIntValue();
prevBlue = blue.getIntValue();
} else {
red.setValue(prevRed);
green.setValue(prevGreen);
blue.setValue(prevBlue);
}
rainbowSpeed.setVisible(v);
saturation.setVisible(v);
brightness.setVisible(v);
red.setVisible(!v);
green.setVisible(!v);
blue.setVisible(!v);
applyRGBAColorUpdates();
});
red.onUpdate(r -> applyRGBAColorUpdates());
green.onUpdate(g -> applyRGBAColorUpdates());
blue.onUpdate(b -> applyRGBAColorUpdates());
alpha.onUpdate(a -> applyRGBAColorUpdates());
}
@SubscribeEvent
public void onTick(TickEvent.Post event) {
if (rainbow.isEnabled()) {
float speed = (float) (rainbowSpeed.getMax() - rainbowSpeed.getValue());
float hue = (System.currentTimeMillis() % (long) speed) / speed;
Color color = Color.getHSBColor(hue, saturation.getFloatValue(), brightness.getFloatValue());
Colors.red = color.getRed();
Colors.green = color.getGreen();
Colors.blue = color.getBlue();
updateColor();
}
}
private void applyRGBAColorUpdates() {
Colors.red = red.getIntValue();
Colors.green = green.getIntValue();
Colors.blue = blue.getIntValue();
Colors.alpha = alpha.getIntValue();
updateColor();
}
private void updateColor() {
Colors.updateAllColors(new Color(
Colors.red,
Colors.green,
Colors.blue,
Colors.alpha
));
}
}
@@ -1,54 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.*;
import org.lwjgl.glfw.GLFW;
/** lógica del HUD manejada en:
* @see me.retucio.camtweaks.ui.HudRenderer
* @see me.retucio.camtweaks.ui.widgets.HudElement
* @see me.retucio.camtweaks.ui.HudEditorScreen
*/
public class HUD extends Module {
// editor
public KeySetting editorKey = addSetting(new KeySetting("tecla del editor", "tecla asignada al editor de elementos del hud", GLFW.GLFW_KEY_PAGE_UP));
// colores
public NumberSetting red = addSetting(new NumberSetting("rojo", "cantidad de rojo", 255, 0, 255, 1));
public NumberSetting green = addSetting(new NumberSetting("verde", "cantidad de verde", 255, 0, 255, 1));
public NumberSetting blue = addSetting(new NumberSetting("azul", "cantidad de azul", 255, 0, 255, 1));
public BooleanSetting rainbow = addSetting(new BooleanSetting("arcoíris", "gay.", false));
public NumberSetting rainbowSpeed = addSetting(new NumberSetting("velocidad del arcoíris", "velocidad del arcoíris", 1000, 0, 10000, 2));
public NumberSetting alpha = addSetting(new NumberSetting("opacidad", "antitransparencia", 255, 0, 255, 1));
// ajustes
public BooleanSetting showOnF3 = addSetting(new BooleanSetting("mostrar en F3", "renderizar HUD en el menú de debug", false));
public BooleanSetting shadow = addSetting(new BooleanSetting("sombra", "texto con sombra", true));
public NumberSetting timezone = addSetting(new NumberSetting("zona horaria", "zona horaria en UTC+n", 1, -6, 6, 1));
public EnumSetting<TimeFormat> timeFormat = addSetting(new EnumSetting<>("formato de la hora", "12h o 24h", TimeFormat.class, TimeFormat.TWENTY_FOUR_HOUR));
public StringSetting customText = addSetting(new StringSetting("texto custom", "marca de agua (dejar vacío para quitar)", "adolf jitler inshtagram feishbuc twiter", 40));
public HUD() {
super("HUD", "superposición de la pantalla con info. adicional");
rainbow.onUpdate(v -> {
red.setVisible(!v);
green.setVisible(!v);
blue.setVisible(!v);
rainbowSpeed.setVisible(v);
});
}
public enum TimeFormat {
TWENTY_FOUR_HOUR("24h"),
TWELVE_HOUR("12h");
final String name;
TimeFormat(String name) { this.name = name; }
@Override public String toString() { return name; }
}
}
@@ -1,131 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.RenderHeldItemEvent;
import me.retucio.camtweaks.event.events.RenderArmEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.Hand;
import net.minecraft.util.math.RotationAxis;
import org.joml.Vector3d;
/** continúa en:
* @see me.retucio.camtweaks.mixin.HeldItemRendererMixin
*/
public class HandView extends Module {
// ajustes de animaciones
public BooleanSetting oldAnimations = addSetting(new BooleanSetting("animaciones viejas", "como las de la 1.8, al pegar", false));
public BooleanSetting skipSwapping = addSetting(new BooleanSetting("no swap", "se salta la animación de cambiar items de mano", false));
public BooleanSetting noFood = addSetting(new BooleanSetting("no comer", "no renderiza la animación de comer", false));
// ajustes de mano principal
public NumberSetting scaleMainX = addSetting(new NumberSetting("escala de la mano principal (X)", ".",
1, 0.01, 5, 0.1));
public NumberSetting scaleMainY = addSetting(new NumberSetting("escala de la mano principal (Y)", ".",
1, 0.01, 5, 0.1));
public NumberSetting scaleMainZ = addSetting(new NumberSetting("escala de la mano principal (Z)", ".",
1, 0.01, 5, 0.1));
public NumberSetting posMainX = addSetting(new NumberSetting("posición de la mano principal (X)", ".",
0, -3, 3, 0.1));
public NumberSetting posMainY = addSetting(new NumberSetting("posición de la mano principal (Y)", ".",
0, -3, 3, 0.1));
public NumberSetting posMainZ = addSetting(new NumberSetting("posición de la mano principal (Z)", ".",
0, -3, 3, 0.1));
public NumberSetting rotMainX = addSetting(new NumberSetting("rotación de la mano principal (X)", ".",
0, -180, 180, 1));
public NumberSetting rotMainY = addSetting(new NumberSetting("rotación de la mano principal (Y)", ".",
0, -180, 180, 1));
public NumberSetting rotMainZ = addSetting(new NumberSetting("rotación de la mano principal (Z)", ".",
0, -180, 180, 1));
// ajustes de mano secundaria
public NumberSetting scaleOffX = addSetting(new NumberSetting("escala de la mano secundaria (X)", ".",
1, 0.01, 5, 0.1));
public NumberSetting scaleOffY = addSetting(new NumberSetting("escala de la mano secundaria (Y)", ".",
1, 0.01, 5, 0.1));
public NumberSetting scaleOffZ = addSetting(new NumberSetting("escala de la mano secundaria (Z)", ".",
1, 0.01, 5, 0.1));
public NumberSetting posOffX = addSetting(new NumberSetting("posición de la mano secundaria (X)", ".",
0, -3, 3, 0.1));
public NumberSetting posOffY = addSetting(new NumberSetting("posición de la mano secundaria (Y)", ".",
0, -3, 3, 0.1));
public NumberSetting posOffZ = addSetting(new NumberSetting("posición de la mano secundaria (Z)", ".",
0, -3, 3, 0.1));
public NumberSetting rotOffX = addSetting(new NumberSetting("rotación de la mano secundaria (X)", ".",
0, -180, 180, 1));
public NumberSetting rotOffY = addSetting(new NumberSetting("rotación de la mano secundaria (Y)", ".",
0, -180, 180, 1));
public NumberSetting rotOffZ = addSetting(new NumberSetting("rotación de la mano secundaria (Z)", ".",
0, -180, 180, 1));
// brazo
public NumberSetting scaleArmX = addSetting(new NumberSetting("escala del brazo (X)", ".",
1, 0.01, 5, 0.1));
public NumberSetting scaleArmY = addSetting(new NumberSetting("escala del brazo (Y)", ".",
1, 0.01, 5, 0.1));
public NumberSetting scaleArmZ = addSetting(new NumberSetting("escala del brazo (Z)", ".",
1, 0.01, 5, 0.1));
public NumberSetting posArmX = addSetting(new NumberSetting("posición del brazo (X)", ".",
0, -3, 3, 0.1));
public NumberSetting posArmY = addSetting(new NumberSetting("posición del brazo (Y)", ".",
0, -3, 3, 0.1));
public NumberSetting posArmZ = addSetting(new NumberSetting("posición del brazo (Z)", ".",
0, -3, 3, 0.1));
public NumberSetting rotArmX = addSetting(new NumberSetting("rotación del brazo (X)", ".",
0, -180, 180, 1));
public NumberSetting rotArmY = addSetting(new NumberSetting("rotación del brazo (Y)", ".",
0, -180, 180, 1));
public NumberSetting rotArmZ = addSetting(new NumberSetting("rotación del brazo (Z)", ".",
0, -180, 180, 1));
public HandView() {
super("manos", "modifica la manera en la que se renderizan las manos");
}
@SubscribeEvent
public void onHeldItemRender(RenderHeldItemEvent event) {
if (event.getHand() == Hand.MAIN_HAND) {
scale(event.getMatrices(), new Vector3d(scaleMainX.getValue(), scaleMainY.getValue(), scaleMainZ.getValue()));
translate(event.getMatrices(), new Vector3d(posMainX.getValue(), posMainY.getValue(), posMainZ.getValue()));
rotate(event.getMatrices(), new Vector3d(rotMainX.getValue(), rotMainY.getValue(), rotMainZ.getValue()));
}
else {
scale(event.getMatrices(), new Vector3d(scaleOffX.getValue(), scaleOffY.getValue(), scaleOffZ.getValue()));
translate(event.getMatrices(), new Vector3d(posOffX.getValue(), posOffY.getValue(), posOffZ.getValue()));
rotate(event.getMatrices(), new Vector3d(rotOffX.getValue(), rotOffY.getValue(), rotOffZ.getValue()));
}
}
@SubscribeEvent
public void onRenderArm(RenderArmEvent event) {
scale(event.getMatrices(), new Vector3d(scaleArmX.getValue(), scaleArmY.getValue(), scaleArmZ.getValue()));
translate(event.getMatrices(), new Vector3d(posArmX.getValue(), posArmY.getValue(), posArmZ.getValue()));
rotate(event.getMatrices(), new Vector3d(rotArmX.getValue(), rotArmY.getValue(), rotArmZ.getValue()));
}
private void rotate(MatrixStack matrix, Vector3d rotation) {
matrix.multiply(RotationAxis.POSITIVE_X.rotationDegrees((float) rotation.x));
matrix.multiply(RotationAxis.POSITIVE_Y.rotationDegrees((float) rotation.y));
matrix.multiply(RotationAxis.POSITIVE_Z.rotationDegrees((float) rotation.z));
}
private void scale(MatrixStack matrix, Vector3d scale) {
matrix.scale((float) scale.x, (float) scale.y, (float) scale.z);
}
private void translate(MatrixStack matrix, Vector3d translation) {
matrix.translate((float) translation.x, (float) translation.y, (float) translation.z);
}
}
@@ -1,87 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.EnumSetting;
import me.retucio.camtweaks.module.settings.ListSetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
import me.retucio.camtweaks.util.Lists;
import net.minecraft.particle.ParticleType;
import net.minecraft.util.Formatting;
/** continúa en:
* @see me.retucio.camtweaks.mixin.ClientPlayNetworkHandlerMixin
* @see me.retucio.camtweaks.mixin.EntityEffectParticleEffectMixin
* @see me.retucio.camtweaks.mixin.FogRendererMixin
* @see me.retucio.camtweaks.mixin.GameRendererMixin
* @see me.retucio.camtweaks.mixin.InGameHudMixin
* @see me.retucio.camtweaks.mixin.InGameOverlayRendererMixin
* @see me.retucio.camtweaks.mixin.ParticleManagerMixin
* @see me.retucio.camtweaks.mixin.StuckArrowsFeatureRendererMixin
* @see me.retucio.camtweaks.mixin.TextRendererDrawerMixin
* @see me.retucio.camtweaks.mixin.WeatherRenderingMixin
*/
public class NoRender extends Module {
public BooleanSetting spyglassOverlay = addSetting(new BooleanSetting("catalejo", "renderizar overlay del catalejo", false));
public BooleanSetting fluidOverlay = addSetting(new BooleanSetting("fluídos", "renderizar fluídos sobre la cámara como el agua, lava o nieve en polvo (aunque no sea un fluído)", false));
public BooleanSetting pumpkinOverlay = addSetting(new BooleanSetting("calabaza", "renderiza el overlay de la calabaza tallada", false));
public BooleanSetting fireOverlay = addSetting(new BooleanSetting("fuego", "renderizar llamas sobre la cámara", false));
public BooleanSetting portalOverlay = addSetting(new BooleanSetting("portal", "renderizar el overlay del portal del nether", false));
public BooleanSetting rain = addSetting(new BooleanSetting("lluvia", "l l u v i a", true));
public BooleanSetting snow = addSetting(new BooleanSetting("nieve", "n i e v e", true));
public BooleanSetting dimensionFog = addSetting(new BooleanSetting("niebla de dimensión", "n i e b l a", true));
public BooleanSetting endFlashes; // para cuando actualice
public ListSetting<ParticleType<?>> particles = addSetting(new ListSetting<>("partículas", "lista de partículas que se renderizan",
Lists.particleList, Lists.allTrue(Lists.particleList), Lists.particleNames));
public BooleanSetting nauseaEffect = addSetting(new BooleanSetting("náusea", "renderizar borrachera", false));
public BooleanSetting blindnessEffect = addSetting(new BooleanSetting("ceguera", "renderizar miopía", false));
public BooleanSetting darknessEffect = addSetting(new BooleanSetting("oscuridad", "renderizar miedo a la oscuridad", false));
public BooleanSetting nightVisionEffect;
public BooleanSetting scoreboard = addSetting(new BooleanSetting("marcador", "mostrar marcador a la derecha", false));
public BooleanSetting titles = addSetting(new BooleanSetting("títulos", "mostrar títulos (del comando /title)", false));
public BooleanSetting totemPop = addSetting(new BooleanSetting("tótem", "renderizar el pop del tótem", true));
public BooleanSetting stuckArrows = addSetting(new BooleanSetting("flechas clavadas", "renderizar flechas clavadas en jugadores", false));
public BooleanSetting bold = addSetting(new BooleanSetting("negrita", "letra pero §lgorda", true));
// public BooleanSetting italics = addSetting(new BooleanSetting("cursiva", "letra pero §otorcida", true));
public BooleanSetting underlined = addSetting(new BooleanSetting("subrayado", "letra pero §nen el suelo", true));
public BooleanSetting strikethrough = addSetting(new BooleanSetting("tachado", "letra pero §mdiscriminada", true));
public EnumSetting<Colors> color = addSetting(new EnumSetting<>("colores", "§co§4r§6g§eu§al§2l§9o §1g§5a§dy", Colors.class, Colors.DEFAULT));
public BooleanSetting scrambledText = addSetting(new BooleanSetting("garabato", "engarabatar texto (o como se diga) (§kasí§r)", false));
public NoRender() {
super("no render", "customiza qué se renderiza y qué no");
}
public enum Colors {
BLACK("negro"),
DARK_BLUE("azul oscuro"),
DARK_GREEN("verde"),
DARK_AQUA("cian"),
DARK_RED("granate"),
DARK_PURPLE("morado"),
GOLD("naranja"),
GRAY("gris claro"),
DARK_GRAY("gris oscuro"),
BLUE("azul"),
GREEN("lima"),
AQUA("turquesa"),
RED("rojo"),
LIGHT_PURPLE("lila"),
YELLOW("amarillo"),
WHITE("blanco"),
DEFAULT("por defecto");
private final String name;
Colors(String name) { this.name = name; }
@Override public String toString() { return name; }
public Formatting toFormatting() { return (Formatting.byColorIndex(this.ordinal())); }
}
}
@@ -1,59 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.MouseScrollEvent;
import me.retucio.camtweaks.event.events.PerspectiveChangeEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.*;
import me.retucio.camtweaks.util.KeyUtil;
import org.lwjgl.glfw.GLFW;
// continúa en CameraMixin
public class PerspectivePlus extends Module {
private double distance;
// ajustes
public BooleanSetting clip = addSetting(new BooleanSetting(
"clip", "atravesar bloques con la cámara", true));
public NumberSetting defaultDistance = addSetting(new NumberSetting(
"distancia", "distancia a la que está la cámara del jugador por defecto",
4, 1, 20, 0.2));
public NumberSetting scrollSens = addSetting(new NumberSetting(
"sensibilidad del scroll", "sensibilidad de la rueda del ratón (0 para desactivar)",
1, 0, 8, 0.1));
public KeySetting scrollKey = addSetting(new KeySetting("tecla del scroll", "qué tecla mantener para usar la rueda del ratón", GLFW.GLFW_KEY_LEFT_ALT));
public PerspectivePlus() {
super("perspectiva plus", "añade cositas chulas al cambio de perspectiva");
}
@Override
public void onEnable() {
distance = defaultDistance.getValue();
super.onEnable();
}
@SubscribeEvent
public void onPerspectiveChange(PerspectiveChangeEvent event) {
distance = defaultDistance.getValue();
}
@SubscribeEvent
public void onMouseScroll(MouseScrollEvent event) {
if (mc.options.getPerspective() == net.minecraft.client.option.Perspective.FIRST_PERSON
|| mc.currentScreen != null || scrollSens.getValue() <= 0) return;
if (KeyUtil.isKeyDown(scrollKey.getKey())) {
distance -= event.getVertical() / 4 * (scrollSens.getValue() * distance);
event.cancel();
}
}
public double getDistance() {
return distance;
}
}
@@ -1,14 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
/** continúa en:
* @see me.retucio.camtweaks.mixin.ClientPlayerEntityMixin
*/
public class PortalGUI extends Module {
public PortalGUI() {
super("interfaz en portales", "te permite abrir interfaces dentro de portales, como el chat o el inventario");
}
}
@@ -1,85 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.PacketEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.EnumSetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
import net.minecraft.network.packet.s2c.play.WorldTimeUpdateS2CPacket;
// continúa en ClientWorldPropertiesMixin, DimensionTypeMixin,
public class TimeChanger extends Module {
public BooleanSetting renderSun = addSetting(new BooleanSetting("sol", "que haya sol o no", true));
public BooleanSetting renderMoon = addSetting(new BooleanSetting("luna", "que haya luna o no", true));
public BooleanSetting renderStars = addSetting(new BooleanSetting("estrellas", "que hayan estrellas o no", true));
public EnumSetting<MoonPhases> moonPhase = addSetting(new EnumSetting<>("fase lunar", "fase lunar actual", MoonPhases.class, MoonPhases.DEFAULT));
public NumberSetting time = addSetting(new NumberSetting("hora", "hora del juego", 0, -20000, 20000, 1));
public TimeChanger() {
super("cielo custom", "te deja cambiar visualmente el progreso del día");
renderMoon.onUpdate(v -> moonPhase.setVisible(v));
}
private long realTime;
@Override
public void onEnable() {
if (mc.world == null) return;
realTime = mc.world.getTime();
}
@Override
public void onDisable() {
if (mc.world == null) return;
mc.world.getLevelProperties().setTimeOfDay(realTime);
}
@SubscribeEvent
public void onPacketReceive(PacketEvent.Receive event) {
if (event.getPacket() instanceof WorldTimeUpdateS2CPacket packet) {
realTime = packet.timeOfDay();
event.cancel();
}
}
@Override
public void onTick() {
if (mc.world == null) return;
mc.world.getLevelProperties().setTimeOfDay(time.getLongValue());
}
public int getMoonPhase() {
if (mc.world == null) return -1;
return switch (moonPhase.getValue()) {
case DEFAULT -> (int) (mc.world.getLunarTime() / 24000L) % 8;
case FULL_MOON -> 0;
case WANING_GIBBOUS -> 1;
case LAST_QUARTER -> 2;
case WANING_CRESCENT -> 3;
case NEW_MOON -> 4;
case WAXING_CRESCENT -> 5;
case FIRST_QUARTER -> 6;
case WAXING_GIBBOUS -> 7;
};
}
public enum MoonPhases {
DEFAULT("por defecto"),
FULL_MOON("luna llena"),
WANING_GIBBOUS("menguante gibosa"),
LAST_QUARTER("cuarto menguante"),
WANING_CRESCENT("luna vieja"),
NEW_MOON("luna nueva"),
WAXING_CRESCENT("creciente"),
FIRST_QUARTER("cuarto creciente"),
WAXING_GIBBOUS("creciente gibosa");
private final String name;
MoonPhases(String name) { this.name = name; }
@Override public String toString() { return name; }
}
}
@@ -1,51 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.EnumSetting;
import me.retucio.camtweaks.module.settings.KeySetting;
import org.lwjgl.glfw.GLFW;
public class TooltipsPlus extends Module {
public EnumSetting<DisplayModes> displayMode = addSetting(new EnumSetting<>(
"mostrar", "cúando mostrar la cajita de los huevos", DisplayModes.class, DisplayModes.ALWAYS));
public KeySetting displayKey = addSetting(new KeySetting(
"tecla de visualización", "tecla a presionar para mostrar la cajita", GLFW.GLFW_KEY_LEFT_CONTROL));
public BooleanSetting middleClickPreview = addSetting(new BooleanSetting("preview de middle click",
"abre una interfaz con los contenidos de un bloque de almacenamiento al presionar el middle click (la ruedita)", false));
public EnumSetting<SizeFormat> itemSize = addSetting(new EnumSetting<>(
"tamaño del ítem", "cómo mostrar el tamaño del ítem en memoria", SizeFormat.class, SizeFormat.NONE));
public TooltipsPlus() {
super("tooltips plus", "mejoras varias a las cajitas de descripción de items");
}
public enum DisplayModes {
ALWAYS("siempre"),
KEY("al presionar una tecla"),
NEVER("nunca");
final String name;
DisplayModes(String name) { this.name = name; }
@Override public String toString() { return name; }
}
public enum SizeFormat {
NONE("no mostrar"),
BYTES("bytes"),
KB("kilobytes"),
MB("megabytes");
final String name;
SizeFormat(String name) { this.name = name; }
@Override public String toString() { return name; }
}
}
@@ -1,100 +0,0 @@
package me.retucio.camtweaks.module.modules;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.GetFOVEvent;
import me.retucio.camtweaks.event.events.MouseScrollEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.module.settings.KeySetting;
import me.retucio.camtweaks.module.settings.NumberSetting;
import me.retucio.camtweaks.util.KeyUtil;
import org.lwjgl.glfw.GLFW;
// continúa en GameRendererMixin
public class Zoom extends Module {
public BooleanSetting showHands = addSetting(new BooleanSetting("mostrar manos", "esconde o muestra las manos al hacer zoom", true));
public BooleanSetting showHUD = addSetting(new BooleanSetting("mostrar HUD", "esconde o muestra los indicadores en pantalla", true));
public NumberSetting scrollSens = addSetting(new NumberSetting("sensibilidad del scroll", "sensibilidad de la rueda del ratón (0 para desactivar)",
0.4, 0, 8, 0.1));
public KeySetting scrollKey = addSetting(new KeySetting("tecla del scroll", "qué tecla mantener para usar la rueda del ratón", GLFW.GLFW_KEY_LEFT_CONTROL));
public NumberSetting defaultZoom = addSetting(new NumberSetting("zoom", "cantidad de zoom",
6, 1, 10, 0.1));
public NumberSetting mouseSensMultiplier = addSetting(new NumberSetting("sensibilidad", "multiplicador de la sensibilidad del ratón",
0.7, 0.01, 1, 0.05));
public BooleanSetting smoothCam = addSetting(new BooleanSetting("cámara cinemática", "usa la cámara cinemática mientras hagas zoom", false));
private boolean prevSmoothCam;
private double prevMouseSens;
private double prevFov;
private boolean prevHUD;
private double value;
public Zoom() {
super("zoom", "lupa");
super.keyMode.setValue(KeyModes.HOLD);
super.keyMode.setDefaultValue(KeyModes.HOLD);
super.notify.setEnabled(false);
super.notify.setDefaultValue(false);
assignKey(GLFW.GLFW_KEY_F);
}
@Override
public void onEnable() {
if (mc.options == null) return;
CameraTweaks.EVENT_BUS.register(this);
prevSmoothCam = mc.options.smoothCameraEnabled;
prevMouseSens = mc.options.getMouseSensitivity().getValue();
prevFov = mc.options.getFov().getValue();
prevHUD = mc.options.hudHidden;
mc.options.hudHidden = !showHUD.isEnabled();
value = defaultZoom.getValue();
}
@Override
public void onDisable() {
if (mc.options == null) return;
CameraTweaks.EVENT_BUS.unregister(this);
mc.options.smoothCameraEnabled = prevSmoothCam;
mc.options.getMouseSensitivity().setValue(prevMouseSens);
mc.options.hudHidden = prevHUD;
mc.worldRenderer.scheduleTerrainUpdate();
}
@Override
public void onTick() {
mc.options.smoothCameraEnabled = smoothCam.isEnabled();
if (!smoothCam.isEnabled())
mc.options.getMouseSensitivity().setValue(prevMouseSens * mouseSensMultiplier.getValue());
}
@SubscribeEvent
private void onMouseScroll(MouseScrollEvent event) {
boolean key = scrollKey.getKey() == GLFW.GLFW_KEY_UNKNOWN || KeyUtil.isKeyDown(scrollKey.getKey());
if (isEnabled() && scrollSens.getValue() > 0 && key) {
value += event.getVertical() * 0.25 * (scrollSens.getValue() * value);
if (value < 1) value = 1;
event.cancel();
}
}
@SubscribeEvent
private void onGetFov(GetFOVEvent event) {
event.setFov((float) (event.getFov() / value));
if (prevFov != event.getFov()) mc.worldRenderer.scheduleTerrainUpdate();
prevFov = event.getFov();
}
}
@@ -1,58 +0,0 @@
package me.retucio.camtweaks.module.settings;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.camtweaks.UpdateSettingEvent;
import me.retucio.camtweaks.module.Module;
// base para los tipos de ajustes
public abstract class AbstractSetting {
private final String name;
private final String description;
private boolean visible = true;
private boolean searchMatch = true;
private Module module;
protected AbstractSetting(String name, String description) {
this.name = name;
this.description = description;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isSearchMatch() {
return searchMatch;
}
public void setSearchMatch(boolean searchMatch) {
this.searchMatch = searchMatch;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Module getModule() {
return module;
}
public void setModule(Module module) {
this.module = module;
}
public void fireUpdateEvent() {
CameraTweaks.EVENT_BUS.post(new UpdateSettingEvent(this, module.shouldSaveSettings()));
}
}
@@ -1,55 +0,0 @@
package me.retucio.camtweaks.module.settings;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.camtweaks.UpdateSettingEvent;
import java.util.function.Consumer;
// ajuste booleano, es decir, o se encuentra encencido o apagado (similar a un interruptor)
public class BooleanSetting extends AbstractSetting {
private boolean defaultValue;
private boolean enabled;
private Consumer<Boolean> updateListener;
public BooleanSetting(String name, String description, boolean defaultValue) {
super(name, description);
this.enabled = defaultValue;
this.defaultValue = defaultValue;
}
public void toggle() {
setEnabled(!enabled);
if (updateListener != null) updateListener.accept(enabled);
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
if (this.enabled != enabled) {
this.enabled = enabled;
fireUpdateEvent();
if (updateListener != null) updateListener.accept(enabled);
}
}
public boolean getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(boolean value) {
defaultValue = value;
}
public void reset() {
setEnabled(defaultValue);
}
public void onUpdate(Consumer<Boolean> listener) {
this.updateListener = listener;
if (updateListener != null) updateListener.accept(enabled); // actualizar por primera vez
}
}
@@ -1,72 +0,0 @@
package me.retucio.camtweaks.module.settings;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.ui.frames.ClientSettingsFrame;
import me.retucio.camtweaks.util.ChatUtil;
import me.retucio.camtweaks.util.KeyUtil;
import org.lwjgl.glfw.GLFW;
import java.util.function.Consumer;
public class KeySetting extends AbstractSetting {
private int key;
private int defaultKey;
private Consumer<Integer> updateListener;
public KeySetting(String name, String description, int defaultKey) {
super(name, description);
this.key = defaultKey;
this.defaultKey = defaultKey;
}
public int getKey() {
return key;
}
public void setKey(int key) {
if (this.key == key) return;
if (key == GLFW.GLFW_KEY_ESCAPE) {
this.key = GLFW.GLFW_KEY_UNKNOWN; // asignar la tecla ESC a deshabilitar la tecla
fireUpdateEvent();
if (updateListener != null) updateListener.accept(key);
return;
}
if (ModuleManager.INSTANCE != null) {
for (Module module : ModuleManager.INSTANCE.getModules())
if (module.getKey() == key && !ClientSettingsFrame.guiSettings.multipleKeybinds.isEnabled() && key != -1) {
module.setKey(-1);
ChatUtil.info("tecla del módulo " + module.getName() + " restablecida");
}
}
this.key = key;
fireUpdateEvent();
if (updateListener != null) updateListener.accept(key);
}
public int getDefaultKey() {
return defaultKey;
}
public void setDefaultKey(int key) {
this.defaultKey = key;
}
public String getKeyName() {
return KeyUtil.getKeyName(key);
}
public void reset() {
setKey(defaultKey);
}
public void onUpdate(Consumer<Integer> listener) {
this.updateListener = listener;
if (updateListener != null) updateListener.accept(key);
}
}
@@ -1,97 +0,0 @@
package me.retucio.camtweaks.module.settings;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.camtweaks.UpdateSettingEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class ListSetting<T> extends AbstractSetting {
private final List<T> options;
private Map<T, Boolean> values;
private Map<T, Boolean> defaultValues;
private Map<T, String> displayNames = null;
private Consumer<Map<T, Boolean>> updateListener;
public ListSetting(String name, String description, List<T> options, Map<T, Boolean> initialValues) {
super(name, description);
this.options = options;
this.defaultValues = new HashMap<>();
for (T option : options) {
boolean enabled = initialValues != null && initialValues.getOrDefault(option, false);
defaultValues.put(option, enabled);
}
this.values = new HashMap<>(defaultValues);
}
public ListSetting(String name, String description, List<T> options, Map<T, Boolean> initialValues, Map<T, String> displayNames) {
this(name, description, options, initialValues);
this.displayNames = displayNames;
}
public boolean isEnabled(T option) {
return values.getOrDefault(option, false);
}
public void setEnabled(T option, boolean enabled) {
if (values.containsKey(option) && values.get(option) != enabled) {
values.put(option, enabled);
fireUpdateEvent();
if (updateListener != null) updateListener.accept(new HashMap<>(values));
}
}
public void toggle(T option) {
setEnabled(option, !isEnabled(option));
}
public Map<T, Boolean> getValues() {
return new HashMap<>(values);
}
public void setValues(Map<T, Boolean> values) {
this.values = new HashMap<>(values);
}
public Map<T, Boolean> getDefaultValues() {
return new HashMap<>(defaultValues);
}
public void setDefaultValues(Map<T, Boolean> values) {
defaultValues = values;
}
public void reset() {
values.clear();
values.putAll(defaultValues);
fireUpdateEvent();
if (updateListener != null) updateListener.accept(new HashMap<>(values));
}
public void setAll(boolean enabled) {
for (T option : options) values.put(option, enabled);
}
public void onUpdate(Consumer<Map<T, Boolean>> listener) {
this.updateListener = listener;
if (updateListener != null) updateListener.accept(new HashMap<>(values));
}
public List<T> getOptions() {
return options;
}
public Map<T, String> getDisplayNames() {
return displayNames;
}
public String getDisplayName(T key) {
if (displayNames != null) return displayNames.get(key);
return key.toString();
}
}
@@ -1,54 +0,0 @@
package me.retucio.camtweaks.module.settings;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.camtweaks.UpdateSettingEvent;
import java.util.function.Consumer;
public class StringSetting extends AbstractSetting {
private String value;
private String defaultValue;
private final int maxLength;
private Consumer<String> updateListener;
public StringSetting(String name, String description, String defaultValue, int maxLength) {
super(name, description);
this.value = defaultValue;
this.defaultValue = defaultValue;
this.maxLength = maxLength;
}
public String getValue() {
return value;
}
public void setValue(String value) {
if (this.value.equals(value)) return;
this.value = value.length() > maxLength ? value.substring(0, maxLength) : value;
fireUpdateEvent();
if (updateListener != null) updateListener.accept(this.value);
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public void reset() {
setValue(defaultValue);
}
public int getMaxLength() {
return maxLength;
}
public void onUpdate(Consumer<String> listener) {
this.updateListener = listener;
if (updateListener != null) updateListener.accept(value);
}
}
@@ -1,305 +0,0 @@
package me.retucio.camtweaks.ui;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.KeyEvent;
import me.retucio.camtweaks.event.events.MouseClickEvent;
import me.retucio.camtweaks.event.events.MouseScrollEvent;
import me.retucio.camtweaks.event.events.camtweaks.SettingsFrameEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.AbstractSetting;
import me.retucio.camtweaks.ui.buttons.ListButton;
import me.retucio.camtweaks.ui.buttons.SettingButton;
import me.retucio.camtweaks.ui.frames.ClientSettingsFrame;
import me.retucio.camtweaks.ui.frames.ModuleFrame;
import me.retucio.camtweaks.ui.frames.SettingsFrame;
import me.retucio.camtweaks.ui.widgets.ScrollBarWidget;
import me.retucio.camtweaks.ui.widgets.SearchBarWidget;
import me.retucio.camtweaks.util.KeyUtil;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.Click;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
import org.lwjgl.glfw.GLFW;
import java.util.ArrayList;
import java.util.List;
import static me.retucio.camtweaks.ui.frames.ClientSettingsFrame.guiSettings;
// interfaz gráfica, se abre con el shift derecho por defecto. aquí se encuentran los módulos y sus ajustes
public class ClickGUI extends Screen {
public static ClickGUI INSTANCE;
private boolean anyFocused;
private Object selected = null;
private final ModuleFrame modulesFrame = new ModuleFrame(20, 30, 100, 20);
private final List<SettingsFrame> settingsFrames = new ArrayList<>();
private final ClientSettingsFrame guiSettingsFrame = new ClientSettingsFrame(200, 30, 100, 20);
private final ScrollBarWidget scrollBar = new ScrollBarWidget();
private final SearchBarWidget searchBar = new SearchBarWidget(340, 16, 300, 20);
private final MinecraftClient mc = MinecraftClient.getInstance();
public ClickGUI() {
super(Text.of("interfaz"));
settingsFrames.add(guiSettingsFrame);
CameraTweaks.EVENT_BUS.register(this);
}
@Override
public void render(DrawContext ctx, int mouseX, int mouseY, float delta) {
scrollBar.setWindowHeight(mc.getWindow().getScaledHeight());
scrollBar.setContentHeight(calculateContentHeight());
scrollBar.render(ctx, mouseX, mouseY);
int scrollOffset = scrollBar.getScrollOffset();
searchBar.updateRenderY(scrollOffset);
searchBar.render(ctx, mouseX, mouseY, delta);
searchBar.updatePosition(mouseX, mouseY);
// actualizar la posición de renderizado vertical de los marcos cada tick
modulesFrame.updateRenderY(scrollOffset);
for (SettingsFrame sf : settingsFrames)
sf.updateRenderY(scrollOffset);
// renderizar el marco de los ajustes de cada módulo que lo tenga abierto. se abre haciendo clic derecho sobre el módulo
for (SettingsFrame sf : settingsFrames.reversed()) {
sf.render(ctx, mouseX, mouseY, delta);
sf.updatePosition(mouseX, mouseY);
}
// renderizar el marco de los módulos
modulesFrame.render(ctx, mouseX, mouseY, delta);
modulesFrame.updatePosition(mouseX, mouseY);
for (SettingsFrame sf : settingsFrames)
sf.drawTooltips(ctx, mouseX, mouseY);
filterSearchResults();
super.render(ctx, mouseX, mouseY, delta);
}
private int calculateContentHeight() {
int bottom = modulesFrame.y + modulesFrame.h + modulesFrame.totalHeight;
for (SettingsFrame frame : settingsFrames)
bottom = Math.max(bottom, frame.y + frame.h + frame.totalHeight);
return bottom + 20; // padding
}
public boolean mouseClicked(Click click, boolean doubled) {
scrollBar.mouseClicked(click.x(), click.y(), click.button());
searchBar.mouseClicked(click.x(), click.y(), click.button());
// detectar clics sobre los marcos
modulesFrame.mouseClicked(click.x(), click.y(), click.button());
for (SettingsFrame sf : new ArrayList<>(settingsFrames))
sf.mouseClicked(click.x(), click.y(), click.button());
return super.mouseClicked(click, doubled);
}
@Override
public boolean mouseReleased(Click click) {
scrollBar.mouseReleased(click.x(), click.y(), click.button());
searchBar.mouseReleased(click.x(), click.y(), click.button());
// registrar cuándo se suelta el clic, en cada marco respectivamente
modulesFrame.mouseReleased(click.x(), click.y(), click.button());
for (SettingsFrame sf : new ArrayList<>(settingsFrames))
sf.mouseRelease(click.x(), click.y(), click.button());
return super.mouseReleased(click);
}
@Override
public boolean mouseDragged(Click click, double deltaX, double deltaY) {
scrollBar.mouseDragged(click.y());
return super.mouseDragged(click, deltaX, deltaY);
}
@SubscribeEvent
public void onKey(KeyEvent event) {
searchBar.onKey(event.getKey(), event.getAction());
}
@SubscribeEvent
public void onMouseScroll(MouseScrollEvent event) {
// subir y bajar la pantalla con la rueda del ratón
scrollBar.onMouseScroll(event.getVertical() * guiSettings.scrollSens.getValue());
}
@SubscribeEvent
public void onMouseMiddleButton(MouseClickEvent event) {
// mover todos los marcos a un punto visible al presionar shift + la rueda del ratón
if (CameraTweaks.mc.currentScreen != this || event.getButton() != 2 || !KeyUtil.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT)) return;
int h = CameraTweaks.mc.getWindow().getScaledHeight();
int minY = Math.min(modulesFrame.y, settingsFrames.stream().mapToInt(sf -> sf.y).min().orElse(modulesFrame.y));
int maxY = Math.max(modulesFrame.y + modulesFrame.h, settingsFrames.stream().mapToInt(sf -> sf.y + sf.h).max().orElse(modulesFrame.y + modulesFrame.h));
int correction = minY < 0 ? -minY + 4 : (maxY > h ? h - maxY - 4 : 0);
if (correction != 0) {
modulesFrame.y += correction;
settingsFrames.forEach(sf -> sf.y += correction);
}
}
public void filterSearchResults() {
if (!guiSettings.searchBar.isEnabled()) return;
String searchInput = searchBar.getSearchInput().trim();
if (!guiSettings.matchCase.isEnabled()) searchInput = searchInput.toLowerCase();
for (SettingsFrame sf : settingsFrames) {
for (SettingButton sb : sf.getButtons()) {
AbstractSetting setting = sb.getSetting();
if (searchInput.isEmpty()) {
setting.setSearchMatch(true);
continue;
}
String name = setting.getName();
String description = setting.getDescription();
if (!guiSettings.matchCase.isEnabled()) {
name = name.toLowerCase();
description = description.toLowerCase();
}
setting.setSearchMatch(name.contains(searchInput) || description.contains(searchInput));
}
}
}
public void openSettingsFrame(Module module, int x, int y) {
// abrir un marco donde se encuentran los ajustes del módulo deseado
if (isSettingsFrameOpen(module)) return; // permitir un solo marco de ajustes por módulo
SettingsFrame frame = new SettingsFrame(module, x, y, 120, 20);
settingsFrames.add(frame);
CameraTweaks.EVENT_BUS.post(new SettingsFrameEvent.Open(frame));
}
public void openListSettingsFrame(Module module, int x, int y) {
if (isSettingsFrameOpen(module)) return;
SettingsFrame frame = new SettingsFrame(module, x, y, 120, 18);
settingsFrames.add(frame);
}
// cerrar el marco de ajustes
public void closeSettingsFrame(Module module) {
// porque java.util.ConcurrentModificationException o algo no sé es lo único que se me ha ocurrido hacer
List<SettingsFrame> toRemove = new ArrayList<>();
for (SettingsFrame sf : settingsFrames) {
if (sf.module == module) {
CameraTweaks.EVENT_BUS.post(new SettingsFrameEvent.Close(sf));
toRemove.add(sf);
unselect(sf);
}
}
settingsFrames.removeAll(toRemove);
}
// verificar si un módulo tiene su marco de ajustes abierto
public boolean isSettingsFrameOpen(Module module) {
return settingsFrames.stream()
.anyMatch(sf -> sf.module.getName().equals(module.getName()));
}
public void refreshListButtons() {
for (SettingsFrame frame : settingsFrames)
for (SettingButton button : frame.getButtons())
if (button instanceof ListButton<?> lb)
lb.refreshDummy();
}
// métodos del súper
@Override
public void close() { // evitar que al reabrir la interfaz sin previamente haber soltado el clic, se sigan arrastrando objetos
modulesFrame.mouseReleased(0, 0, 0);
settingsFrames.forEach(sf -> sf.mouseRelease(0, 0, 0));
scrollBar.mouseReleased(0, 0, 0);
searchBar.mouseReleased(0, 0, 0);
unselect(selected);
super.close();
}
@Override
public boolean shouldPause() {
// no pausar el juego cuando se abre la interfaz
return false;
}
@Override
public boolean shouldCloseOnEsc() {
return super.shouldCloseOnEsc() && !anyFocused;
}
@Override
protected void applyBlur(DrawContext ctx) {
if (guiSettings.blur.isEnabled()) super.applyBlur(ctx);
}
// getters y setters de widgets
public ModuleFrame getModulesFrame() {
return modulesFrame;
}
public ClientSettingsFrame getGuiSettingsFrame() {
return guiSettingsFrame;
}
public List<SettingsFrame> getSettingsFrames() {
return settingsFrames;
}
public SearchBarWidget getSearchBar() {
return searchBar;
}
public void setAnyFocused(boolean anyFocused) {
this.anyFocused = anyFocused;
}
// selección de widgets
public Object getSelected() {
return selected;
}
public void setSelected(Object object) {
this.selected = object;
}
public boolean canSelect(Object object) {
return getSelected() == null || getSelected() == object;
}
public boolean trySelect(Object object) {
if (canSelect(object)) {
setSelected(object);
return true;
}
return false;
}
public void unselect(Object object) {
if (selected == object) setSelected(null);
}
}
@@ -1,215 +0,0 @@
package me.retucio.camtweaks.ui;
import me.retucio.camtweaks.config.ConfigManager;
import me.retucio.camtweaks.ui.frames.ClientSettingsFrame;
import me.retucio.camtweaks.ui.widgets.HudElement;
import me.retucio.camtweaks.util.Colors;
import me.retucio.camtweaks.util.KeyUtil;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.Click;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.input.KeyInput;
import net.minecraft.text.Text;
import org.lwjgl.glfw.GLFW;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class HudEditorScreen extends Screen {
public static HudEditorScreen INSTANCE;
private final MinecraftClient mc = MinecraftClient.getInstance();
private final List<HudElement> elements = new ArrayList<>();
@Nullable private HudElement selected = null;
private boolean dragging = false;
private int dragOffsetX, dragOffsetY;
public HudEditorScreen() {
super(Text.literal("editor del hud"));
}
public void setElements(List<HudElement> elements) {
this.elements.clear();
this.elements.addAll(elements);
}
@Override
public void render(DrawContext ctx, int mouseX, int mouseY, float delta) {
ctx.fill(0, 0, this.width, this.height, Colors.hudEditorScreenBackgroundColor.getRGB());
// texto con instrucciones
ctx.drawCenteredTextWithShadow(mc.textRenderer, "EDITOR DEL HUD", this.width / 2, this.height / 2 - mc.textRenderer.fontHeight, -1);
ctx.drawCenteredTextWithShadow(mc.textRenderer,
Text.literal("arrastrar para mover · click derecho para alternar visibilidad · esc para guardar y salir · shift + click derecho para restablecer"),
this.width / 2, this.height / 2 + mc.textRenderer.fontHeight, Colors.instructionsTextColor.getRGB());
// dibujar elementos
for (HudElement element : elements)
element.renderPreview(ctx);
// tooltips con información sobre el elemento sobre el que está el puntero del ratón
if (!dragging) {
for (HudElement element : elements) {
if (!element.isVisible()) continue;
if (element.contains(mouseX, mouseY)) {
List<Text> tooltip = getTooltipFor(element);
if (!tooltip.isEmpty()) ctx.drawTooltip(mc.textRenderer, tooltip, mouseX + 7, mouseY + 20);
break;
}
}
}
super.render(ctx, mouseX, mouseY, delta);
}
@Override
public boolean mouseClicked(Click click, boolean doubled) {
int mouseX = (int) click.x();
int mouseY = (int) click.y();
// iterar de atrás a adelante para respetar el orden z
for (int i = elements.size() - 1; i >= 0; i--) {
HudElement element = elements.get(i);
if (element.contains(mouseX, mouseY)) {
selected = element;
if (click.button() == 0) {
dragging = true;
dragOffsetX = mouseX - element.getX();
dragOffsetY = mouseY - element.getY();
// traer el elemento seleccionado al frente
elements.remove(i);
elements.add(element);
return true;
} else if (click.button() == 1) {
if (mc.isShiftPressed())
selected.resetPosition();
else
selected.setVisible(!selected.isVisible());
return true;
}
}
}
return super.mouseClicked(click, doubled);
}
@Override
public boolean mouseDragged(Click click, double deltaX, double deltaY) {
if (!dragging || selected == null || click.button() != 0)
return super.mouseDragged(click, deltaX, deltaY);
int mouseX = (int) click.x();
int mouseY = (int) click.y();
int newX = mouseX - dragOffsetX;
int newY = mouseY - dragOffsetY;
// clampear para evitar que los elementos se salgan de la pantalla
newX = Math.max(1, Math.min(newX, width - selected.getWidth() - 1));
newY = Math.max(1, Math.min(newY, height - selected.getHeight() - 1));
selected.setPosition(newX, newY);
return true;
}
@Override
public boolean mouseReleased(Click click) {
if (dragging && click.button() == 0) {
dragging = false;
savePositionsToConfig(); // guardar inmediatamente al config
return true;
} else if (click.button() == 1 && selected != null) {
saveVisibilitiesToConfig();
selected = null;
return true;
}
selected = null;
return super.mouseReleased(click);
}
@Override
public boolean keyPressed(KeyInput input) {
// esc para guardar y salir
if (input.key() == GLFW.GLFW_KEY_ESCAPE) {
saveAndClose();
return true;
}
return super.keyPressed(input);
}
private void savePositionsToConfig() {
for (HudElement element : elements)
ConfigManager.setHudPosition(element.getId(), element.getX(), element.getY());
ConfigManager.save();
}
private void saveVisibilitiesToConfig() {
for (HudElement element : elements)
ConfigManager.setHudVisibility(element.getId(), element.isVisible());
ConfigManager.save();
}
private void saveAndClose() {
savePositionsToConfig();
selected = null;
mc.setScreen(null);
}
@Override
protected void applyBlur(DrawContext ctx) {
if (ClientSettingsFrame.guiSettings.blur.isEnabled()) super.applyBlur(ctx);
}
public boolean isSelected(HudElement element) {
return selected == element;
}
// para los tooltips
private List<Text> getTooltipFor(HudElement element) {
List<Text> list = new ArrayList<>();
switch (element.getId()) {
case "coords" -> {
list.add(Text.literal("coordenadas"));
list.add(Text.literal("te muestra tu posición en el mundo en coordenadas XYZ"));
}
case "fps" -> {
list.add(Text.literal("FPS"));
list.add(Text.literal("te muestra la tasa de fotogramas por segundo del juego"));
}
case "tps" -> {
list.add(Text.literal("tps"));
list.add(Text.literal("te muestra la tasa de ticks por segundo del servidor (0-20)"));
}
case "customText" -> {
list.add(Text.literal("texto custom"));
list.add(Text.literal("te permite renderizar texto al gusto"));
}
case "time" -> {
list.add(Text.literal("hora"));
list.add(Text.literal("te muestra la hora y los minutos de la zona horaria escogida"));
}
default -> {
list.add(Text.literal(element.getId()));
list.add(Text.literal("."));
}
}
return list;
}
}
@@ -1,202 +0,0 @@
package me.retucio.camtweaks.ui;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.config.ConfigManager;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.PacketEvent;
import me.retucio.camtweaks.event.events.camtweaks.UpdateSettingEvent;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.Freecam;
import me.retucio.camtweaks.module.modules.HUD;
import me.retucio.camtweaks.ui.widgets.HudElement;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.TitleScreen;
import net.minecraft.client.render.RenderTickCounter;
import net.minecraft.util.math.Vec3d;
import java.awt.*;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HudRenderer {
private static final MinecraftClient mc = MinecraftClient.getInstance();
private static float estimatedTPS = 20f;
private long lastPacketTime = 0;
private static final Map<String, int[]> positions = ConfigManager.getConfig().hudPositions;
private static final Map<String, Boolean> visibilities = ConfigManager.getConfig().hudVisibilities;
private static final List<HudElement> elements = new ArrayList<>();
private static boolean initialized = false;
private static HudElement customTextElement = null;
public static void initElements() {
if (initialized) return;
initialized = true;
HUD hud = ModuleManager.INSTANCE.getModuleByClass(HUD.class);
// coordenadas
addElement("coords", 2, mc.getWindow().getScaledHeight() - mc.textRenderer.fontHeight, (ctx, mx, my, delta) -> {
drawSnappedText(ctx, getElementText("coords", delta, hud), mx, my, getColor(hud).getRGB(), hud.shadow.isEnabled());
});
// FPS
addElement("fps", 2, 2, (ctx, mx, my, delta) -> {
drawSnappedText(ctx, getElementText("fps", 0, hud), mx, my, getColor(hud).getRGB(), hud.shadow.isEnabled());
});
// TPS
addElement("tps", 2, mc.textRenderer.fontHeight + 4, (ctx, mx, my, delta) -> {
drawSnappedText(ctx, getElementText("tps", delta, hud), mx, my, getColor(hud).getRGB(), hud.shadow.isEnabled());
});
// texto custom
addElement("customText", mc.getWindow().getScaledWidth() / 2 - mc.textRenderer.getWidth(getElementText("customText", 0, ModuleManager.INSTANCE.getModuleByClass(HUD.class))) / 2, 2, (ctx, mx, my, delta) -> {
drawSnappedText(ctx, getElementText("customText", delta, hud), mx, my, getColor(hud).getRGB(), hud.shadow.isEnabled());
});
customTextElement = elements.stream()
.filter(e -> e.getId().equals("customText"))
.findFirst()
.orElse(null);
// hora
addElement("time", mc.getWindow().getScaledWidth() - mc.textRenderer.getWidth("04:20"), mc.getWindow().getScaledHeight() - mc.textRenderer.fontHeight - 2, (ctx, mx, my, delta) -> {
drawSnappedText(ctx, getElementText("time", delta, hud), mx, my, getColor(hud).getRGB(), hud.shadow.isEnabled());
});
HudEditorScreen.INSTANCE.setElements(getElements());
}
private static void addElement(String id, int defX, int defY, HudElement.Renderer renderer) {
int[] saved = positions.get(id);
Boolean visible = visibilities.get(id);
int x = saved == null ? defX : saved[0];
int y = saved == null ? defY : saved[1];
boolean v = visible == null || visible;
if (visibilities.isEmpty()) v = true;
elements.add(new HudElement(id, defX, defY, x, y, v) {
@Override public void render(DrawContext ctx, int mx, int my, float delta) {
renderer.render(ctx, x, y, delta);
}
});
}
public static Color getColor(HUD hud) {
if (hud.rainbow.isEnabled()) {
float speed = 10001 - hud.rainbowSpeed.getFloatValue();
float hue = (System.currentTimeMillis() % (int) speed) / speed;
Color rgb = Color.getHSBColor(hue, 1, 1);
return new Color(rgb.getRed(), rgb.getGreen(), rgb.getBlue(), hud.alpha.getIntValue());
}
return new Color(hud.red.getIntValue(), hud.green.getIntValue(), hud.blue.getIntValue(), hud.alpha.getIntValue());
}
public static void drawSnappedText(DrawContext ctx, String text, int x, int y, int color, boolean shadow) {
int textWidth = mc.textRenderer.getWidth(text);
int screenWidth = mc.getWindow().getScaledWidth();
int screenHeight = mc.getWindow().getScaledHeight();
boolean snapRight = x > screenWidth / 2;
int drawX = snapRight ? x + (textWidth + 2) - textWidth : x;
// clampear y
y = Math.max(0, Math.min(y, screenHeight - mc.textRenderer.fontHeight));
// clampear x
drawX = Math.max(0, Math.min(drawX, screenWidth - textWidth));
ctx.drawText(mc.textRenderer, text, drawX, y, color, shadow);
}
public static void render(DrawContext ctx, RenderTickCounter tc) {
if (ModuleManager.INSTANCE == null
|| mc.player == null
|| mc.getCameraEntity() == null
|| mc.currentScreen instanceof TitleScreen
|| mc.options.hudHidden)
return;
HUD hud = ModuleManager.INSTANCE.getModuleByClass(HUD.class);
if (!hud.isEnabled()) return;
if (mc.getDebugHud().shouldShowDebugHud() && !hud.showOnF3.isEnabled()) return;
initElements();
if (mc.currentScreen instanceof HudEditorScreen) return;
float deltaTime = tc.getDynamicDeltaTicks();
for (HudElement element : elements)
if (element.isVisible()) element.render(ctx, 0, 0, deltaTime);
}
public static List<HudElement> getElements() {
return elements;
}
// texto a dibujar por elemento
public static String getElementText(String id, float delta, HUD hud) {
switch (id) {
case "coords" -> {
Freecam freecam = ModuleManager.INSTANCE.getModuleByClass(Freecam.class);
Vec3d pos = freecam.isEnabled()
? new Vec3d(freecam.getX(delta), freecam.getY(delta), freecam.getZ(delta))
: mc.player.getEntityPos();
return (int) pos.x + " " + (int) pos.y + " " + (int) pos.z;
}
case "fps" -> {
return "FPS: " + mc.getCurrentFps();
}
case "tps" -> {
return "TPS: " + estimatedTPS;
}
case "customText" -> {
return ModuleManager.INSTANCE.getModuleByClass(HUD.class).customText.getValue();
}
case "time" -> {
ZoneOffset offset = ZoneOffset.ofHours(hud.timezone.getIntValue());
LocalTime now = LocalTime.now(offset);
boolean is24 = hud.timeFormat.is(HUD.TimeFormat.TWENTY_FOUR_HOUR);
DateTimeFormatter format = DateTimeFormatter.ofPattern(is24 ? "HH:mm" : "hh:mm a");
return now.format(format);
}
default -> { return id; }
}
}
@SubscribeEvent
public void onReceivePacket(PacketEvent.Receive event) {
long now = System.currentTimeMillis();
if (lastPacketTime > 0) {
float tps = 1000f / (now - lastPacketTime);
estimatedTPS = Math.min(20f, tps);
}
lastPacketTime = now;
}
/** para cuando se cambie el valor del texto custom */
@SubscribeEvent
public void onUpdateSetting(UpdateSettingEvent event) {
HUD hud = ModuleManager.INSTANCE.getModuleByClass(HUD.class);
if (event.getSetting() == hud.customText) {
if (customTextElement != null) {
int newX = mc.getWindow().getScaledWidth() / 2 - mc.textRenderer.getWidth(hud.customText.getValue()) / 2;
customTextElement.setX(newX);
}
}
}
}
@@ -1,74 +0,0 @@
package me.retucio.camtweaks.ui.buttons;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.frames.ModuleFrame;
import me.retucio.camtweaks.util.Colors;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
// clase para el botón para cada módulo
public class ModuleButton {
public Module module;
public ModuleFrame parent;
public int offset;
public final int height = 18;
public ModuleButton(Module module, ModuleFrame parent, int offset) {
this.module = module;
this.parent = parent;
this.offset = offset;
}
public void render(DrawContext ctx, double mouseX, double mouseY, float delta) {
ctx.fill( // dibujar el contorno del botón
parent.x + 2, parent.renderY + offset + 3,
parent.x + parent.w - 2 , parent.renderY + height + offset,
determineColor(mouseX, mouseY));
ctx.drawText( // dibujar el nombre del módulo
parent.mc.textRenderer, module.getName(),
parent.x + 5, parent.renderY + offset + (height / 2) - (parent.mc.textRenderer.fontHeight / 2) + 2,
-1, true);
// dibujar "tooltips" (cajas de texto) al pasar el puntero encima del botón, para mostrar su descripción
if (isHovered((int) mouseX, (int) mouseY))
ctx.drawTooltip(Text.of(module.getDescription()), (int) mouseX, (int) mouseY + 20);
}
public void mouseClicked(double mouseX, double mouseY, int button) {
if (isHovered((int) mouseX, (int) mouseY) && ClickGUI.INSTANCE.trySelect(this)) {
if (button == 0) { // clic izquierdo para activar / desactivar el módulo
module.toggle();
} else if (button == 1) { // clic derecho para el marco de ajustes (también lo cierra si está abierto)
if (ClickGUI.INSTANCE.isSettingsFrameOpen(module))
ClickGUI.INSTANCE.closeSettingsFrame(module);
else
ClickGUI.INSTANCE.openSettingsFrame(module,
parent.x + parent.w + 120, parent.renderY + offset);
}
}
}
public void mouseReleased(double mouseX, double mouseY, int button) {
ClickGUI.INSTANCE.unselect(this);
}
// verifica si el puntero del ratón se encuentra sobre el botón del módulo
public boolean isHovered(int mouseX, int mouseY) {
return ClickGUI.INSTANCE.canSelect(this)
&& mouseX > parent.x
&& mouseX < parent.x + parent.w
&& mouseY > parent.renderY + offset
&& mouseY < parent.renderY + height + offset;
}
public int determineColor(double mouseX, double mouseY) {
// determina el color del botón, dependiendo de si está el puntero encima y si está activado
if (module.isEnabled())
return isHovered((int) mouseX, (int) mouseY) ? Colors.mainColor.brighter().getRGB() : Colors.mainColor.getRGB();
return isHovered((int) mouseX, (int) mouseY) ? Colors.buttonColor.brighter().getRGB() : Colors.buttonColor.getRGB();
}
}
@@ -1,80 +0,0 @@
package me.retucio.camtweaks.ui.buttons;
import me.retucio.camtweaks.module.settings.AbstractSetting;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.frames.SettingsFrame;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
// clase base para los botones de los ajustes
public abstract class SettingButton {
protected final AbstractSetting setting;
protected final SettingsFrame parent;
protected int offset;
protected int x, y, w, h;
public SettingButton(AbstractSetting setting, SettingsFrame parent, int offset) {
this.setting = setting;
this.parent = parent;
this.offset = offset;
}
public abstract void render(DrawContext ctx, double mouseX, double mouseY, float delta);
public abstract void mouseClicked(double mouseX, double mouseY, int button);
public abstract void mouseReleased(double mouseX, double mouseY, int button);
// dibujar "tooltips" (cajitas de texto bajo el puntero del ratón) con la descripción para asistir al usuario en el caso de que tenga down
public void drawTooltip(DrawContext ctx, double mouseX, double mouseY) {
if (isHovered((int) mouseX, (int) mouseY))
ctx.drawTooltip(Text.of(setting.getDescription()), (int) mouseX, (int) mouseY + 20);
}
protected boolean isHovered(double mouseX, double mouseY) {
return isHovered((int) mouseX, (int) mouseY);
}
protected boolean isHovered(int mouseX, int mouseY) {
if (!ClickGUI.INSTANCE.canSelect(this)) return false;
return mouseX > x && mouseX < x + w &&
mouseY > y && mouseY < y + h;
}
public AbstractSetting getSetting() {
return setting;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
}
@@ -1,57 +0,0 @@
package me.retucio.camtweaks.ui.buttons;
import me.retucio.camtweaks.module.settings.BooleanSetting;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.frames.SettingsFrame;
import me.retucio.camtweaks.util.Colors;
import me.retucio.camtweaks.util.KeyUtil;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
import org.lwjgl.glfw.GLFW;
import java.awt.*;
import static me.retucio.camtweaks.CameraTweaks.mc;
// botón para los ajustes booleanos (funciona como un interruptor)
public class ToggleButton extends SettingButton {
private final BooleanSetting setting;
public ToggleButton(BooleanSetting setting, SettingsFrame parent, int offset) {
super(setting, parent, offset);
this.setting = setting;
}
@Override
public void render(DrawContext ctx, double mouseX, double mouseY, float delta) {
Color color = setting.isEnabled()
? Colors.enabledToggleButtonColor
: Colors.disabledToggleButtonColor;
if (isHovered((int) mouseX, (int) mouseY))
color = color.brighter();
ctx.fill(x, y, x + w, y + h, color.getRGB());
ctx.drawText(parent.mc.textRenderer, setting.getName(), x + 5, y + 3, -1, true);
}
@Override
public void mouseClicked(double mouseX, double mouseY, int button) {
if (isHovered((int) mouseX, (int) mouseY) && ClickGUI.INSTANCE.trySelect(this)) {
if (button == 0) setting.toggle(); // clic izquierdo para alternar
else if (button == 1 && mc.isShiftPressed()) // shift izquierdo + clic derecho para restablecer al valor por defecto
setting.reset();
}
}
@Override
public void mouseReleased(double mouseX, double mouseY, int button) {
ClickGUI.INSTANCE.unselect(this);
}
public BooleanSetting getSetting() {
return setting;
}
}
@@ -1,85 +0,0 @@
package me.retucio.camtweaks.ui.frames;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.camtweaks.GUISettingsFrameEvent;
import me.retucio.camtweaks.module.modules.GUI;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.buttons.SettingButton;
import me.retucio.camtweaks.util.Colors;
import net.minecraft.client.gui.DrawContext;
import java.util.List;
public class ClientSettingsFrame extends SettingsFrame {
public static final GUI guiSettings = new GUI();
public boolean extended = false;
private final String title = "ajustes del mod";
public ClientSettingsFrame(int x, int y, int w, int h) {
super(guiSettings, x, y, w, h);
}
@Override
public void render(DrawContext ctx, int mouseX, int mouseY, float delta) {
updateWidth();
ctx.fill(x, renderY, x + w, renderY + h, Colors.mainColor.getRGB());
ctx.drawText(mc.textRenderer, title,
x + 8,
renderY + (h / 2) - (mc.textRenderer.fontHeight / 2),
-1, true);
ctx.drawText(mc.textRenderer, extended ? "-" : "+",
x + w - mc.textRenderer.getWidth("+") - 8,
renderY + (h / 2) - (mc.textRenderer.fontHeight / 2),
-1, true);
List<SettingButton> visibleButtons = settingButtons.stream()
.filter(sb -> sb.getSetting().isVisible() && sb.getSetting().isSearchMatch())
.toList();
if (extended) {
int currentY = renderY + h + 3;
totalHeight = visibleButtons.size() * h;
ctx.fill(x, currentY - 2, x + w, currentY + totalHeight, Colors.frameBGColor.getRGB());
for (SettingButton sb : visibleButtons) {
sb.setX(x + 4);
sb.setY(currentY);
sb.setW(w - 8);
sb.setH(h - h / 4);
sb.render(ctx, mouseX, mouseY, delta);
sb.drawTooltip(ctx, mouseX, mouseY);
currentY += h;
}
} else totalHeight = 0;
}
@Override
public void mouseClicked(double mouseX, double mouseY, int button) {
if (isHovered(mouseX, mouseY) && ClickGUI.INSTANCE.trySelect(this)) {
if (button == 0) {
dragging = true;
dragX = (int) (mouseX - x);
dragY = (int) (mouseY - y);
} else if (button == 1) {
extended = !extended;
CameraTweaks.EVENT_BUS.post(new GUISettingsFrameEvent.Extend());
}
}
if (!extended) return; // solo dejar clicar en los módulos si el marco está extendido
for (SettingButton settingButton : settingButtons)
settingButton.mouseClicked(mouseX, mouseY, button);
}
@Override
public void mouseRelease(double mouseX, double mouseY, int button) {
ClickGUI.INSTANCE.unselect(this);
if (button == 0 && dragging)
CameraTweaks.EVENT_BUS.post(new GUISettingsFrameEvent.Move());
super.mouseRelease(mouseX, mouseY, button);
}
}
@@ -1,246 +0,0 @@
package me.retucio.camtweaks.ui.frames;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.event.events.camtweaks.SettingsFrameEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.*;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.buttons.*;
import me.retucio.camtweaks.ui.buttons.SliderButton;
import me.retucio.camtweaks.ui.buttons.TextButton;
import me.retucio.camtweaks.ui.buttons.ToggleButton;
import me.retucio.camtweaks.util.Colors;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
// marco para los botones de los ajustes de cada módulo
public class SettingsFrame {
private final String title;
public final Module module;
final List<SettingButton> settingButtons = new ArrayList<>();
public List<SettingButton> visibleButtons = new ArrayList<>();
public int x, y, w, h;
public int renderY;
int dragX, dragY;
boolean dragging;
public int totalHeight = 0;
public final MinecraftClient mc = MinecraftClient.getInstance();
@SuppressWarnings({"rawtypes", "unchecked"})
public SettingsFrame(Module module, int x, int y, int w, int h) {
this.module = module;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
// añadir el respectivo tipo de botón de cada ajuste a la lista de botones
int offset = h;
for (AbstractSetting setting : module.getSettings()) {
if (!setting.isVisible()) continue;
switch (setting) {
case BooleanSetting b -> {
addButton(new ToggleButton(b, this, offset));
offset += 18;
} case NumberSetting n -> {
addButton(new SliderButton(n, this, offset));
offset += 18;
} case EnumSetting e -> {
addButton(new CycleButton<>(e, this, offset));
offset += 18;
} case KeySetting k -> {
addButton(new BindButton(k, this, offset));
offset += 18;
} case StringSetting s -> {
addButton(new TextButton(s, this, offset));
offset += 18;
} case ListSetting l -> {
addButton(new ListButton<>(l, this, offset));
offset += 18;
} default -> {}
}
}
title = "ajustes de " + module.getName();
visibleButtons = settingButtons.stream()
.filter(sb -> sb.getSetting().isVisible())
.toList();
}
public void addButton(SettingButton button) {
settingButtons.add(button);
updateWidth(); // actualizar anchura del frame tras cada iteración
}
public void render(DrawContext ctx, int mouseX, int mouseY, float delta) {
updateWidth();
// cabezal
int centerX = x + w / 2;
int centerY = renderY + h / 2;
int titleX = x + 8;
int titleY = centerY - mc.textRenderer.fontHeight / 2;
int headerColor = module.isEnabled()
? Colors.enabledToggleButtonColor.getRGB()
: Colors.disabledToggleButtonColor.getRGB();
int closeButtonColor = isCloseButtonHovered(mouseX, mouseY)
? Color.RED.getRGB()
: -1;
if (!module.shouldSaveSettings()) headerColor = (int) module.getSettings().stream().filter(s -> ((BooleanSetting) s).isEnabled()).count() > 0
? Colors.enabledToggleButtonColor.getRGB()
: Colors.disabledToggleButtonColor.getRGB();
ctx.fill(x, renderY, x + w, renderY + h, headerColor);
ctx.drawText(mc.textRenderer, title, titleX, titleY, -1, true);
ctx.drawText(mc.textRenderer, "×", x + w - mc.textRenderer.getWidth("×") - 8, titleY, closeButtonColor, true);
// descripción
visibleButtons = settingButtons.stream()
.filter(sb -> sb.getSetting().isVisible() && sb.getSetting().isSearchMatch())
.toList();
List<String> descLines = wrapDescription(module.getDescription(), w - 8);
int lineSpacing = 2;
int descHeight = descLines.size() * mc.textRenderer.fontHeight + (descLines.size() - 1) * lineSpacing;
int descBoxTop = renderY + h + 5;
int descBoxBottom = descBoxTop + descHeight + 8;
totalHeight = descHeight + 8 + h * visibleButtons.size() + 4;
ctx.fill(x, descBoxTop - 4, x + w, descBoxTop + totalHeight, Colors.frameBGColor.getRGB());
ctx.fill(x + 4, descBoxTop, x + w - 4, descBoxBottom, Colors.buttonColor.getRGB());
int firstLineY = descBoxTop + ((descBoxBottom - descBoxTop) - descHeight) / 2;
for (int i = 0; i < descLines.size(); i++) {
String line = descLines.get(i);
int lineX = centerX - mc.textRenderer.getWidth(line) / 2;
int lineY = firstLineY + i * (mc.textRenderer.fontHeight + lineSpacing);
ctx.drawText(mc.textRenderer, line, lineX, lineY, -1, true);
}
int startButtonY = firstLineY - descBoxTop + descBoxBottom;
for (SettingButton sb : visibleButtons) {
sb.setX(x + 4);
sb.setY(startButtonY);
sb.setW(w - 8);
sb.setH(h - h / 4);
sb.render(ctx, mouseX, mouseY, delta);
startButtonY += h;
}
}
public void drawTooltips(DrawContext ctx, double mouseX, double mouseY) {
for (SettingButton sb : visibleButtons)
sb.drawTooltip(ctx, mouseX, mouseY);
}
public void mouseClicked(double mouseX, double mouseY, int button) {
if (isHovered(mouseX, mouseY) && ClickGUI.INSTANCE.trySelect(this)) {
if (isCloseButtonHovered(mouseX, mouseY)) {
ClickGUI.INSTANCE.closeSettingsFrame(this.module);
return;
} if (button == 0) {
dragging = true;
dragX = (int) (mouseX - x);
dragY = (int) (mouseY - y);
} else if (button == 1) {
ClickGUI.INSTANCE.closeSettingsFrame(module);
}
}
for (SettingButton sb : settingButtons)
if (sb.getSetting().isVisible())
sb.mouseClicked(mouseX, mouseY, button);
}
public void mouseRelease(double mouseX, double mouseY, int button) {
ClickGUI.INSTANCE.unselect(this);
if (button == 0) {
dragging = false;
CameraTweaks.EVENT_BUS.post(new SettingsFrameEvent.Move(this));
}
for (SettingButton sb : settingButtons)
if (sb.getSetting().isVisible()) sb.mouseReleased(mouseX, mouseY, button);
}
public void updatePosition(double mouseX, double mouseY) {
if (dragging) {
x = (int) (mouseX - dragX);
y = (int) (mouseY - dragY);
}
}
public boolean isHovered(double mouseX, double mouseY) {
return mouseX > x && mouseX < x + w &&
mouseY > renderY && mouseY < renderY + h;
}
public boolean isCloseButtonHovered(double mouseX, double mouseY) {
return mouseX > x + w - mc.textRenderer.getWidth("×") - 12 && mouseX < x + w - 4
&& mouseY > renderY + 4 && mouseY < renderY + h - 4;
}
@SuppressWarnings("rawtypes")
void updateWidth() {
// asegurarse de que todos los botones caben en el marco, haciendo que la anchura se ajuste al texto más largo
if (mc.textRenderer == null) return;
int maxWidth = mc.textRenderer.getWidth(title);
for (SettingButton button : settingButtons) {
String text = button.getSetting().getName();
switch (button) {
case SliderButton sliderButton -> text += ": " + sliderButton.df.format((sliderButton.getSetting()).getValue());
case CycleButton cycleButton -> text += ": " + cycleButton.getSetting().getValue();
case BindButton bindButton -> text += ": " + bindButton.getSetting().getKeyName();
case TextButton textButton -> text += ": " + textButton.getSetting().getValue();
default -> {}
}
int textWidth = mc.textRenderer.getWidth(text);
maxWidth = Math.max(maxWidth, textWidth);
}
this.w = maxWidth + 30;
}
private List<String> wrapDescription(String text, int maxWidth) {
List<String> lines = new ArrayList<>();
if (mc.textRenderer == null) return lines;
String[] words = text.split(" ");
StringBuilder line = new StringBuilder();
for (String word : words) {
String testLine = line.isEmpty() ? word : line + " " + word;
if (mc.textRenderer.getWidth(testLine) > maxWidth - 8) { // padding of 4 each side
if (!line.isEmpty()) lines.add(line.toString());
line = new StringBuilder(word);
} else {
line = new StringBuilder(testLine);
}
}
if (!line.isEmpty()) lines.add(line.toString());
return lines;
}
public List<SettingButton> getButtons() {
return settingButtons;
}
public void updateRenderY(int scrollOffset) {
renderY = y - scrollOffset;
}
}
@@ -1,144 +0,0 @@
package me.retucio.camtweaks.ui.widgets;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.HUD;
import me.retucio.camtweaks.ui.HudEditorScreen;
import me.retucio.camtweaks.ui.HudRenderer;
import me.retucio.camtweaks.util.Colors;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.text.Text;
import java.awt.*;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class HudElement {
protected final MinecraftClient mc = MinecraftClient.getInstance();
private final String id;
protected boolean visible;
protected int x, y;
protected int defaultX, defaultY;
protected int width = 85, height = 14; // tamaño por defecto
public HudElement(String id, int defX, int defY, int x, int y, boolean visible) {
this.id = id;
this.visible = visible;
this.x = x;
this.y = y;
this.defaultX = defX;
this.defaultY = defY;
}
// fallback
public void render(DrawContext ctx, int mouseX, int mouseY, float tickDelta) {
ctx.drawText(mc.textRenderer, Text.literal(getId()), x, y, -1, false);
}
/** renderizar previsualización del elemento para el editor */
public void renderPreview(DrawContext ctx) {
final HUD hud = ModuleManager.INSTANCE.getModuleByClass(HUD.class);
final String previewText = buildPreviewText(hud);
width = mc.textRenderer.getWidth(previewText);
height = mc.textRenderer.fontHeight;
drawBackground(ctx);
int color = -1;
boolean shadow = false;
if (hud != null) {
color = HudRenderer.getColor(hud).getRGB();
shadow = hud.shadow.isEnabled();
}
HudRenderer.drawSnappedText(ctx, previewText, x, y, color, shadow);
}
/** construir texto para la previsualización */
private String buildPreviewText(HUD hud) {
float delta = mc.getRenderTickCounter().getDynamicDeltaTicks();
if ("coords".equals(id)) {
if (mc.player == null) return "X Y Z";
return HudRenderer.getElementText(id, delta, hud);
}
if ("fps".equals(id)) {
return HudRenderer.getElementText(id, delta, hud);
}
if ("tps".equals(id)) {
return HudRenderer.getElementText(id, delta, hud);
}
if ("customText".equals(id)) {
if (hud != null && hud.customText != null && !hud.customText.getValue().isEmpty())
return HudRenderer.getElementText(id, delta, hud);
return "texto custom";
}
if ("time".equals(id)) {
if (hud != null && hud.timeFormat != null)
return HudRenderer.getElementText(id, delta, hud);
return "4:20 PM";
}
return id; // fallback: id del elemento
}
/** fondo y contorno */
private void drawBackground(DrawContext ctx) {
int bg = visible ? Colors.visibleHudElementColor.getRGB() : Colors.disabledHudElementColor.getRGB();
int outline = HudEditorScreen.INSTANCE.isSelected(this) ? Colors.selectedHudElementOutlineColor.getRGB() : Colors.unselectedHudElementOutlineColor.getRGB();
// fondo
ctx.fill(x - 1, y - 1, x + width + 1, y + height + 1, bg);
// contorno
ctx.fill(x - 1, y - 1, x + width + 1, y, outline);
ctx.fill(x - 1, y + height, x + width + 1, y + height + 1, outline);
ctx.fill(x - 1, y, x, y + height, outline);
ctx.fill(x + width, y, x + width + 1, y + height, outline);
}
public boolean contains(int mouseX, int mouseY) {
return mouseX >= x && mouseX <= x + width
&& mouseY >= y && mouseY <= y + height;
}
// getters y setters
public String getId() { return id; }
public int getX() { return x; }
public int getY() { return y; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public int getWidth() { return width; }
public int getHeight() { return height; }
public boolean isVisible() { return visible; }
public void setVisible(boolean visible) { this.visible = visible; }
public void setPosition(int newX, int newY) {
this.x = newX;
this.y = newY;
}
public void resetPosition() {
this.x = defaultX;
this.y = defaultY;
}
public interface Renderer {
void render(DrawContext ctx, int x, int y, float delta);
}
}
@@ -1,84 +0,0 @@
package me.retucio.camtweaks.util;
import me.retucio.camtweaks.CameraTweaks;
import me.retucio.camtweaks.mixin.accessor.KeyBindingAccessor;
import net.minecraft.client.option.KeyBinding;
import org.lwjgl.glfw.GLFW;
// cosas útiles relacionadas a las teclas
public class KeyUtil {
public static boolean isKeyDown(int key) {
return GLFW.glfwGetKey(
CameraTweaks.mc.getWindow().getHandle(),
key) != GLFW.GLFW_RELEASE;
}
public static boolean isKeyDown(KeyBinding key) {
return GLFW.glfwGetKey(
CameraTweaks.mc.getWindow().getHandle(),
((KeyBindingAccessor) key).getBoundKey().getCode()
) != GLFW.GLFW_RELEASE;
}
public static String getKeyName(int key) {
if (key == GLFW.GLFW_KEY_UNKNOWN) return "ninguna";
String name = GLFW.glfwGetKeyName(key, 0);
if (name != null) return name.toUpperCase();
// para teclas especiales
return switch (key) {
case GLFW.GLFW_KEY_SPACE -> "espacio";
case GLFW.GLFW_KEY_LEFT_SHIFT -> "shift izquierdo";
case GLFW.GLFW_KEY_RIGHT_SHIFT -> "shift derecho";
case GLFW.GLFW_KEY_LEFT_CONTROL -> "ctrl izquierdo";
case GLFW.GLFW_KEY_RIGHT_CONTROL -> "ctrl derecho";
case GLFW.GLFW_KEY_LEFT_ALT -> "alt izquierdo";
case GLFW.GLFW_KEY_RIGHT_ALT -> "alt gr";
case GLFW.GLFW_KEY_TAB -> "tab";
case GLFW.GLFW_KEY_ENTER -> "enter";
case GLFW.GLFW_KEY_BACKSPACE -> "borrar";
case GLFW.GLFW_KEY_DELETE -> "suprimir";
case GLFW.GLFW_KEY_UP -> "arriba";
case GLFW.GLFW_KEY_DOWN -> "abajo";
case GLFW.GLFW_KEY_LEFT -> "izquierda";
case GLFW.GLFW_KEY_RIGHT -> "derecha";
case GLFW.GLFW_KEY_PAGE_UP -> "pág. arriba";
case GLFW.GLFW_KEY_PAGE_DOWN -> "pág. abajo";
default -> {
if (key >= GLFW.GLFW_KEY_F1 && key <= GLFW.GLFW_KEY_F25)
yield "F" + (key - GLFW.GLFW_KEY_F1 + 1); // F1–F25
yield "tecla " + key; // fallback
}
};
}
// quizás debería de añadir layouts...
public static String shiftKey(String c) {
return switch (c) {
case "`" -> "~";
case "1" -> "!";
case "2" -> "@";
case "3" -> "#";
case "4" -> "$";
case "5" -> "%";
case "6" -> "^";
case "7" -> "&";
case "8" -> "*";
case "9" -> "(";
case "0" -> ")";
case "-" -> "_";
case "=" -> "+";
case "[" -> "{";
case "]" -> "}";
case "\\" -> "|";
case ";" -> ":";
case "'" -> "\"";
case "," -> "<";
case "." -> ">";
case "/" -> "?";
default -> c.toUpperCase();
};
}
}
@@ -1,66 +0,0 @@
package me.retucio.camtweaks.util;
import net.minecraft.block.Block;
import net.minecraft.client.particle.Particle;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.entity.EntityType;
import net.minecraft.item.Item;
import net.minecraft.particle.ParticleType;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.registry.Registries;
import net.minecraft.text.Text;
import java.util.*;
import static me.retucio.camtweaks.CameraTweaks.mc;
public class Lists {
public static final List<EntityType<?>> entityList = Registries.ENTITY_TYPE.stream().toList();
public static Map<EntityType<?>, String> entityNames;
public static final List<ParticleType<?>> particleList = Registries.PARTICLE_TYPE.stream().toList();
public static Map<ParticleType<?>, String> particleNames;
public static final List<Item> itemList = Registries.ITEM.stream().toList();
public static Map<Item, String> itemNames;
public static final List<Block> blockList = Registries.BLOCK.stream().toList();
public static void init() {
// no consigo traducir el texto. a tomar por culo, se queda en inglés, si no entiendes pues a estudiar
entityNames = getMapOfLists(entityList,
entityList.stream().map(entity -> I18n.translate(entity.getTranslationKey())).toList());
// no hay traducciones para nombres de partículas, y paso de hacerlas yo
particleNames = getMapOfLists(particleList,
particleList.stream().map(particle -> Registries.PARTICLE_TYPE.getId(particle).toShortTranslationKey()).toList());
itemNames = getMapOfLists(itemList,
itemList.stream().map(item -> I18n.translate(item.getTranslationKey())).toList());
}
public static <T> Map<T, Boolean> allTrue(List<T> options) {
Map<T, Boolean> map = new HashMap<>();
for (T option : options) map.put(option, true);
return map;
}
public static <T> Map<T, Boolean> allFalse(List<T> options) {
Map<T, Boolean> map = new HashMap<>();
for (T option : options) map.put(option, false);
return map;
}
public static <T> Map<T, String> getMapOfLists(List<T> options, List<String> names) {
Map<T, String> result = new HashMap<>();
// no exceder los límites de ninguna de las dos listas
int size = Math.min(options.size(), names.size());
for (int i = 0; i < size; i++)
result.put(options.get(i), names.get(i));
return result;
}
}
@@ -1,39 +0,0 @@
package me.retucio.camtweaks.util;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.TickEvent;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import org.joml.Vector3d;
import static me.retucio.camtweaks.CameraTweaks.mc;
public class MiscUtil {
public static Screen screen;
private MiscUtil() {}
@SubscribeEvent
public static void onTick(TickEvent.Post event) {
if (screen != null && mc.currentScreen == null) {
mc.setScreen(screen);
screen = null;
}
}
public static void copyVector(Vector3d destination, Vec3d source) {
destination.x = source.x;
destination.y = source.y;
destination.z = source.z;
}
public static Vector3d getEntityVector(Vector3d vector, Entity entity, double tickDelta) {
vector.x = MathHelper.lerp(tickDelta, entity.lastRenderX, entity.getX());
vector.y = MathHelper.lerp(tickDelta, entity.lastRenderY, entity.getY());
vector.z = MathHelper.lerp(tickDelta, entity.lastRenderZ, entity.getZ());
return vector;
}
}
@@ -1,13 +0,0 @@
package me.retucio.camtweaks.util.interfaces;
import net.minecraft.client.gui.hud.ChatHudLine;
import net.minecraft.text.Text;
import java.util.List;
public interface IChatHud {
void smegma$add(Text message, int id);
List<ChatHudLine.Visible> smegma$getVisibleMessages();
}
@@ -1,14 +0,0 @@
package me.retucio.camtweaks.util.interfaces;
import com.mojang.authlib.GameProfile;
public interface IChatHudLine {
String smegma$getText();
int smegma$getId();
void smegma$setId(int id);
GameProfile smegma$getSender();
void smegma$setSender(GameProfile profile);
}
@@ -1,7 +0,0 @@
package me.retucio.camtweaks.util.interfaces;
public interface IChatHudLineVisible extends IChatHudLine {
boolean smegma$isStartOfEntry();
void smegma$setStartOfEntry(boolean start);
}
@@ -1,8 +0,0 @@
package me.retucio.camtweaks.util.interfaces;
import com.mojang.authlib.GameProfile;
public interface IMessageHandler {
GameProfile smegma$getSender();
}
@@ -1,14 +0,0 @@
package me.retucio.camtweaks.util.interfaces;
import net.minecraft.util.math.Vec3i;
import org.joml.Vector3d;
public interface IVec3d {
void smegma$set(double x, double y, double z);
default void smegma$set(Vec3i vec) { smegma$set(vec.getX(), vec.getY(), vec.getZ()); }
default void semgma$set(Vector3d vec) { smegma$set(vec.x, vec.y, vec.z); }
void smegma$setXZ(double x, double z);
void smegma$setY(double y);
}
@@ -1,43 +1,50 @@
package me.retucio.camtweaks;
package me.retucio.sputnik;
import me.retucio.camtweaks.command.CommandManager;
import me.retucio.camtweaks.command.commands.BindCommand;
import me.retucio.sputnik.cape.CapeManager;
import me.retucio.sputnik.command.CommandManager;
import me.retucio.sputnik.command.commands.BindCommand;
import me.retucio.camtweaks.config.ConfigManager;
import me.retucio.sputnik.config.ConfigManager;
import me.retucio.camtweaks.event.EventBus;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.ShutdownEvent;
import me.retucio.sputnik.event.EventBus;
import me.retucio.sputnik.event.SubscribeEvent;
import me.retucio.sputnik.event.events.ShutdownEvent;
import me.retucio.sputnik.event.events.sputnik.LoadCapeManagerEvent;
import me.retucio.sputnik.event.events.sputnik.LoadClickGUIEvent;
import me.retucio.sputnik.event.events.sputnik.LoadCommandManagerEvent;
import me.retucio.sputnik.event.events.sputnik.LoadModuleManagerEvent;
import me.retucio.camtweaks.event.events.camtweaks.LoadClickGUIEvent;
import me.retucio.camtweaks.event.events.camtweaks.LoadCommandManagerEvent;
import me.retucio.camtweaks.event.events.camtweaks.LoadModuleManagerEvent;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.sputnik.module.Module;
import me.retucio.sputnik.module.ModuleManager;
import me.retucio.sputnik.module.modules.client.HUD;
import me.retucio.camtweaks.module.modules.HUD;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.camtweaks.ui.HudEditorScreen;
import me.retucio.camtweaks.ui.HudRenderer;
import me.retucio.camtweaks.ui.buttons.BindButton;
import me.retucio.camtweaks.ui.buttons.SettingButton;
import me.retucio.camtweaks.ui.buttons.TextButton;
import me.retucio.camtweaks.ui.frames.ClientSettingsFrame;
import me.retucio.camtweaks.ui.frames.SettingsFrame;
import me.retucio.camtweaks.util.ChatUtil;
import me.retucio.camtweaks.util.KeyUtil;
import me.retucio.camtweaks.util.Lists;
import me.retucio.camtweaks.util.MiscUtil;
import me.retucio.sputnik.ui.hud.HudRenderer;
import me.retucio.sputnik.ui.screen.ClickGUI;
import me.retucio.sputnik.ui.hud.HudEditorScreen;
import me.retucio.sputnik.ui.widgets.buttons.settings.BindButton;
import me.retucio.sputnik.ui.widgets.buttons.SettingButton;
import me.retucio.sputnik.ui.widgets.buttons.settings.TextButton;
import me.retucio.sputnik.ui.widgets.frames.settings.ClientSettingsFrame;
import me.retucio.sputnik.ui.widgets.frames.SettingsFrame;
import me.retucio.sputnik.ui.widgets.Button;
import me.retucio.sputnik.util.*;
import me.retucio.sputnik.util.KeyUtil;
import me.retucio.sputnik.util.render.DrawUtil;
import me.retucio.sputnik.util.render.RenderUtil;
import me.retucio.sputnik.util.render.Textures;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.SharedConstants;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.TitleScreen;
import net.minecraft.client.gui.screen.ingame.AbstractCommandBlockScreen;
import net.minecraft.client.gui.screen.ingame.AbstractSignEditScreen;
import net.minecraft.client.gui.screen.ingame.AnvilScreen;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -45,33 +52,54 @@ import org.lwjgl.glfw.GLFW;
public class CameraTweaks implements ClientModInitializer {
public class Sputnik implements ClientModInitializer {
// cosas necesarias
public static final String MOD_ID = "camtweaks";
public static final CameraTweaks INSTANCE = new CameraTweaks();
public static final Logger LOGGER = LogManager.getLogger(CameraTweaks.class);
public static final Sputnik INSTANCE = new Sputnik();
public static final EventBus EVENT_BUS = new EventBus();
public static final Logger LOGGER = LogManager.getLogger(Sputnik.class);
public static MinecraftClient mc;
// id y versión
public static final String MOD_ID = "sputnik";
public static final String MOD_VERSION = FabricLoader.getInstance()
.getModContainer(MOD_ID)
.orElseThrow()
.getMetadata()
.getVersion()
.getFriendlyString();
private Screen prevScreen;
public boolean settingsApplied = false;
public static boolean settingsApplied = false;
static {
// puta vida
System.setProperty("java.awt.headless", "false");
}
@Override
public void onInitializeClient() {
// por algún motivo aunque lo añada a los args de la JVM sigue siendo true a menos que haga esto??? puta vida
System.setProperty("java.awt.headless", "false");
mc = MinecraftClient.getInstance();
ConfigManager.load();
EVENT_BUS.register(this);
EVENT_BUS.register(MiscUtil.class);
EVENT_BUS.register(ChatUtil.class);
EVENT_BUS.register(HudRenderer.class);
EVENT_BUS.register(DrawUtil.class);
EVENT_BUS.register(EntityUtil.class);
EVENT_BUS.register(InventoryUtil.class);
EVENT_BUS.register(MiscUtil.class);
EVENT_BUS.register(NetworkUtil.class);
EVENT_BUS.register(RenderUtil.class);
Lists.init();
ModuleManager.INSTANCE = new ModuleManager(EVENT_BUS);
Textures.registerAll();
CapeManager.INSTANCE = new CapeManager();
EVENT_BUS.post(new LoadCapeManagerEvent());
ModuleManager.INSTANCE = new ModuleManager();
EVENT_BUS.post(new LoadModuleManagerEvent());
CommandManager.INSTANCE = new CommandManager();
@@ -81,31 +109,30 @@ public class CameraTweaks implements ClientModInitializer {
HudEditorScreen.INSTANCE = new HudEditorScreen();
EVENT_BUS.post(new LoadClickGUIEvent());
ConfigManager.load();
mc.execute(HudRenderer::init);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
ConfigManager.save();
EVENT_BUS.post(new ShutdownEvent());
}));
}
// se ejecuta cada tick, es decir, 20 veces por segundo
public void onTick() {
ModuleManager.INSTANCE.getEnabledModules().forEach(Module::onTick);
if (!settingsApplied
&& ConfigManager.getConfig() != null
&& mc.player != null && mc.world != null) {
&& !ConfigManager.hasLoaded()) {
ConfigManager.applyConfig();
settingsApplied = true;
}
ModuleManager.INSTANCE.getEnabledModules().forEach(Module::onTick);
mc.getWindow().setTitle(ClientSettingsFrame.guiSettings.windowTitle.getValue());
}
// se ejecuta cada vez que se presiona una tecla
public void onKeyPress(int key, int action) {
public void onKey(int key, int action) {
if (key == GLFW.GLFW_KEY_F3) return; // prevenir activación de módulos al usar combinaciones de F3
ModuleManager.INSTANCE.getEnabledModules().forEach(module -> module.onKey(key, action));
boolean anyFocused = isAnySettingButtonFocused() || ClickGUI.INSTANCE.getSearchBar().isFocused();
ClickGUI.INSTANCE.setAnyFocused(anyFocused);
@@ -126,7 +153,7 @@ public class CameraTweaks implements ClientModInitializer {
// verifica si algún botón de ajustes está escuchando
private boolean isAnySettingButtonFocused() {
for (SettingsFrame sf : ClickGUI.INSTANCE.getSettingsFrames())
for (SettingButton sb : sf.getButtons())
for (Button sb : sf.getButtons())
if ((sb instanceof BindButton b && b.isFocused()) || (sb instanceof TextButton t && t.isFocused()))
return true;
return false;
@@ -149,17 +176,17 @@ public class CameraTweaks implements ClientModInitializer {
// se ocupa de hacer los botones de ajustes que lo necesiten escuchar teclas
private void handleSettingButtonsKey(int key, int action) {
for (SettingsFrame sf : ClickGUI.INSTANCE.getSettingsFrames()) {
for (SettingButton sb : sf.getButtons()) {
if (sb instanceof BindButton b) b.onKey(key, action);
else if (sb instanceof TextButton t) t.onKey(key, action);
for (SettingButton<?> sb : sf.getButtons()) {
if (sb instanceof BindButton bb) bb.onKey(key, action);
if (sb instanceof TextButton tb) tb.onKey(key, action);
}
}
}
// maneja la lógica de apertura de la interfaz
private void handleClickGUIKey(int key, boolean anyFocused) {
if (key != ClientSettingsFrame.guiSettings.getKey() || anyFocused) return;
if (!(mc != null && mc.world != null && mc.player != null)) return;
if (key != ClientSettingsFrame.guiSettings.getKey() || anyFocused || isOnTypingScreen())
return;
// al parecer esto hace que con la tecla de la interfaz puedas ir cambiando de splash text en la pantalla del título
// pero me ha hecho gracia así que así se queda
@@ -174,10 +201,14 @@ public class CameraTweaks implements ClientModInitializer {
// manejar la lógica de apertura del editor de elementos del hud, con la misma lógica que handleClickGUIKey()
private void handleHudEditorKey(int key, boolean anyFocused) {
if (key != ModuleManager.INSTANCE.getModuleByClass(HUD.class).editorKey.getKey() || anyFocused) return;
if (!(mc != null && mc.world != null && mc.player != null)) return;
HUD hud = ModuleManager.INSTANCE.getModuleByClass(HUD.class);
if (key != hud.editorKey.getValue() || anyFocused || isOnTypingScreen()) return;
if (mc.currentScreen != HudEditorScreen.INSTANCE) {
if (!hud.isEnabled()) {
ChatUtil.warn("HUD está desactivado, lumbreras");
return;
}
prevScreen = mc.currentScreen;
mc.setScreen(HudEditorScreen.INSTANCE);
} else {
@@ -195,8 +226,19 @@ public class CameraTweaks implements ClientModInitializer {
module.setEnabled(false);
}
private boolean isOnTypingScreen() {
return mc.currentScreen instanceof ChatScreen
|| mc.currentScreen instanceof AnvilScreen
|| mc.currentScreen instanceof AbstractSignEditScreen
|| mc.currentScreen instanceof AbstractCommandBlockScreen;
}
@SubscribeEvent
public void onStop(ShutdownEvent event) {
ConfigManager.save();
}
public static String getVersionName() {
return MOD_ID + "_v" + MOD_VERSION + "_" + SharedConstants.getGameVersion().name();
}
}
@@ -0,0 +1,61 @@
package me.retucio.sputnik.cape;
import me.retucio.sputnik.Sputnik;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.NativeImage;
import net.minecraft.client.texture.NativeImageBackedTexture;
import net.minecraft.util.Identifier;
import java.io.IOException;
import java.io.InputStream;
public class Cape {
private final MinecraftClient mc = MinecraftClient.getInstance();
private final String name;
private final Identifier id;
private NativeImage img;
private NativeImageBackedTexture texture;
public Cape(String name) {
this.name = name;
this.id = Identifier.of(Sputnik.MOD_ID, "textures/capes/" + name + ".png");
}
public void load() {
this.img = loadTexture(this.id);
}
public NativeImage loadTexture(Identifier id) {
try (InputStream inputStream = mc.getResourceManager().getResource(id).get().getInputStream()) {
return NativeImage.read(inputStream);
} catch (IOException e) {
Sputnik.LOGGER.error("ups: {}", e.getMessage());
return null;
}
}
public void register() {
texture = new NativeImageBackedTexture(null, img);
mc.getTextureManager().registerTexture(id, texture);
img = null;
}
public String getName() {
return name;
}
public Identifier getId() {
return id;
}
public NativeImageBackedTexture getTexture() {
return texture;
}
@Override
public String toString() {
return name.replace('-', ' ');
}
}
@@ -0,0 +1,87 @@
package me.retucio.sputnik.cape;
import java.util.ArrayList;
import java.util.List;
import static me.retucio.sputnik.Sputnik.mc;
public class CapeManager {
public static CapeManager INSTANCE;
private final List<Cape> capes = new ArrayList<>();
public CapeManager() {
addCapes();
}
public void addCapes() {
addCape("sputnik");
addCape("half-life");
addCape("hollow-knight");
addCape("cherry-blossom");
addCape("migrator");
addCape("minecraft");
addCape("pancakes");
addCape("vanilla");
addCape("tiktok");
addCape("twitch");
addCape("mojang");
addCape("mojang-old");
addCape("mojang-old-old");
addCape("minecon-2011");
addCape("minecon-2012");
addCape("minecon-2013");
addCape("minecon-2015");
addCape("minecon-2016");
addCape("experience-2025");
addCape("15th-anniversary");
addCape("bedrock");
addCape("birthday");
addCape("copper");
addCape("eye-blossom");
addCape("mcc-15");
addCape("prismarine");
addCape("turtle");
addCape("valentine");
addCape("chinese-translator");
addCape("cobalt");
addCape("mojira-mod");
addCape("millionth-customer");
addCape("realms-mapmaker");
addCape("scrolls-champion");
addCape("translator");
addCape("cheapsh0t");
addCape("dannybstyle");
addCape("julianclark");
addCape("mrmessiah");
for (Cape cape : capes) {
mc.execute(cape::load);
mc.execute(cape::register);
}
}
private void addCape(String name) {
capes.add(new Cape(name));
}
public Cape getCape(String name) {
for (Cape cape : capes)
if (cape.getName().equalsIgnoreCase(name))
return cape;
return null;
}
public List<Cape> getCapes() {
return capes;
}
}
@@ -1,4 +1,4 @@
package me.retucio.camtweaks.command;
package me.retucio.sputnik.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.ArgumentType;
@@ -65,7 +65,7 @@ public abstract class Command {
}
public String toString() {
return me.retucio.camtweaks.command.CommandManager.INSTANCE.getPrefix() + name;
return me.retucio.sputnik.command.CommandManager.INSTANCE.getPrefix() + name;
}
public String toString(String... args) {
@@ -1,11 +1,14 @@
package me.retucio.camtweaks.command;
package me.retucio.sputnik.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import me.retucio.camtweaks.command.commands.*;
import me.retucio.sputnik.Sputnik;
import me.retucio.sputnik.command.commands.*;
import me.retucio.sputnik.event.SubscribeEvent;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandSource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;
@@ -29,16 +32,28 @@ public class CommandManager {
public static void registerCommands() {
addCommand(new BindCommand());
addCommand(new ConfigCommand());
addCommand(new CopyScreenshotCommand());
// addCommand(new EnderChestCommand()); no funciona D:
addCommand(new EnderChestCommand());
addCommand(new GarbageCleanerCommand());
addCommand(new PeekCommand());
addCommand(new PrefixCommand());
addCommand(new PurgeCommand());
addCommand(new SaveScreenshotCommand());
addCommand(new SendCommand());
addCommand(new SpectateCommand());
addCommand(new ToggleCommand());
commands.sort(Comparator.comparing(Command::getName));
for (Command command : commands) {
for (Method method : command.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(SubscribeEvent.class)) {
Sputnik.EVENT_BUS.register(command);
break;
}
}
}
}
public static void addCommand(Command command) {
@@ -0,0 +1,208 @@
package me.retucio.sputnik.command.args;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import me.retucio.sputnik.util.EntityUtil;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import static me.retucio.sputnik.Sputnik.mc;
// para autocompletar entidades
public class EntityArgumentType implements ArgumentType<Entity> {
public static final EntityArgumentType INSTANCE = new EntityArgumentType();
private static final DynamicCommandExceptionType NO_SUCH_ENTITY = new DynamicCommandExceptionType(
name -> Text.literal("Entidad \"" + name + "\" no encontrada"));
private static final Collection<String> EXAMPLES = List.of(
"AdlerHitdolf",
"@p"
);
private static final Pattern UUID_PATTERN = Pattern.compile(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
);
private EntityArgumentType() {}
@Override
public Entity parse(StringReader reader) throws CommandSyntaxException {
String argument = reader.readString();
if (mc.world == null)
throw NO_SUCH_ENTITY.create(argument);
if (argument.startsWith("@"))
return parseSelector(argument);
if (isUUID(argument)) {
UUID uuid = UUID.fromString(argument);
return findEntityByUUID(uuid);
}
return findPlayerByName(argument);
}
private boolean isUUID(String input) {
return UUID_PATTERN.matcher(input).matches();
}
private Entity parseSelector(String selector) throws CommandSyntaxException {
if (mc.player == null) throw NO_SUCH_ENTITY.create(selector);
return switch (selector.toLowerCase()) {
case "@p" ->
findNearestPlayer();
case "@r" ->
findRandomPlayer();
case "@s" ->
mc.player;
case "@a" -> throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument()
.createWithContext(new StringReader(selector));
default -> {
if (selector.startsWith("@e"))
yield parseEntitySelector(selector);
else if (selector.startsWith("@p") && selector.length() > 2)
yield parsePlayerSelector(selector);
throw NO_SUCH_ENTITY.create(selector);
}
};
}
private Entity findNearestPlayer() throws CommandSyntaxException {
PlayerEntity nearest = null;
double nearestDistance = Double.MAX_VALUE;
for (PlayerEntity player : mc.world.getPlayers()) {
if (player == mc.player) continue;
double distance = mc.player.squaredDistanceTo(player);
if (distance < nearestDistance) {
nearestDistance = distance;
nearest = player;
}
}
if (nearest == null)
throw NO_SUCH_ENTITY.create("@p");
return nearest;
}
private Entity findRandomPlayer() throws CommandSyntaxException {
List<PlayerEntity> players = new ArrayList<>(mc.world.getPlayers());
if (players.isEmpty()) throw NO_SUCH_ENTITY.create("@r");
players.remove(mc.player);
if (players.isEmpty()) return mc.player;
Random random = new Random();
return players.get(random.nextInt(players.size()));
}
private Entity parseEntitySelector(String selector) throws CommandSyntaxException {
if (selector.equals("@e")) {
List<Entity> entities = new ArrayList<>();
for (Entity entity : mc.world.getEntities())
if (!(entity instanceof PlayerEntity))
entities.add(entity);
if (entities.isEmpty()) throw NO_SUCH_ENTITY.create(selector);
Random random = new Random();
return entities.get(random.nextInt(entities.size()));
}
if (selector.startsWith("@e[type=")) {
String type = selector.substring(8, selector.length() - 1);
return findEntityByType(type);
}
throw NO_SUCH_ENTITY.create(selector);
}
private Entity parsePlayerSelector(String selector) throws CommandSyntaxException {
return findNearestPlayer();
}
private Entity findEntityByType(String type) throws CommandSyntaxException {
List<Entity> matchingEntities = new ArrayList<>();
for (Entity entity : mc.world.getEntities()) {
String entityType = entity.getType().getTranslationKey();
if (entityType.contains(type.toLowerCase().replace("minecraft:", "")))
matchingEntities.add(entity);
}
if (matchingEntities.isEmpty()) throw NO_SUCH_ENTITY.create(type);
Entity nearest = null;
double nearestDistance = Double.MAX_VALUE;
for (Entity entity : matchingEntities) {
double distance = mc.player.squaredDistanceTo(entity);
if (distance < nearestDistance) {
nearestDistance = distance;
nearest = entity;
}
}
return nearest;
}
private Entity findEntityByUUID(UUID uuid) throws CommandSyntaxException {
for (Entity entity : mc.world.getEntities())
if (entity.getUuid().equals(uuid))
return entity;
throw NO_SUCH_ENTITY.create(uuid.toString());
}
private PlayerEntity findPlayerByName(String name) throws CommandSyntaxException {
for (PlayerEntity player : mc.world.getPlayers())
if (player.getName().getString().equalsIgnoreCase(name))
return player;
throw NO_SUCH_ENTITY.create(name);
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
if (mc.world != null)
for (PlayerEntity player : mc.world.getPlayers())
builder.suggest(player.getName().getString());
builder.suggest("@p");
builder.suggest("@r");
builder.suggest("@s");
Entity lookingAt = EntityUtil.getEntityPlayerIsLookingAt();
if (lookingAt != null)
builder.suggest(lookingAt.getUuid().toString());
return builder.buildFuture();
}
@Override
public Collection<String> getExamples() {
return EXAMPLES;
}
public static Entity get(CommandContext<?> context, String name) {
return context.getArgument(name, Entity.class);
}
}
@@ -1,4 +1,4 @@
package me.retucio.camtweaks.command.args;
package me.retucio.sputnik.command.args;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
@@ -7,8 +7,9 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.sputnik.module.Module;
import me.retucio.sputnik.module.ModuleManager;
import me.retucio.sputnik.util.MiscUtil;
import net.minecraft.command.CommandSource;
import net.minecraft.text.Text;
@@ -19,7 +20,8 @@ import java.util.concurrent.CompletableFuture;
public class ModuleArgumentType implements ArgumentType<Module> {
public static final ModuleArgumentType INSTANCE = new ModuleArgumentType();
private static final DynamicCommandExceptionType unknownModuleE = new DynamicCommandExceptionType(
private static final DynamicCommandExceptionType UNKNOWN_MODULE = new DynamicCommandExceptionType(
name -> Text.literal("módulo \"" + name + "\" no encontrado"));
private static final Collection<String> examples = ModuleManager.INSTANCE.getModules()
@@ -29,13 +31,14 @@ public class ModuleArgumentType implements ArgumentType<Module> {
public Module parse(StringReader reader) throws CommandSyntaxException {
String argument = reader.readString().replace("_", " ");
Module module = ModuleManager.INSTANCE.getModuleByName(argument);
if (module == null) throw unknownModuleE.create(argument);
if (module == null) throw UNKNOWN_MODULE.create(argument);
return module;
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
return CommandSource.suggestMatching(ModuleManager.INSTANCE.getModules().stream().map(module -> module.getName().replace(" ", "_")), builder);
return CommandSource.suggestMatching(ModuleManager.INSTANCE.getModules()
.stream().map(module -> MiscUtil.removeAccentMarks(module.getName().replace(" ", "_"))), builder);
}
@Override
@@ -1,4 +1,4 @@
package me.retucio.camtweaks.command.args;
package me.retucio.sputnik.command.args;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
@@ -15,7 +15,7 @@ import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static me.retucio.camtweaks.CameraTweaks.mc;
import static me.retucio.sputnik.Sputnik.mc;
// para autocompletar nombres de jugadores
public class PlayerArgumentType implements ArgumentType<PlayerEntity> {
@@ -45,7 +45,8 @@ public class PlayerArgumentType implements ArgumentType<PlayerEntity> {
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
return CommandSource.suggestMatching(mc.world.getPlayers().stream().map(abstractClientPlayerEntity -> abstractClientPlayerEntity.getName().getString()), builder);
return CommandSource.suggestMatching(mc.world.getPlayers().stream().map(
abstractClientPlayerEntity -> abstractClientPlayerEntity.getName().getString()), builder);
}
@Override
@@ -1,12 +1,12 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.command.args.ModuleArgumentType;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.settings.KeySetting;
import me.retucio.camtweaks.util.ChatUtil;
import me.retucio.camtweaks.util.KeyUtil;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.command.args.ModuleArgumentType;
import me.retucio.sputnik.module.Module;
import me.retucio.sputnik.module.setting.settings.KeySetting;
import me.retucio.sputnik.util.ChatUtil;
import me.retucio.sputnik.util.KeyUtil;
import net.minecraft.command.CommandSource;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
@@ -42,8 +42,7 @@ public class BindCommand extends Command {
public static boolean onKeyPress(int key) {
if (listeningModule == null) return false;
KeySetting bind = listeningModule.getBind();
if (bind != null)
bind.setKey(key);
if (bind != null) bind.setValue(key);
ChatUtil.info(
Text.of("la tecla " + Formatting.AQUA + KeyUtil.getKeyName(key) + Formatting.RESET +
@@ -0,0 +1,66 @@
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.command.args.ModuleArgumentType;
import me.retucio.sputnik.ui.screen.ClickGUI;
import me.retucio.sputnik.ui.widgets.frames.SettingsFrame;
import net.minecraft.command.CommandSource;
import me.retucio.sputnik.module.Module;
public class ConfigCommand extends Command {
public ConfigCommand() {
super("config", "abre el marco de ajustes de un módulo", "ajustes", "settings");
}
@Override
public void build(LiteralArgumentBuilder<CommandSource> builder) {
builder
.then(argument("módulo", ModuleArgumentType.INSTANCE)
.executes(ctx -> {
mc.execute(() -> openSf(ctx));
return SUCCESS;
})
.then(argument("x", IntegerArgumentType.integer())
.then(argument("y", IntegerArgumentType.integer())
.executes(ctx -> {
mc.execute(() -> openSfWithPos(ctx,
ctx.getArgument("x", Integer.class),
ctx.getArgument("y", Integer.class)));
return SUCCESS;
})
)
)
);
}
private void openSf(CommandContext<CommandSource> ctx) {
Module module = ctx.getArgument("módulo", Module.class);
mc.setScreen(ClickGUI.INSTANCE);
if (ClickGUI.INSTANCE.isSettingsFrameOpen(module)) return;
SettingsFrame sf = ClickGUI.INSTANCE.getSfOfModule(module);
int x = mc.getWindow().getScaledWidth() / 2 - sf.getW() / 2;
int y = 67;
ClickGUI.INSTANCE.openSettingsFrame(module, x, y);
}
private void openSfWithPos(CommandContext<CommandSource> ctx, int x, int y) {
Module module = ctx.getArgument("módulo", Module.class);
mc.setScreen(ClickGUI.INSTANCE);
if (ClickGUI.INSTANCE.isSettingsFrameOpen(module)) {
SettingsFrame sf = ClickGUI.INSTANCE.getSfOfModule(module);
sf.setX(x);
sf.setY(y);
}
ClickGUI.INSTANCE.openSettingsFrame(module, x, y);
}
}
@@ -1,9 +1,9 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.ScreenshotPlus;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.module.ModuleManager;
import me.retucio.sputnik.module.modules.misc.ScreenshotPlus;
import net.minecraft.command.CommandSource;
// se usa principalmente para el módulo ScreenshotPlus, pero también se puede usar sin él supongo
@@ -0,0 +1,46 @@
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.event.SubscribeEvent;
import me.retucio.sputnik.event.events.TickEvent;
import me.retucio.sputnik.ui.screen.PreviewScreen;
import me.retucio.sputnik.util.ChatUtil;
import me.retucio.sputnik.util.InventoryUtil;
import net.minecraft.command.CommandSource;
// accede a los contenidos de tu enderchest
public class EnderChestCommand extends Command {
private boolean shouldOpenEchest = false;
public EnderChestCommand() {
super("echest", "muestra el contenido de tu enderchest (solo de ver)", "ec", "enderchest");
}
@Override
public void build(LiteralArgumentBuilder<CommandSource> builder) {
builder.executes(ctx -> {
mc.execute(() -> {
if (mc.player == null) return;
if (InventoryUtil.getEchestInv() == null) {
ChatUtil.warn("necesitas abrir un enderchest una vez primero");
return;
}
shouldOpenEchest = true;
});
return SUCCESS;
});
}
@SubscribeEvent
public void onTick(TickEvent.Post event) {
if (shouldOpenEchest) {
shouldOpenEchest = false;
if (InventoryUtil.getEchestInv() != null)
mc.setScreen(new PreviewScreen(InventoryUtil.getEchestInv(), null));
}
}
}
@@ -0,0 +1,23 @@
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.util.ChatUtil;
import net.minecraft.command.CommandSource;
import net.minecraft.text.Text;
public class GarbageCleanerCommand extends Command {
public GarbageCleanerCommand() {
super("gc", "limpia la ram mediante el recolector de basura (gc)", "garbagecollect");
}
@Override
public void build(LiteralArgumentBuilder<CommandSource> builder) {
builder.executes(context -> {
System.gc();
ChatUtil.info(Text.of("basura recolectada"));
return SUCCESS;
});
}
}
@@ -1,9 +1,9 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.command.args.PlayerArgumentType;
import me.retucio.camtweaks.util.MiscUtil;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.command.args.PlayerArgumentType;
import me.retucio.sputnik.util.MiscUtil;
import net.minecraft.client.gui.screen.ingame.InventoryScreen;
import net.minecraft.command.CommandSource;
@@ -1,10 +1,10 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.ui.frames.ClientSettingsFrame;
import me.retucio.camtweaks.util.ChatUtil;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.ui.widgets.frames.settings.ClientSettingsFrame;
import me.retucio.sputnik.util.ChatUtil;
import net.minecraft.command.CommandSource;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
@@ -1,9 +1,9 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.util.interfaces.IChatHud;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.util.interfaces.IChatHud;
import net.minecraft.client.gui.hud.ChatHud;
import net.minecraft.client.gui.hud.ChatHudLine;
import net.minecraft.command.CommandSource;
@@ -31,7 +31,7 @@ public class PurgeCommand extends Command {
ChatHud chatHud = mc.inGameHud.getChatHud();
synchronized (chatHud) {
List<ChatHudLine.Visible> visibleMessages = ((IChatHud) chatHud).smegma$getVisibleMessages();
List<ChatHudLine.Visible> visibleMessages = ((IChatHud) chatHud).sputnik$getVisibleMessages();
int toRemove = Math.min(amount, visibleMessages.size());
for (int i = 0; i < toRemove; i++)
visibleMessages.removeFirst();
@@ -1,10 +1,10 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.camtweaks.module.modules.ScreenshotPlus;
import me.retucio.camtweaks.util.ChatUtil;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.module.ModuleManager;
import me.retucio.sputnik.module.modules.misc.ScreenshotPlus;
import me.retucio.sputnik.util.ChatUtil;
import net.minecraft.command.CommandSource;
import java.io.IOException;
@@ -1,9 +1,9 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.mixin.accessor.ClientPlayNetworkHandlerAccessor;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.mixin.accessor.ClientPlayNetworkHandlerAccessor;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.command.CommandSource;
import net.minecraft.network.encryption.NetworkEncryptionUtils;
@@ -11,7 +11,6 @@ import net.minecraft.network.message.LastSeenMessagesCollector;
import net.minecraft.network.message.MessageBody;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.network.packet.c2s.play.ChatMessageC2SPacket;
import net.minecraft.text.Text;
import java.time.Instant;
@@ -0,0 +1,49 @@
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.command.args.EntityArgumentType;
import me.retucio.sputnik.event.SubscribeEvent;
import me.retucio.sputnik.event.events.KeyEvent;
import me.retucio.sputnik.util.EntityUtil;
import net.minecraft.command.CommandSource;
import net.minecraft.entity.Entity;
import org.lwjgl.glfw.GLFW;
public class SpectateCommand extends Command {
public SpectateCommand() {
super("espectar", "te permite adquirir el punto de vista de una entidad", "spectate", "spec");
}
@Override
public void build(LiteralArgumentBuilder<CommandSource> builder) {
builder
.executes(ctx -> { // If no argument, use the entity player is looking at
mc.execute(() -> {
Entity target = EntityUtil.getEntityPlayerIsLookingAt();
if (target != null)
mc.setCameraEntity(target);
});
return SUCCESS;
})
.then(argument("entidad", EntityArgumentType.INSTANCE)
.executes(ctx -> {
Entity entity = EntityArgumentType.get(ctx, "entidad");
if (mc.player != null && entity != null) {
mc.setCameraEntity(entity);
}
return SUCCESS;
})
);
}
@SubscribeEvent
public void onKey(KeyEvent event) {
if (mc.getCameraEntity() != mc.player && mc.currentScreen == null
&& event.getKey() == GLFW.GLFW_KEY_ESCAPE && event.getAction() != GLFW.GLFW_RELEASE ) {
event.cancel();
mc.setCameraEntity(mc.player);
}
}
}
@@ -1,10 +1,10 @@
package me.retucio.camtweaks.command.commands;
package me.retucio.sputnik.command.commands;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.retucio.camtweaks.command.Command;
import me.retucio.camtweaks.command.args.ModuleArgumentType;
import me.retucio.camtweaks.module.Module;
import me.retucio.camtweaks.module.ModuleManager;
import me.retucio.sputnik.command.Command;
import me.retucio.sputnik.command.args.ModuleArgumentType;
import me.retucio.sputnik.module.Module;
import me.retucio.sputnik.module.ModuleManager;
import net.minecraft.command.CommandSource;
// porque usar el ratón es más lento que escribir, a menos que tengas toque con el teclado como yo
@@ -0,0 +1,357 @@
package me.retucio.sputnik.config;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class BinarySerializer {
private static final int MAGIC_NUMBER = 0x53505554; // "SPUT"
private static final int VERSION = 1;
private static final byte TYPE_NULL = 0;
private static final byte TYPE_BOOLEAN = 1;
private static final byte TYPE_INT = 2;
private static final byte TYPE_DOUBLE = 3;
private static final byte TYPE_STRING = 4;
private static final byte TYPE_MAP = 5;
private static final byte TYPE_INT_ARRAY = 6;
private static final byte TYPE_FRAME_DATA = 7;
public static void writeConfig(ClientConfig config, File file)
throws IOException {
try (DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(file)))) {
// cabezal
out.writeInt(MAGIC_NUMBER);
out.writeInt(VERSION);
// mapas
writeStringBooleanMap(out, config.moduleStates);
writeSettingsMap(out, config.settings);
writeStringIntArrayMap(out, config.settingsFrames);
writeExtendableFrames(out, config.extendableFrames);
writeStringIntArrayMap(out, config.hudPositions);
writeStringBooleanMap(out, config.hudVisibilities);
writeStringStringMap(out, config.hudImagePaths);
// posición de la barra de búsqueda
if (config.searchBarPosition != null) {
out.writeBoolean(true);
out.writeInt(config.searchBarPosition[0]);
out.writeInt(config.searchBarPosition[1]);
} else {
out.writeBoolean(false);
}
}
}
public static ClientConfig readConfig(File file)
throws IOException {
if (!file.exists() || file.length() == 0) {
throw new IOException("archivo de config. vacío o inexistente");
}
try (DataInputStream in = new DataInputStream(
new BufferedInputStream(new FileInputStream(file)))) {
if (file.length() < 8) {
throw new IOException("archivo demasiado pequeño para ser válido");
}
// verificar cabezal
int magic = in.readInt();
if (magic != MAGIC_NUMBER) {
throw new IOException("formato de archivo inválido: " + magic);
}
int version = in.readInt();
if (version != VERSION) {
throw new IOException("versión inválida: " + version);
}
ClientConfig config = new ClientConfig();
// leer mapas
config.moduleStates = readStringBooleanMap(in);
config.settings = readSettingsMap(in);
config.settingsFrames = readStringIntArrayMap(in);
config.extendableFrames = readExtendableFrames(in);
config.hudPositions = readStringIntArrayMap(in);
config.hudVisibilities = readStringBooleanMap(in);
config.hudImagePaths = readStringStringMap(in);
// leer pos. de la barra de búsqueda
if (in.readBoolean()) {
config.searchBarPosition = new int[]{in.readInt(), in.readInt()};
}
return config;
}
}
private static void writeStringBooleanMap(DataOutputStream out, Map<String, Boolean> map)
throws IOException {
if (map == null) {
out.writeInt(0);
return;
}
out.writeInt(map.size());
for (Map.Entry<String, Boolean> entry : map.entrySet()) {
writeString(out, entry.getKey());
out.writeBoolean(entry.getValue());
}
}
private static Map<String, Boolean> readStringBooleanMap(DataInputStream in)
throws IOException {
int size = in.readInt();
Map<String, Boolean> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
String key = readString(in);
boolean value = in.readBoolean();
map.put(key, value);
}
return map;
}
private static void writeSettingsMap(DataOutputStream out, Map<String, Object> map)
throws IOException {
if (map == null) {
out.writeInt(0);
return;
}
out.writeInt(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
writeString(out, entry.getKey());
writeSettingValue(out, entry.getValue());
}
}
private static Map<String, Object> readSettingsMap(DataInputStream in)
throws IOException {
int size = in.readInt();
Map<String, Object> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
String key = readString(in);
Object value = readSettingValue(in);
map.put(key, value);
}
return map;
}
private static void writeSettingValue(DataOutputStream out, Object value)
throws IOException {
switch (value) {
case Boolean b -> {
out.writeByte(TYPE_BOOLEAN);
out.writeBoolean(b);
}
case Integer i -> {
out.writeByte(TYPE_INT);
out.writeInt(i);
}
case Double v -> {
out.writeByte(TYPE_DOUBLE);
out.writeDouble(v);
}
case String s -> {
out.writeByte(TYPE_STRING);
writeString(out, s);
}
case Map<?, ?> map -> {
out.writeByte(TYPE_MAP);
writeGenericMap(out, map);
} // fallback
case null, default -> out.writeByte(TYPE_NULL);
}
}
private static Object readSettingValue(DataInputStream in) throws IOException {
byte type = in.readByte();
return switch (type) {
case TYPE_BOOLEAN -> in.readBoolean();
case TYPE_INT -> in.readInt();
case TYPE_DOUBLE -> in.readDouble();
case TYPE_STRING -> readString(in);
case TYPE_MAP -> readGenericMap(in);
default -> null;
};
}
private static void writeGenericMap(DataOutputStream out, Map<?, ?> map)
throws IOException {
if (map == null) {
out.writeInt(0);
return;
}
out.writeInt(map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {
writeObject(out, entry.getKey());
writeObject(out, entry.getValue());
}
}
private static Map<Object, Object> readGenericMap(DataInputStream in)
throws IOException {
int size = in.readInt();
Map<Object, Object> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
Object key = readObject(in);
Object value = readObject(in);
map.put(key, value);
}
return map;
}
private static void writeObject(DataOutputStream out, Object obj)
throws IOException {
switch (obj) {
case String s -> {
out.writeByte(TYPE_STRING);
writeString(out, s);
}
case Boolean b -> {
out.writeByte(TYPE_BOOLEAN);
out.writeBoolean(b);
}
case Number number -> {
if (obj instanceof Integer) {
out.writeByte(TYPE_INT);
out.writeInt((Integer) obj);
} else if (obj instanceof Double) {
out.writeByte(TYPE_DOUBLE);
out.writeDouble((Double) obj);
}
}
default -> {
out.writeByte(TYPE_STRING);
writeString(out, obj.toString());
}
}
}
private static Object readObject(DataInputStream in) throws IOException {
byte type = in.readByte();
return switch (type) {
case TYPE_STRING -> readString(in);
case TYPE_BOOLEAN -> in.readBoolean();
case TYPE_INT -> in.readInt();
case TYPE_DOUBLE -> in.readDouble();
default -> null;
};
}
private static void writeStringIntArrayMap(DataOutputStream out, Map<String, int[]> map)
throws IOException {
if (map == null) {
out.writeInt(0);
return;
}
out.writeInt(map.size());
for (Map.Entry<String, int[]> entry : map.entrySet()) {
writeString(out, entry.getKey());
int[] array = entry.getValue();
if (array == null) {
out.writeInt(0);
} else {
out.writeInt(array.length);
for (int value : array) {
out.writeInt(value);
}
}
}
}
private static Map<String, int[]> readStringIntArrayMap(DataInputStream in)
throws IOException {
int size = in.readInt();
Map<String, int[]> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
String key = readString(in);
int arraySize = in.readInt();
int[] array = new int[arraySize];
for (int j = 0; j < arraySize; j++) {
array[j] = in.readInt();
}
map.put(key, array);
}
return map;
}
private static void writeExtendableFrames(DataOutputStream out, Map<String, ClientConfig.FrameData> map)
throws IOException {
if (map == null) {
out.writeInt(0);
return;
}
out.writeInt(map.size());
for (Map.Entry<String, ClientConfig.FrameData> entry : map.entrySet()) {
writeString(out, entry.getKey());
ClientConfig.FrameData data = entry.getValue();
out.writeInt(data.x());
out.writeInt(data.y());
out.writeBoolean(data.extended());
}
}
private static Map<String, ClientConfig.FrameData> readExtendableFrames(DataInputStream in)
throws IOException {
int size = in.readInt();
Map<String, ClientConfig.FrameData> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
String key = readString(in);
int x = in.readInt();
int y = in.readInt();
boolean extended = in.readBoolean();
map.put(key, new ClientConfig.FrameData(x, y, extended));
}
return map;
}
private static void writeStringStringMap(DataOutputStream out, Map<String, String> map)
throws IOException {
if (map == null) {
out.writeInt(0);
return;
}
out.writeInt(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
writeString(out, entry.getKey());
writeString(out, entry.getValue());
}
}
private static Map<String, String> readStringStringMap(DataInputStream in)
throws IOException {
int size = in.readInt();
Map<String, String> map = new HashMap<>(size);
for (int i = 0; i < size; i++) {
String key = readString(in);
String value = readString(in);
map.put(key, value);
}
return map;
}
// Optimized string writing (UTF-8 with length prefix)
private static void writeString(DataOutputStream out, String str) throws IOException {
if (str == null) {
out.writeInt(-1);
return;
}
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
out.writeInt(bytes.length);
out.write(bytes);
}
private static String readString(DataInputStream in) throws IOException {
int length = in.readInt();
if (length == -1) return null;
byte[] bytes = new byte[length];
in.readFully(bytes);
return new String(bytes, "UTF-8");
}
}
@@ -1,15 +1,17 @@
package me.retucio.camtweaks.config;
package me.retucio.sputnik.config;
import me.retucio.camtweaks.event.SubscribeEvent;
import me.retucio.camtweaks.event.events.camtweaks.*;
import me.retucio.camtweaks.module.settings.*;
import me.retucio.camtweaks.ui.ClickGUI;
import me.retucio.sputnik.event.SubscribeEvent;
import me.retucio.sputnik.event.events.sputnik.*;
import me.retucio.sputnik.module.setting.settings.*;
import me.retucio.sputnik.ui.screen.ClickGUI;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import static me.retucio.camtweaks.CameraTweaks.EVENT_BUS;
import static me.retucio.camtweaks.CameraTweaks.mc;
import static me.retucio.sputnik.Sputnik.EVENT_BUS;
import static me.retucio.sputnik.Sputnik.mc;
// clase donde se guardan las configuraciones temporalmente hasta escribirlas en camera_tweaks.json
public class ClientConfig {
@@ -32,6 +34,12 @@ public class ClientConfig {
// id del elemento del hud -> true: visible / false: no visible
public Map<String, Boolean> hudVisibilities = new HashMap<>();
// id del elemento del hud -> ruta de la imagen (NEW)
public Map<String, String> hudImagePaths = new HashMap<>();
// posición de la barra de búsqueda (x, y)
public int[] searchBarPosition = new int[]{340, 16};
public ClientConfig() {
EVENT_BUS.register(this);
}
@@ -49,12 +57,14 @@ public class ClientConfig {
// guardar ajustes con su respectivo tipo de valor, en formato "nombreMódulo:nombreAjuste"
Object value = null;
switch (event.getSetting()) {
case BooleanSetting b: value = b.isEnabled(); break;
case BooleanSetting b: value = b.getValue(); break;
case EnumSetting e: value = e.getIndex(); break;
case KeySetting k: value = k.getKey(); break;
case KeySetting k: value = k.getValue(); break;
case NumberSetting n: value = n.getValue(); break;
case StringSetting s: value = s.getValue(); break;
case ListSetting l: value = l.getValues(); break;
case ListSetting l: value = l.getConfigValues(); break;
case ColorSetting c: value = c.getConfigValue(); break;
case OptionSetting o: value = o.getDisplayName(); break;
default: break;
}
@@ -63,53 +73,54 @@ public class ClientConfig {
@SubscribeEvent
public void onOpenSettingsFrame(SettingsFrameEvent.Open event) {
if (settingsFrames.containsKey(event.getFrame().module.getName())) return;
ConfigManager.setFramePosition(event.getFrame());
}
@SubscribeEvent
public void onCloseSettingsFrame(SettingsFrameEvent.Close event) {
settingsFrames.remove(event.getFrame().module.getName());
settingsFrames.remove(event.getFrame().getModule().getName());
ConfigManager.save();
}
@SubscribeEvent
public void onMoveSettingsFrame(SettingsFrameEvent.Move event) {
settingsFrames.replace(event.getFrame().module.getName(), new int[]{event.getFrame().x, event.getFrame().y});
settingsFrames.replace(event.getFrame().getModule().getName(), new int[]{event.getFrame().getX(), event.getFrame().getY()});
ConfigManager.save();
}
@SubscribeEvent
public void onExtendModuleFrame(ModuleFrameEvent.Extend event) {
extendableFrames.put("M", new FrameData(
ClickGUI.INSTANCE.getModulesFrame().x,
ClickGUI.INSTANCE.getModulesFrame().y,
ClickGUI.INSTANCE.getModulesFrame().getX(),
ClickGUI.INSTANCE.getModulesFrame().getY(),
ClickGUI.INSTANCE.getModulesFrame().extended));
}
@SubscribeEvent
public void onMoveModuleFrame(ModuleFrameEvent.Move event) {
extendableFrames.replace("M", new FrameData(
ClickGUI.INSTANCE.getModulesFrame().x,
ClickGUI.INSTANCE.getModulesFrame().y,
ClickGUI.INSTANCE.getModulesFrame().getX(),
ClickGUI.INSTANCE.getModulesFrame().getY(),
ClickGUI.INSTANCE.getModulesFrame().extended));
}
@SubscribeEvent
public void onExtendGUISettingsFrame(GUISettingsFrameEvent.Extend event) {
extendableFrames.put("S", new FrameData(
ClickGUI.INSTANCE.getGuiSettingsFrame().x,
ClickGUI.INSTANCE.getGuiSettingsFrame().y,
ClickGUI.INSTANCE.getGuiSettingsFrame().getX(),
ClickGUI.INSTANCE.getGuiSettingsFrame().getY(),
ClickGUI.INSTANCE.getGuiSettingsFrame().extended));
}
@SubscribeEvent
public void onMoveGUISettingsFrame(GUISettingsFrameEvent.Move event) {
extendableFrames.replace("S", new FrameData(
ClickGUI.INSTANCE.getGuiSettingsFrame().x,
ClickGUI.INSTANCE.getGuiSettingsFrame().y,
ClickGUI.INSTANCE.getGuiSettingsFrame().getX(),
ClickGUI.INSTANCE.getGuiSettingsFrame().getY(),
ClickGUI.INSTANCE.getGuiSettingsFrame().extended));
}
public record FrameData(int x, int y, boolean extended) {}
public record FrameData(int x, int y, boolean extended) implements Serializable {
@Serial private static final long serialVersionUID = 1L;
}
}
@@ -0,0 +1,352 @@
package me.retucio.sputnik.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import me.retucio.sputnik.Sputnik;
import me.retucio.sputnik.module.Module;
import me.retucio.sputnik.module.ModuleManager;
import me.retucio.sputnik.module.setting.*;
import me.retucio.sputnik.module.setting.settings.*;
import me.retucio.sputnik.ui.widgets.Frame;
import me.retucio.sputnik.ui.widgets.frames.ModuleFrame;
import me.retucio.sputnik.ui.screen.ClickGUI;
import me.retucio.sputnik.ui.widgets.frames.settings.ClientSettingsFrame;
import me.retucio.sputnik.ui.widgets.frames.SettingsFrame;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
// se ocupa de guardar, cargar y aplicar ajustes
public class ConfigManager {
private static final File CONFIG_FILE = new File("sputnik.dat");
private static final File LEGACY_JSON_FILE = new File("sputnik.json");
private static boolean loaded = false;
private static ClientConfig config = null;
// ------------------ MÉTODOS PRINCIPALES ------------------
// guardar configuraciones
public static void save() {
if (!loaded) return;
ensureConfig();
try {
BinarySerializer.writeConfig(config, CONFIG_FILE);
Sputnik.LOGGER.info("ajustes guardados");
} catch (IOException e) {
Sputnik.LOGGER.error("error al guardar ajustes", e);
}
}
public static void load() {
Sputnik.LOGGER.info("cargando ajustes...");
if (CONFIG_FILE.exists()) {
try {
config = BinarySerializer.readConfig(CONFIG_FILE);
Sputnik.LOGGER.info("ajustes cargados");
return;
} catch (IOException e) {
Sputnik.LOGGER.error("error cargando ajustes, intentando json", e);
}
}
// Fallback to legacy JSON
if (LEGACY_JSON_FILE.exists()) {
try (FileReader reader = new FileReader(LEGACY_JSON_FILE)) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
config = gson.fromJson(reader, ClientConfig.class);
Sputnik.LOGGER.info("ajustes json cargados (migración)");
save();
return;
} catch (IOException e) {
Sputnik.LOGGER.error("error cargando json, usando defaults", e);
}
}
// crear nuevo config
ensureConfig();
save();
}
// aplicar configuraciones cargadas
public static void applyConfig() {
if (!shouldApply()) return;
applyModuleStates();
applyModuleSettings();
applySettingsFrames();
applySearchBarPosition();
applyGuiSettings();
applyExtendableFrames();
loaded = true;
Sputnik.LOGGER.info("ajustes aplicados");
}
// obtener configuración actual
public static ClientConfig getConfig() {
ensureConfig();
return config;
}
// ------------------ GUARDAR VALORES INDIVIDUALES EN LA CONFIG. ------------------
public static void setModuleState(Module module) {
ensureConfig();
config.moduleStates.put(module.getName(), module.isEnabled());
save();
}
public static void setSetting(Setting<?> setting, Object value) {
ensureConfig();
config.settings.put(getSettingKey(setting), value);
save();
}
public static void setFramePosition(SettingsFrame frame) {
ensureConfig();
if (!config.settingsFrames.containsKey(frame.getModule().getName()))
config.settingsFrames.put(frame.getModule().getName(), new int[] {frame.getX(), frame.getY()});
else
config.settingsFrames.replace(frame.getModule().getName(), new int[] {frame.getX(), frame.getY()});
save();
}
public static void setExtendableFrame(String key, ClientConfig.FrameData data) {
ensureConfig();
config.extendableFrames.put(key, data);
save();
}
public static void setHudPosition(String id, int x, int y) {
ensureConfig();
config.hudPositions.put(id, new int[] {x, y});
save();
}
public static void setHudVisibility(String id, Boolean visible) {
ensureConfig();
config.hudVisibilities.put(id, visible);
save();
}
public static void setSearchBarPosition(int x, int y) {
ensureConfig();
config.searchBarPosition = new int[] {x, y};
save();
}
// ------------------ APLICAR AJUSTES ------------------
@SuppressWarnings({"rawtypes", "unchecked"})
public static void applySetting(Module parent, Setting<?> setting) {
String key = getSettingKey(setting);
if (!config.settings.containsKey(key)) return;
Object value = config.settings.get(key);
switch (setting) {
case BooleanSetting booleanSetting -> applyBooleanSetting(booleanSetting, value);
case EnumSetting enumSetting -> applyEnumSetting(enumSetting, value);
case NumberSetting numberSetting -> applyNumberSetting(numberSetting, value);
case StringSetting stringSetting -> applyStringSetting(stringSetting, value);
case KeySetting keySetting -> applyKeySetting(keySetting, value);
case ListSetting listSetting -> applyListSetting(listSetting, value);
case ColorSetting colorSetting -> applyColorSetting(colorSetting, value);
case OptionSetting optionSetting -> applyOptionSetting(optionSetting, value);
default -> Sputnik.LOGGER.warn("watafac queseso: {}", setting.getClass().getSimpleName());
}
}
private static void applyModuleStates() {
ModuleManager.INSTANCE.getModules().forEach(module -> {
if (config.moduleStates.containsKey(module.getName())) {
module.setEnabled(config.moduleStates.get(module.getName()));
}
});
Sputnik.LOGGER.info("estados de módulos aplicados");
}
private static void applyModuleSettings() {
ModuleManager.INSTANCE.getModules().forEach(module -> {
module.getSettings().forEach(setting -> applySetting(module, setting));
});
Sputnik.LOGGER.info("ajustes de módulos aplicados");
}
private static void applySettingsFrames() {
config.settingsFrames.forEach((moduleName, position) -> {
Module module = ModuleManager.INSTANCE.getModuleByName(moduleName);
if (module == null) {
Sputnik.LOGGER.warn("\"null\" como módulo (\"{}\")", moduleName);
return;
}
ClickGUI.INSTANCE.openSettingsFrame(module, position[0], position[1]);
});
Sputnik.LOGGER.info("estados de marcos de ajustes aplicados");
}
private static void applySearchBarPosition() {
if (config.searchBarPosition != null && config.searchBarPosition.length == 2) {
ClickGUI.INSTANCE.getSearchBar().setX(config.searchBarPosition[0]);
ClickGUI.INSTANCE.getSearchBar().setY(config.searchBarPosition[1]);
}
Sputnik.LOGGER.info("posición de la barra de búsqueda aplicada");
}
private static void applyGuiSettings() {
ClientSettingsFrame.guiSettings.setEnabled(true);
ClientSettingsFrame.guiSettings.getSettings().forEach(setting -> {
applySetting(ClientSettingsFrame.guiSettings, setting);
});
Sputnik.LOGGER.info("ajustes del cliente aplicados");
}
private static void applyExtendableFrames() {
applyExtendableFrame(ClickGUI.INSTANCE.getModulesFrame());
applyExtendableFrame(ClickGUI.INSTANCE.getGuiSettingsFrame());
Sputnik.LOGGER.info("posiciones de marcos extendibles aplicadas");
ClickGUI.INSTANCE.refreshListButtons();
}
private static void applyExtendableFrame(Frame<?> frame) {
ClientConfig.FrameData frameData = null;
if (frame instanceof ModuleFrame)
frameData = config.extendableFrames.get("M");
if (frame instanceof ClientSettingsFrame)
frameData = config.extendableFrames.get("S");
if (frameData != null) {
frame.setX(frameData.x());
frame.setY(frameData.y());
if (frame instanceof ModuleFrame mFrame)
mFrame.extended = frameData.extended();
if (frame instanceof ClientSettingsFrame sFrame)
sFrame.extended = frameData.extended();
}
}
// ajustes de módulos
private static void applyBooleanSetting(BooleanSetting setting, Object value) {
if (value instanceof Boolean) {
setting.setValue((Boolean) value);
}
}
private static <T extends Enum<T>> void applyEnumSetting(EnumSetting<T> setting, Object value) {
if (value instanceof Double) {
setting.setIndex(((Double) value).intValue());
} else if (value instanceof Integer) {
setting.setIndex((Integer) value);
}
}
private static void applyNumberSetting(NumberSetting setting, Object value) {
if (value instanceof Double) {
setting.setValue((Double) value);
}
}
private static void applyStringSetting(StringSetting setting, Object value) {
if (value instanceof String) {
setting.setValue((String) value);
}
}
private static void applyKeySetting(KeySetting setting, Object value) {
if (value instanceof Double) {
setting.setValue(((Double) value).intValue());
} else if (value instanceof Integer) {
setting.setValue((Integer) value);
}
}
private static <T> void applyListSetting(ListSetting<T> setting, Object value) {
if (value instanceof Map<?, ?> map) {
Map<T, Boolean> convertedValues = new HashMap<>();
for (T option : setting.getOptions()) {
String key = setting.getDisplayName(option);
Object booleanValue = map.get(key);
convertedValues.put(option, booleanValue instanceof Boolean && (Boolean) booleanValue);
}
setting.setValue(convertedValues);
}
}
private static void applyColorSetting(ColorSetting setting, Object value) {
if (!(value instanceof Map<?, ?> map)) return;
Number r = (Number) map.get("r");
Number g = (Number) map.get("g");
Number b = (Number) map.get("b");
Number a = (Number) map.get("a");
if (r != null && g != null && b != null && a != null) {
setting.setRGB(
r.intValue(),
g.intValue(),
b.intValue(),
a.intValue()
);
}
applyOptionalProperty(map, "rb", Boolean.class, setting::setRainbow);
applyOptionalProperty(map, "rs", Number.class, val -> setting.setRainbowSpeed(val.intValue()));
applyOptionalProperty(map, "sat", Number.class, val -> setting.setSaturation(val.floatValue()));
applyOptionalProperty(map, "bri", Number.class, val -> setting.setBrightness(val.floatValue()));
}
private static <T> void applyOptionSetting(OptionSetting<T> setting, Object value) {
if (value instanceof String name) {
setting.setValueByName(name);
}
}
private static <T> void applyOptionalProperty(Map<?, ?> map, String key, Class<T> type, Consumer<T> setter) {
Object value = map.get(key);
if (type.isInstance(value)) {
setter.accept(type.cast(value));
}
}
// ------------------ MÉTODOS DE AYUDA ------------------
private static boolean shouldApply() {
return Sputnik.mc != null && ModuleManager.INSTANCE != null && config != null;
}
private static void ensureConfig() {
if (config == null) config = new ClientConfig();
}
private static String getSettingKey(Setting<?> setting) {
return setting.getSg().getModule().getName() + ":" + setting.getName();
}
public static boolean hasLoaded() {
return loaded;
}
}
@@ -0,0 +1,27 @@
package me.retucio.sputnik.event;
import net.minecraft.entity.vehicle.AbstractBoatEntity;
import net.minecraft.util.math.Vec3d;
public class BoatMoveEvent extends Event {
private final AbstractBoatEntity boat;
private Vec3d pos;
public BoatMoveEvent(AbstractBoatEntity boat, Vec3d pos) {
this.boat = boat;
this.pos = pos;
}
public AbstractBoatEntity getBoat() {
return boat;
}
public Vec3d getPos() {
return pos;
}
public void setPos(Vec3d pos) {
this.pos = pos;
}
}
@@ -1,7 +1,8 @@
package me.retucio.camtweaks.event;
package me.retucio.sputnik.event;
// evento base, cancelable (usado en mixins)
public class Event {
private boolean cancelled;
public boolean isCancelled() {
@@ -1,4 +1,4 @@
package me.retucio.camtweaks.event;
package me.retucio.sputnik.event;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -6,6 +6,7 @@ import java.util.*;
// al llamar un evento, se guarda en el bus de eventos, de donde luego se puede detectar si ese evento ha sucedido
public class EventBus {
private final Map<Class<?>, List<ListenerMethod>> listeners = new HashMap<>();
private record ListenerMethod(Object instance, Method method) {}
@@ -1,4 +1,4 @@
package me.retucio.camtweaks.event;
package me.retucio.sputnik.event;
public enum Stage {
PRE, // antes de que haya sucedido
@@ -1,4 +1,4 @@
package me.retucio.camtweaks.event;
package me.retucio.sputnik.event;
import java.lang.annotation.*;
@@ -0,0 +1,21 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.entity.Entity;
/**
* @see me.retucio.sputnik.mixin.ClientWorldMixin#onAddEntity
*/
public class AddEntityEvent extends Event {
private final Entity entity;
public AddEntityEvent(Entity entity) {
this.entity = entity;
}
public Entity getEntity() {
return entity;
}
}
@@ -0,0 +1,24 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
public class AttackBlockEvent extends Event {
private final BlockPos pos;
private final Direction dir;
public AttackBlockEvent(BlockPos pos, Direction dir) {
this.pos = pos;
this.dir = dir;
}
public BlockPos getPos() {
return pos;
}
public Direction getDir() {
return dir;
}
}
@@ -0,0 +1,21 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.entity.Entity;
/**
* @see me.retucio.sputnik.mixin.ClientPlayerInteractionManagerMixin#onAttackEntity
*/
public class AttackEntityEvent extends Event {
private final Entity entity;
public AttackEntityEvent(Entity entity) {
this.entity = entity;
}
public Entity getEntity() {
return entity;
}
}
@@ -0,0 +1,43 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.shape.VoxelShape;
public class BlockShapeEvent extends Event {
private BlockState state;
private BlockPos pos;
private VoxelShape shape;
public BlockShapeEvent(BlockState state, BlockPos pos, VoxelShape shape) {
this.state = state;
this.pos = pos;
this.setShape(shape);
}
public BlockState getState() {
return state;
}
public void setState(BlockState state) {
this.state = state;
}
public BlockPos getPos() {
return pos;
}
public void setPos(BlockPos pos) {
this.pos = pos;
}
public VoxelShape getShape() {
return shape;
}
public void setShape(VoxelShape shape) {
this.shape = shape;
}
}
@@ -0,0 +1,25 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.util.math.BlockPos;
/**
* @see me.retucio.sputnik.mixin.ClientPlayerInteractionManagerMixin#onBlockBreak
*/
public class BreakBlockEvent extends Event {
private BlockPos pos;
public BreakBlockEvent(BlockPos pos) {
this.pos = pos;
}
public BlockPos getPos() {
return pos;
}
public void setPos(BlockPos pos) {
this.pos = pos;
}
}
@@ -0,0 +1,36 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
/**
* @see me.retucio.sputnik.mixin.EntityMixin#onRotation
* @see me.retucio.sputnik.mixin.EntityMixin#onChangeYaw
* @see me.retucio.sputnik.mixin.EntityMixin#onChangePitch
*/
public class ChangeRotationEvent extends Event {
private float yaw;
private float pitch;
public ChangeRotationEvent(float yaw, float pitch) {
this.yaw = yaw;
this.pitch = pitch;
}
public float getYaw() {
return yaw;
}
public void setYaw(float yaw) {
this.yaw = yaw;
}
public float getPitch() {
return pitch;
}
public void setPitch(float pitch) {
this.pitch = pitch;
}
}
@@ -0,0 +1,9 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
/**
* @see me.retucio.sputnik.mixin.ChunkOcclusionDataBuilderMixin#onChunkOcclusion
*/
public class ChunkOcclusionEvent extends Event {}
@@ -1,11 +1,12 @@
package me.retucio.camtweaks.event.events;
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.module.modules.misc.ChatPlus;
import net.minecraft.text.ClickEvent;
/** este evento es solo para asegurarse de que comandos del mod se puedan ejecutar solo desde el lado del cliente
* @see me.retucio.camtweaks.module.modules.ChatPlus#getSendButton
*/
/** este evento es solo para asegurarse de que comandos del mod se puedan ejecutar solo desde el lado del cliente
* @see ChatPlus#getSendButton
*/
public class ClientClickEvent implements ClickEvent {
private final String value;
@@ -0,0 +1,20 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
public class ClipAtLedgeEvent extends Event {
private boolean clipping;
public ClipAtLedgeEvent(boolean clipping) {
this.clipping = clipping;
}
public boolean isClipping() {
return clipping;
}
public void setClipping(boolean clipping) {
this.clipping = clipping;
}
}
@@ -0,0 +1,27 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.item.ItemStack;
/**
* @see me.retucio.sputnik.mixin.ItemStackMixin#onDamage
*/
public class DamageItemEvent extends Event {
private final int amount;
private final ItemStack stack;
public DamageItemEvent(int amount, ItemStack stack) {
this.amount = amount;
this.stack = stack;
}
public int getAmount() {
return amount;
}
public ItemStack getStack() {
return stack;
}
}
@@ -0,0 +1,28 @@
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.network.DisconnectionInfo;
/**
* @see me.retucio.sputnik.mixin.ClientConnectionMixin#onDisconnect
*/
public class DisconnectEvent extends Event {
private final DisconnectionInfo info;
private final ServerInfo server;
public DisconnectEvent(DisconnectionInfo info, ServerInfo server) {
this.info = info;
this.server = server;
}
public DisconnectionInfo getInfo() {
return info;
}
public ServerInfo getServer() {
return server;
}
}
@@ -1,11 +1,11 @@
package me.retucio.camtweaks.event.events;
package me.retucio.sputnik.event.events;
import me.retucio.sputnik.event.Event;
import me.retucio.camtweaks.event.Event;
/**
* @see me.retucio.camtweaks.mixin.GameRendererMixin#modifyFov
* @see me.retucio.sputnik.mixin.GameRendererMixin#modifyFov
*/
public class GetFOVEvent extends Event {
private float fov;
Loaded 100 of 455 files, more files were not shown because too many files have changed in this diff. Show more