chore(history): squash 59 commit(s) from 2026-09-23
- refactor(hud/weather/render): Scoreboard 931→240 + Rain 903→159 + UiMeshGeometry 956→99 (8.5.2) - refactor(chams): Chams 985 → 129 + 4×≤195 (8.5.2) - refactor(module): Module 1031 → 139 + 4×≤134 (8.5.2) - refactor(tooltips): BetterTooltips 960 → 181 + 4×≤199 (8.5.2) - refactor(clickgui): ClickGuiPickerState 970→166 + ModulesMenuScreen 966→145 (8.5.2) - refactor(clickgui): CombatProtocolHeuristicsEditorState 932→79 + 4×≤192 (8.5.2) - refactor(hud): CompactHudStatModel 894 → 125 + 4×≤175 (8.5.2) - refactor(iris): ShaderPatchCompiler 843→66 + 4×≤174 (8.5.2) - refactor(tab): CustomTabList 834→136 + 4×≤166 (8.5.2) - refactor(relations): OnlineRelationPlayerPickerComponent 837→74 + 4×≤192 (8.5.2) - refactor(hits): HitEffect 770→120 + 4×≤176 (8.5.2) - refactor(predict): Predictions 815→150 + 4×≤195 (8.5.2) - refactor(config): ConfigProfilesComponent 799→125 + 4×≤195 (8.5.2) - refactor(sim): PlayerMovementSimulation 757→157 + 4×≤194 (8.5.2) - refactor(predict): ProjectilePuncher 747→104 + 3×≤134 (8.5.2) - refactor(crosshair): Crosshair 743→143 + 4×≤167 (8.5.2) - refactor(mediaplayer): MediaPlayer 743→174 + 4×≤196 (8.5.2) - refactor(hud): Itemizer 699→193 + Cooldowns 707→151 (8.5.2) - refactor(hud): Potions 617→176 + 4×≤166 (8.5.2) - refactor(hud): Admins 702→118 + 4×≤138 (8.5.2) - refactor(hud): Keybinds 611→157 + 4×≤160 (8.5.2) - refactor(hud): ModuleList 499→181 + 3×≤150 (8.5.2) - refactor(hud): Radar 392→161 + 2×≤124 (8.5.2) - refactor(hud): Fps 309→168 + 3×≤107 (8.5.2) - refactor(hud): Memory 304→151 + 3×≤144 (8.5.2) - refactor(hud): Tps 339→154 + 3×≤143 (8.5.2) - refactor(hud): Ping 309→145 + 3×≤125 (8.5.2) - refactor(hud): SpeedBps 334→156 + 3×≤142 (8.5.2) - refactor(hud): GameTime 314→150 + 3×≤127 (8.5.2) - refactor(hud): SystemTime 300→136 + 3×≤130 (8.5.2) - refactor(hud): Coordinates 337→174 + 2×≤172 (8.5.2) - refactor(hud): Armor 324→162 + 2×≤148 (8.5.2) - refactor(hud): Inventory 476→153 + 3×≤181 (8.5.2) - docs(todo): обновлён 8.5.2 — отмечены готовые гиганты (BetterButtons/InventorySwap/Svg/Темы/WorldParticles/Module/Chams и хвост) - docs(api): папка combatant-client-26.2/docs + addons.md (API можно ломать при рефакторе) - refactor(visuals): BlockHighlight 692→271 + 4×≤200 (8.5.2) - refactor(mixins): GameRendererMixin 830→344 (хуки) + 4 хелпера (8.5.2) - refactor(visuals): WorldParticles 821→260 + 6×≤200, режимы добиты (8.5.2) - docs(todo): 8.5.2 — WorldParticles/GameRendererMixin/BlockHighlight отмечены ГОТОВО - refactor(render): MeshBuilder 738→447 (фасад write-API) + 3 хелпера, FrameStats снесён (8.5.2) - docs(todo): Фаза 10 — дизайн платформы (аккаунты/конфиги/аватарки), backlog RPC-чата - docs(todo): Подсистема 3 — Аддоны 2.0 (скрипты/версии) + витрина аддонов + админка - docs(todo): Подсистема 2 — RPC-чат/друзья/виджеты-телеметрия + рейт-лимиты, доп. правки Подсистемы 3 - chore: переименование combatant-client-26.2 -> mod, добавлены backend/ и frontend/ - docs(backend): implementation plan for accounts-service (Подсистема 1, часть 1) - chore: пересоздать backend/frontend через cargo new и bun create vite + tailwind; убрать таблицу компонентов из TODO.md - docs(backend): edition 2024 в плане вместо 2021 - chore: обновить версии до реально актуальных (проверено компиляцией) - docs: правила платформы (лимит 250 строк, антипаттерны backend/frontend по итогам ресёрча) + frontend/ARCHITECTURE.md - docs: добавить правило ≤4 файла на папку в правила платформы (backend/frontend) - docs: commit messages in English from now on - chore: gitignore .superpowers/ scratch directory - docs: commit messages in English from now on (mod) - feat(backend): scaffold accounts-service with health check - chore(backend): remove target/ build artifacts from git, add gitignore - chore: track docs/ in git (was accidentally gitignored, never committed) - chore(backend): convert to Cargo workspace, plan full microservice layout - feat(backend): accounts/avatars/device_links schema + migration - feat(backend): argon2id password hashing
This commit is contained in:
parent
ec10395511
commit
9d08fa910a
2239 changed files with 35265 additions and 28110 deletions
60
mod/src/main/java/dev/loki/lovisual/Lifecycle.java
Normal file
60
mod/src/main/java/dev/loki/lovisual/Lifecycle.java
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual;
|
||||
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import dev.loki.lovisual.util.resources.RenderResourceReadiness;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* Minimal client lifecycle: INIT until explicitly activated, then ACTIVE.
|
||||
* Replaces the former Runtime/JarReplacement state machine.
|
||||
*/
|
||||
public enum Lifecycle {
|
||||
;
|
||||
|
||||
private enum State {
|
||||
INIT,
|
||||
ACTIVE,
|
||||
SHUTDOWN
|
||||
}
|
||||
|
||||
private static final AtomicReference<State> STATE = new AtomicReference<>(State.INIT);
|
||||
|
||||
private Lifecycle() {
|
||||
}
|
||||
|
||||
public static void activate() {
|
||||
if (STATE.compareAndSet(State.INIT, State.ACTIVE)) {
|
||||
DebugLog.info("Lifecycle: INIT -> ACTIVE");
|
||||
}
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
if (STATE.getAndSet(State.SHUTDOWN) != State.SHUTDOWN) {
|
||||
DebugLog.info("Lifecycle: -> SHUTDOWN");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isActive() {
|
||||
return STATE.get() == State.ACTIVE;
|
||||
}
|
||||
|
||||
public static boolean canRunRender() {
|
||||
return isActive() && RenderResourceReadiness.isReady();
|
||||
}
|
||||
|
||||
public static boolean canRunHud() {
|
||||
return canRunRender();
|
||||
}
|
||||
|
||||
public static boolean canRunShaderBridge() {
|
||||
return canRunRender();
|
||||
}
|
||||
}
|
||||
437
mod/src/main/java/dev/loki/lovisual/LoVisual.java
Normal file
437
mod/src/main/java/dev/loki/lovisual/LoVisual.java
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual;
|
||||
|
||||
import dev.loki.lovisual.events.impl.render.GameTickEvent;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.hud.HudElementRegistry;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements;
|
||||
import net.fabricmc.fabric.api.client.rendering.v1.level.LevelRenderEvents;
|
||||
import net.minecraft.client.DeltaTracker;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonRenderPipelineManager;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import dev.loki.lovisual.config.i18n.MainConfig;
|
||||
import dev.loki.lovisual.events.Events;
|
||||
import dev.loki.lovisual.features.account.AccountConfig;
|
||||
import dev.loki.lovisual.features.command.core.CommandManager;
|
||||
import dev.loki.lovisual.features.gui.clickgui.render.ClickGuiRenderer;
|
||||
import dev.loki.lovisual.features.gui.clickgui.settings.i18n.I18nPreflightContributors;
|
||||
import dev.loki.lovisual.features.gui.hud.registry.HudElements;
|
||||
import dev.loki.lovisual.features.gui.hud.anchor.HudRenderSpace;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementBootstrap;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.impl.buttons.SwapTooltip;
|
||||
import dev.loki.lovisual.features.module.phase.HudPhase;
|
||||
import dev.loki.lovisual.features.module.lifecycle.ModuleAutoLoader;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.features.module.phase.WorldPhase;
|
||||
import dev.loki.lovisual.mixininterface.render.IGuiGraphics;
|
||||
import dev.loki.lovisual.render.effects.NetherPortalRiftPass;
|
||||
import dev.loki.lovisual.render.effects.SleepOverlayPass;
|
||||
import dev.loki.lovisual.render.engine.LoVisualRenderEngineBootstrap;
|
||||
import dev.loki.lovisual.render.engine.core.system.LoVisualRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.core.frame.RenderPhase;
|
||||
import dev.loki.lovisual.render.engine.core.frame.RenderPhaseScope;
|
||||
import dev.loki.lovisual.render.engine.core.context.ViewportContext;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessManager;
|
||||
import dev.loki.lovisual.render.engine.profiler.config.ProfilerPhase;
|
||||
import dev.loki.lovisual.render.engine.profiler.render.RenderProfiler2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.FullScreenRenderer;
|
||||
import dev.loki.lovisual.render.engine.prewarm.RenderPrewarmContributors;
|
||||
import dev.loki.lovisual.render.engine.prewarm.RenderPrewarmManager;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import dev.loki.lovisual.render.helpers.util.SystemCursor;
|
||||
import dev.loki.lovisual.render.helpers.util.TickDelta;
|
||||
import dev.loki.lovisual.util.aiming.rotation.RotationManager;
|
||||
import dev.loki.lovisual.util.block.bed.SelfBedTracker;
|
||||
import dev.loki.lovisual.util.click.AttackPressing;
|
||||
import dev.loki.lovisual.util.combat.tracking.AntiBotTracker;
|
||||
import dev.loki.lovisual.util.combat.protocol.heuristics.CombatProtocolHeuristics;
|
||||
import dev.loki.lovisual.util.combat.rotation.SprintController;
|
||||
import dev.loki.lovisual.util.entity.simulation.BoatSimulationCache;
|
||||
import dev.loki.lovisual.util.media.session.MediaSessionService;
|
||||
import dev.loki.lovisual.util.network.control.BacktrackController;
|
||||
import dev.loki.lovisual.util.network.control.BlinkManager;
|
||||
import dev.loki.lovisual.util.proxy.ProxyBackend;
|
||||
import dev.loki.lovisual.util.network.control.FakeLagController;
|
||||
import dev.loki.lovisual.util.player.simulation.PlayerSimulationCache;
|
||||
import dev.loki.lovisual.util.pvp.tracker.PvpTargetTracker;
|
||||
import dev.loki.lovisual.util.pvp.tracker.PvpTracker;
|
||||
import dev.loki.lovisual.util.target.TargetManager;
|
||||
import dev.loki.lovisual.util.time.TimerController;
|
||||
import dev.loki.lovisual.features.gui.clickgui.settings.bind.KeyBindSetting;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
public class LoVisual implements ClientModInitializer {
|
||||
|
||||
private static void renderWorldPhase(WorldPhase phase,
|
||||
com.mojang.blaze3d.vertex.PoseStack matrices,
|
||||
net.minecraft.client.renderer.SubmitNodeCollector consumers) {
|
||||
if (!Lifecycle.canRunRender()) return;
|
||||
|
||||
ModuleManager.renderWorld(
|
||||
phase,
|
||||
matrices,
|
||||
consumers,
|
||||
TickDelta.tickProgress(false)
|
||||
);
|
||||
}
|
||||
|
||||
private static void refreshHudFrameTiming(DeltaTracker tickCounter) {
|
||||
LoVisualRenderSystem.updateFrameTiming(
|
||||
TickDelta.tickProgress(tickCounter, false),
|
||||
TickDelta.frameDeltaTicks(tickCounter),
|
||||
TickDelta.fixedDeltaTicks(tickCounter)
|
||||
);
|
||||
}
|
||||
|
||||
private static void renderHudPhase(HudPhase phase, GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
|
||||
if (!Lifecycle.canRunHud()) return;
|
||||
float tickProgress = TickDelta.tickProgress(tickCounter, false);
|
||||
ModuleManager.renderHud(phase, ctx, tickProgress);
|
||||
Renderer2D.Deferred2DLayer layer = deferredLayerForHudPhase(phase);
|
||||
if (renderHudEngine(phase, layer, ctx, tickCounter)) {
|
||||
appendHudDeferredMarker(layer, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean renderHudEngine(HudPhase phase,
|
||||
Renderer2D.Deferred2DLayer layer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
DeltaTracker tickCounter) {
|
||||
boolean rawMain = hasHudMainPassWork(phase, HudRenderSpace.UNSCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_RAW);
|
||||
boolean scaledMain = hasHudMainPassWork(phase, HudRenderSpace.SCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_SCALED);
|
||||
boolean logicalMain = hasHudMainPassWork(phase, HudRenderSpace.UNSCALED_LOGICAL)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_LOGICAL);
|
||||
boolean rawForeground = hasHudForegroundPassWork(phase, HudRenderSpace.UNSCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_RAW_FOREGROUND);
|
||||
boolean scaledForeground = hasHudForegroundPassWork(phase, HudRenderSpace.SCALED)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_SCALED_FOREGROUND);
|
||||
boolean logicalForeground = hasHudForegroundPassWork(phase, HudRenderSpace.UNSCALED_LOGICAL)
|
||||
|| AddonRenderPipelineManager.hasActiveCallbacks(LoVisualRenderStage.HUD_LOGICAL_FOREGROUND);
|
||||
if (!rawMain && !scaledMain && !logicalMain && !rawForeground && !scaledForeground && !logicalForeground) {
|
||||
return false;
|
||||
}
|
||||
|
||||
float tickProgress = TickDelta.tickProgress(tickCounter, false);
|
||||
TextRenderer textRenderer = TextRenderer.get();
|
||||
|
||||
FullScreenRenderer.ensureInit();
|
||||
ViewportContext.beginUnscaled(ctx);
|
||||
refreshHudFrameTiming(tickCounter);
|
||||
|
||||
Renderer2D.withDeferredLayer(layer, () -> {
|
||||
SystemCursor.beginFrame(ctx);
|
||||
try (RenderPhaseScope hudPhase = LoVisualRenderSystem.phase(RenderPhase.HUD_MAIN, "2d:phase:" + phase.name())) {
|
||||
// Raw HUD pass
|
||||
if (rawMain) {
|
||||
Renderer2D.COLOR.begin();
|
||||
ModuleManager.renderHudEngine(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.UNSCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_RAW, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Scaled fixed HUD pass
|
||||
if (scaledMain) {
|
||||
ViewportContext.beginScaled(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.SCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_SCALED, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Logical HUD pass
|
||||
if (logicalMain) {
|
||||
ViewportContext.beginUnscaledLogical(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngine(phase, HudRenderSpace.UNSCALED_LOGICAL, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
DraggableHudElementRegistry.renderAllEngine(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_LOGICAL, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Raw foreground
|
||||
if (rawForeground) {
|
||||
ViewportContext.beginUnscaled(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
ModuleManager.renderHudEngineForeground(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.UNSCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_RAW_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Scaled fixed HUD foreground
|
||||
if (scaledForeground) {
|
||||
ViewportContext.beginScaled(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.SCALED, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_SCALED_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
|
||||
// Logical foreground
|
||||
if (logicalForeground) {
|
||||
ViewportContext.beginUnscaledLogical(ctx);
|
||||
Renderer2D.COLOR.begin();
|
||||
StaticHudElementRegistry.renderAllEngineForeground(phase, HudRenderSpace.UNSCALED_LOGICAL, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
DraggableHudElementRegistry.renderAllEngineForeground(phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
AddonRenderPipelineManager.render2D(LoVisualRenderStage.HUD_LOGICAL_FOREGROUND, phase, Renderer2D.COLOR, textRenderer, ctx, tickProgress);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
} finally {
|
||||
SystemCursor.endFrame();
|
||||
ViewportContext.end(ctx);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void renderHudAfterHotbar(GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
|
||||
if (!Lifecycle.canRunHud()) return;
|
||||
boolean swapTooltipWork = SwapTooltip.hasWork();
|
||||
boolean targetHudWork = DraggableHudElementRegistry.hasEngineWidgetWork("target_hud");
|
||||
if (!swapTooltipWork && !targetHudWork) return;
|
||||
|
||||
float tickProgress = TickDelta.tickProgress(tickCounter, false);
|
||||
TextRenderer textRenderer = TextRenderer.get();
|
||||
Renderer2D.Deferred2DLayer layer = Renderer2D.Deferred2DLayer.HUD_AFTER_MISC_OVERLAYS;
|
||||
|
||||
FullScreenRenderer.ensureInit();
|
||||
ViewportContext.beginUnscaled(ctx);
|
||||
refreshHudFrameTiming(tickCounter);
|
||||
|
||||
Renderer2D.withDeferredLayer(layer, () -> {
|
||||
SystemCursor.beginFrame(ctx);
|
||||
try (RenderPhaseScope hudPhase = LoVisualRenderSystem.phase(RenderPhase.HUD_EFFECTS, "2d:after_hotbar")) {
|
||||
// Raw pass
|
||||
if (swapTooltipWork) {
|
||||
try (ProfilerPhase.Scope tooltipsScope = ProfilerPhase.scope("2d:after_hotbar:swap_tooltip");
|
||||
RenderProfiler2D.Section ignoredTooltips = RenderProfiler2D.section("swap_tooltip")) {
|
||||
Renderer2D.COLOR.begin();
|
||||
SwapTooltip.render();
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
}
|
||||
|
||||
// Logical pass
|
||||
if (targetHudWork) {
|
||||
ViewportContext.beginUnscaledLogical(ctx);
|
||||
try (ProfilerPhase.Scope targetHudScope = ProfilerPhase.scope("2d:after_hotbar:target_hud");
|
||||
RenderProfiler2D.Section ignoredTargetHud = RenderProfiler2D.section("target_hud")) {
|
||||
Renderer2D.COLOR.begin();
|
||||
DraggableHudElementRegistry.renderEngineWidget(
|
||||
"target_hud",
|
||||
Renderer2D.COLOR,
|
||||
textRenderer,
|
||||
ctx,
|
||||
tickProgress
|
||||
);
|
||||
Renderer2D.COLOR.render();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
SystemCursor.endFrame();
|
||||
ViewportContext.end(ctx);
|
||||
}
|
||||
});
|
||||
appendHudDeferredMarker(layer, ctx);
|
||||
}
|
||||
|
||||
private static void appendHudDeferredMarker(Renderer2D.Deferred2DLayer layer, GuiGraphicsExtractor ctx) {
|
||||
if (!(ctx instanceof IGuiGraphics graphics)) return;
|
||||
ctx.nextStratum();
|
||||
graphics.lovisual$addDeferredHudMarker(layer);
|
||||
ctx.nextStratum();
|
||||
}
|
||||
|
||||
private static Renderer2D.Deferred2DLayer deferredLayerForHudPhase(HudPhase phase) {
|
||||
if (phase == null) return Renderer2D.Deferred2DLayer.BEFORE_VANILLA_GUI;
|
||||
return switch (phase) {
|
||||
case NONE -> Renderer2D.Deferred2DLayer.BEFORE_VANILLA_GUI;
|
||||
case FIRST -> Renderer2D.Deferred2DLayer.HUD_FIRST;
|
||||
case BEFORE_MISC_OVERLAYS -> Renderer2D.Deferred2DLayer.HUD_BEFORE_MISC_OVERLAYS;
|
||||
case AFTER_MISC_OVERLAYS -> Renderer2D.Deferred2DLayer.HUD_AFTER_MISC_OVERLAYS;
|
||||
case AFTER_BOSS_BAR -> Renderer2D.Deferred2DLayer.HUD_AFTER_BOSS_BAR;
|
||||
case BEFORE_DEMO_TIMER -> Renderer2D.Deferred2DLayer.HUD_BEFORE_DEMO_TIMER;
|
||||
case BEFORE_CHAT -> Renderer2D.Deferred2DLayer.HUD_BEFORE_CHAT;
|
||||
case AFTER_SUBTITLES -> Renderer2D.Deferred2DLayer.HUD_AFTER_SUBTITLES;
|
||||
case LAST -> Renderer2D.Deferred2DLayer.HUD_LAST;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean hasHudMainPassWork(HudPhase phase, HudRenderSpace space) {
|
||||
boolean moduleWork = space == HudRenderSpace.UNSCALED && ModuleManager.hasHudEngineWork(phase);
|
||||
boolean staticWork = StaticHudElementRegistry.hasEngineWork(phase, space, false);
|
||||
boolean draggableWork = space == HudRenderSpace.UNSCALED_LOGICAL && DraggableHudElementRegistry.hasEngineWork(phase, false);
|
||||
return moduleWork || staticWork || draggableWork;
|
||||
}
|
||||
|
||||
private static boolean hasHudForegroundPassWork(HudPhase phase, HudRenderSpace space) {
|
||||
boolean moduleWork = space == HudRenderSpace.UNSCALED && ModuleManager.hasHudEngineForegroundWork(phase);
|
||||
boolean staticWork = StaticHudElementRegistry.hasEngineWork(phase, space, true);
|
||||
boolean draggableWork = space == HudRenderSpace.UNSCALED_LOGICAL && DraggableHudElementRegistry.hasEngineWork(phase, true);
|
||||
return moduleWork || staticWork || draggableWork;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
LoVisualRenderEngineBootstrap.init();
|
||||
PostProcessManager.register(new NetherPortalRiftPass());
|
||||
PostProcessManager.register(new SleepOverlayPass());
|
||||
MainConfig.get(); // Load global settings (debug flag)
|
||||
AccountConfig.get();
|
||||
ProxyBackend.init();
|
||||
CommandManager.init();
|
||||
MediaSessionService.get().init();
|
||||
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> MediaSessionService.get().shutdown());
|
||||
|
||||
// -------- CONFIG + BINDS ----------
|
||||
// Enabled addons declare built-in module exclusions before auto-discovery.
|
||||
AddonManager.prepareModuleLoading();
|
||||
ModuleAutoLoader.load("dev.loki.lovisual.features.module.modules");
|
||||
AddonManager.init();
|
||||
// Initialize modules' enabled state and settings from new config system
|
||||
ModuleManager.loadAllModuleConfigs();
|
||||
AddonManager.notifyClientReady();
|
||||
// Key binds are restored via Module config (KeyBindSetting) in ModuleManager.loadAllModuleConfigs()
|
||||
HudElements.init(); // init HUD config + widgets
|
||||
StaticHudElementBootstrap.init(); // init vanilla HUD elements config
|
||||
Events.BUS.register(I18nPreflightContributors.INSTANCE);
|
||||
Events.BUS.register(RenderPrewarmContributors.INSTANCE);
|
||||
Events.BUS.register(RotationManager.INSTANCE);
|
||||
Events.BUS.register(AttackPressing.INSTANCE);
|
||||
Events.BUS.register(SprintController.INSTANCE);
|
||||
Events.BUS.register(AntiBotTracker.INSTANCE);
|
||||
Events.BUS.register(CombatProtocolHeuristics.INSTANCE);
|
||||
Events.BUS.register(PvpTracker.INSTANCE);
|
||||
Events.BUS.register(PvpTargetTracker.INSTANCE);
|
||||
Events.BUS.register(SelfBedTracker.INSTANCE);
|
||||
Events.BUS.register(BoatSimulationCache.INSTANCE);
|
||||
Events.BUS.register(PlayerSimulationCache.INSTANCE);
|
||||
Events.BUS.register(BlinkManager.INSTANCE);
|
||||
Events.BUS.register(FakeLagController.INSTANCE);
|
||||
Events.BUS.register(BacktrackController.INSTANCE);
|
||||
Events.BUS.register(TimerController.INSTANCE);
|
||||
|
||||
// -------- КЛЮЧЕВЫЕ ИВЕНТЫ --------
|
||||
|
||||
// === ТИКИ ===
|
||||
|
||||
ClientTickEvents.START_CLIENT_TICK.register(client -> {
|
||||
if (client.player == null) return;
|
||||
if (!Lifecycle.isActive()) return;
|
||||
Events.BUS.post(new GameTickEvent());
|
||||
});
|
||||
|
||||
ClientTickEvents.END_CLIENT_TICK.register(client -> {
|
||||
if (!Lifecycle.isActive()) return;
|
||||
|
||||
if (!ClickGuiRenderer.isBlockingModuleKeybinds()) {
|
||||
ModuleManager.handleModuleKeybinds();
|
||||
}
|
||||
TargetManager.tick();
|
||||
ModuleManager.tickAll();
|
||||
DraggableHudElementRegistry.tickAll();
|
||||
StaticHudElementRegistry.tickAll();
|
||||
});
|
||||
|
||||
/* ====================== WORLD RENDER ====================== */
|
||||
|
||||
LevelRenderEvents.COLLECT_SUBMITS.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.BEFORE_ENTITIES,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
LevelRenderEvents.AFTER_SOLID_FEATURES.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.AFTER_ENTITIES,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
LevelRenderEvents.BEFORE_TRANSLUCENT_TERRAIN.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.BEFORE_TRANSLUCENT,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
LevelRenderEvents.END_MAIN.register(ctx -> renderWorldPhase(
|
||||
WorldPhase.END_MAIN,
|
||||
ctx.poseStack(),
|
||||
ctx.submitNodeCollector()
|
||||
));
|
||||
|
||||
// === HUD 2D OVERLAYS ===
|
||||
|
||||
HudElementRegistry.addFirst(
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_first"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.FIRST, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.addLast(
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_last"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.LAST, ctx, tc)
|
||||
);
|
||||
|
||||
// остальные позиции HUD:
|
||||
HudElementRegistry.attachElementBefore(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.MISC_OVERLAYS,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_before_misc"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_MISC_OVERLAYS, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.MISC_OVERLAYS,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_misc"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_MISC_OVERLAYS, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.SLEEP,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_boss"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_BOSS_BAR, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementBefore(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.DEMO_TIMER,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_before_demo"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_DEMO_TIMER, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementBefore(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.CHAT,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_before_chat"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.BEFORE_CHAT, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
net.fabricmc.fabric.api.client.rendering.v1.hud.VanillaHudElements.SUBTITLES,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_subtitles"),
|
||||
(ctx, tc) -> renderHudPhase(HudPhase.AFTER_SUBTITLES, ctx, tc)
|
||||
);
|
||||
|
||||
HudElementRegistry.attachElementAfter(
|
||||
VanillaHudElements.HOTBAR,
|
||||
Identifier.fromNamespaceAndPath("lovisual", "hud_after_hotbar"),
|
||||
(ctx, tc) -> renderHudAfterHotbar(ctx, tc)
|
||||
);
|
||||
|
||||
Lifecycle.activate();
|
||||
RenderPrewarmManager.prewarm("client initialized");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddonContext;
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
|
||||
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
|
||||
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderCallback;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import dev.loki.lovisual.features.command.util.ClientCommand;
|
||||
import dev.loki.lovisual.features.command.core.CommandManager;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import dev.loki.lovisual.render.iris.patch.ShaderPatchEngine;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.ModContainer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
import dev.loki.lovisual.addon.core.AddonRegistration;
|
||||
import dev.loki.lovisual.addon.manager.ClickGuiSectionManager;
|
||||
import dev.loki.lovisual.addon.manager.ModuleExtensionManager;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonRenderPipelineManager;
|
||||
import dev.loki.lovisual.features.module.modules.misc.ClickGui;
|
||||
|
||||
public final class LoVisualAddonContextImpl implements LoVisualAddonContext {
|
||||
private final AddonRegistration registration;
|
||||
|
||||
public LoVisualAddonContextImpl(AddonRegistration registration) {
|
||||
|
||||
this.registration = registration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return registration.descriptor.id();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoVisualClientApi client() {
|
||||
return LoVisualClientApi.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModContainer modContainer() {
|
||||
return registration.entrypoint.getProvider();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path gameDir() {
|
||||
return FabricLoader.getInstance().getGameDir();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path configDir() {
|
||||
return FabricLoader.getInstance().getConfigDir();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path addonConfigDir() {
|
||||
return configDir().resolve("lovisual").resolve("addons").resolve(addonId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerModule(Module module) {
|
||||
if (module == null) return;
|
||||
module.postInit();
|
||||
registration.modules.add(module.name());
|
||||
AddonManager.noteModuleOwner(addonId(), module.name());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerDraggableHudElement(DraggableHudElement element) {
|
||||
if (element == null) return;
|
||||
DraggableHudElementRegistry.register(element);
|
||||
registration.draggableHudElements.add(element.getId());
|
||||
AddonManager.noteDraggableHudOwner(addonId(), element.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStaticHudElement(AbstractHudElement element) {
|
||||
if (element == null) return;
|
||||
StaticHudElementRegistry.register(element);
|
||||
registration.staticHudElements.add(element.getId());
|
||||
AddonManager.noteStaticHudOwner(addonId(), element.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerCommand(ClientCommand command) {
|
||||
if (command == null) return;
|
||||
CommandManager.register(new AddonClientCommand(addonId(), command));
|
||||
registration.commands.add(command.metadata().id());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerClickGuiSection(String sectionId, String label, LoVisualClickGuiSection section) {
|
||||
if (ClickGuiSectionManager.register(addonId(), sectionId, label, section)) {
|
||||
registration.clickGuiSections.add(sectionId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "ClickGui section registration failed", sectionId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerModuleExtension(String moduleId, LoVisualModuleExtension extension) {
|
||||
if (ModuleExtensionManager.register(addonId(), moduleId, extension)) {
|
||||
registration.moduleExtensions.add(moduleId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Module extension target is unavailable", moduleId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerIrisShaderPatchManifest(String manifestResourcePath) {
|
||||
if (ShaderPatchEngine.registerManifestResource(manifestResourcePath)) {
|
||||
registration.irisPatchManifests.add(manifestResourcePath);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Iris patch manifest registration failed", manifestResourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerRenderCallback(String callbackId, LoVisualRenderStage stage, LoVisualRenderCallback callback) {
|
||||
if (AddonRenderPipelineManager.register(addonId(), callbackId, stage, callback)) {
|
||||
registration.renderCallbacks.add(stage.name().toLowerCase(java.util.Locale.ROOT) + ":" + callbackId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Render callback registration failed", callbackId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerPostProcessPass(String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
int priority,
|
||||
LoVisualPostProcessCallback callback) {
|
||||
if (AddonRenderPipelineManager.registerPostProcess(addonId(), passId, phase, priority, callback)) {
|
||||
registration.postProcessPasses.add(phase.name().toLowerCase(java.util.Locale.ROOT) + ":" + passId);
|
||||
} else {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Post-process registration failed", passId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RenderPipeline registerRenderPipeline(RenderPipeline pipeline) {
|
||||
if (pipeline == null) return null;
|
||||
RenderPipeline registered = LoVisualRenderPipelines.registerAddonPipeline(pipeline);
|
||||
registration.renderCallbacks.add("pipeline:" + pipeline.getLocation());
|
||||
return registered;
|
||||
}
|
||||
|
||||
private record AddonClientCommand(String addonId, ClientCommand delegate) implements ClientCommand {
|
||||
@Override
|
||||
public dev.loki.lovisual.features.command.core.CommandMetadata metadata() {
|
||||
return delegate.metadata();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public String name() {
|
||||
return delegate.name();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public java.util.List<String> aliases() {
|
||||
return delegate.aliases();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public String usage() {
|
||||
return delegate.usage();
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true)
|
||||
@Override
|
||||
@SuppressWarnings("removal")
|
||||
public String description() {
|
||||
return delegate.description();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return AddonManager.isActive(addonId) && delegate.isAvailable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<String> suggest(dev.loki.lovisual.features.command.core.CommandContext ctx, int argIndex, String token) {
|
||||
return delegate.suggest(ctx, argIndex, token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(dev.loki.lovisual.features.command.core.CommandContext ctx) {
|
||||
return isAvailable() && delegate.execute(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddonRuntimeContext;
|
||||
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
|
||||
|
||||
public final class LoVisualAddonRuntimeContextImpl implements LoVisualAddonRuntimeContext {
|
||||
private final String addonId;
|
||||
|
||||
public LoVisualAddonRuntimeContextImpl(String addonId) {
|
||||
|
||||
this.addonId = addonId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return addonId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LoVisualClientApi client() {
|
||||
return LoVisualClientApi.get();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualModuleLoadContext;
|
||||
import dev.loki.lovisual.features.module.lifecycle.ModuleAutoLoader;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.core.AddonRegistration;
|
||||
|
||||
public final class LoVisualModuleLoadContextImpl implements LoVisualModuleLoadContext {
|
||||
private final AddonRegistration registration;
|
||||
private final List<String> pendingExclusions = new ArrayList<>();
|
||||
|
||||
public LoVisualModuleLoadContextImpl(AddonRegistration registration) {
|
||||
|
||||
this.registration = registration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return registration.descriptor.id();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean disableBuiltInModule(String moduleReference) {
|
||||
String reference = moduleReference == null ? "" : moduleReference.trim();
|
||||
if (reference.isEmpty()) return false;
|
||||
|
||||
if (!ModuleAutoLoader.acceptsDisableRequests()) {
|
||||
noteRestartRequired(reference);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!pendingExclusions.contains(reference)) {
|
||||
pendingExclusions.add(reference);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
|
||||
for (String reference : pendingExclusions) {
|
||||
if (!registration.disabledBuiltInModules.contains(reference)) {
|
||||
registration.disabledBuiltInModules.add(reference);
|
||||
}
|
||||
if (!ModuleAutoLoader.requestDisable(reference, addonId())) {
|
||||
noteRestartRequired(reference);
|
||||
}
|
||||
}
|
||||
pendingExclusions.clear();
|
||||
}
|
||||
|
||||
private void noteRestartRequired(String reference) {
|
||||
if (!registration.disabledBuiltInModules.contains(reference)) {
|
||||
registration.disabledBuiltInModules.add(reference);
|
||||
}
|
||||
registration.restartRequired = true;
|
||||
registration.issue(
|
||||
AddonIssue.Severity.WARNING,
|
||||
"Built-in module exclusion requires restart",
|
||||
reference
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.context;
|
||||
|
||||
import dev.loki.lovisual.api.v0.module.ModuleExtensionContext;
|
||||
import dev.loki.lovisual.config.definition.SettingDef;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.mode.ModeValue;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
public final class ModuleExtensionContextImpl implements ModuleExtensionContext {
|
||||
private final String addonId;
|
||||
private final Module module;
|
||||
|
||||
public ModuleExtensionContextImpl(String addonId, Module module) {
|
||||
|
||||
this.addonId = addonId;
|
||||
this.module = module;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String addonId() {
|
||||
return addonId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String moduleId() {
|
||||
return module.name();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Module module() {
|
||||
return module;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addSetting(SettingDef setting) {
|
||||
module.addExtensionSetting(setting);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ConfigValue<?> getConfigValue(String configName) {
|
||||
return module.getConfigValue(configName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addModeOption(String configName, String option) {
|
||||
ConfigValue<?> value = getConfigValue(configName);
|
||||
return value instanceof ModeValue mode && mode.addOption(option);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AddonDescriptor(
|
||||
String id,
|
||||
String name,
|
||||
String version,
|
||||
String description,
|
||||
List<String> authors,
|
||||
String iconPath,
|
||||
int apiVersion,
|
||||
String entrypointDefinition
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
public record AddonIssue(
|
||||
String addonId,
|
||||
Severity severity,
|
||||
String message,
|
||||
String detail
|
||||
) {
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARNING,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
486
mod/src/main/java/dev/loki/lovisual/addon/core/AddonManager.java
Normal file
486
mod/src/main/java/dev/loki/lovisual/addon/core/AddonManager.java
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.lifecycle.ModuleAutoLoader;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.api.metadata.CustomValue;
|
||||
import net.fabricmc.loader.api.metadata.ModMetadata;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.context.LoVisualAddonContextImpl;
|
||||
import dev.loki.lovisual.addon.context.LoVisualAddonRuntimeContextImpl;
|
||||
import dev.loki.lovisual.addon.context.LoVisualModuleLoadContextImpl;
|
||||
import dev.loki.lovisual.addon.core.AddonDescriptor;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.core.AddonRegistration;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonSnapshot;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStateStore;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStatus;
|
||||
|
||||
public enum AddonManager {
|
||||
;
|
||||
|
||||
public static final String ADDON_METADATA_KEY = "lovisual:addon";
|
||||
|
||||
private static final Map<String, AddonRegistration> ADDONS = new LinkedHashMap<>();
|
||||
private static final Map<String, Boolean> ENABLED_OVERRIDES = new LinkedHashMap<>();
|
||||
private static final Map<String, String> MODULE_OWNERS = new LinkedHashMap<>();
|
||||
private static final Map<String, String> DRAGGABLE_HUD_OWNERS = new LinkedHashMap<>();
|
||||
private static final Map<String, String> STATIC_HUD_OWNERS = new LinkedHashMap<>();
|
||||
private static boolean discovered;
|
||||
private static boolean moduleLoadingPrepared;
|
||||
private static boolean initialized;
|
||||
private static boolean clientReady;
|
||||
|
||||
/**
|
||||
* Discovers enabled addon entrypoints and lets them configure built-in module
|
||||
* exclusions before {@code ModuleAutoLoader} starts instantiating modules.
|
||||
*/
|
||||
public static void prepareModuleLoading() {
|
||||
ensureDiscovered();
|
||||
if (moduleLoadingPrepared) return;
|
||||
moduleLoadingPrepared = true;
|
||||
configureEnabledAddons();
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
if (initialized) return;
|
||||
prepareModuleLoading();
|
||||
if (!ModuleAutoLoader.isDiscoveryFinished()) {
|
||||
return;
|
||||
}
|
||||
reconcileModuleExclusions();
|
||||
initialized = true;
|
||||
initializeEnabledAddons();
|
||||
}
|
||||
|
||||
/**
|
||||
* Completes addon startup after module configs have been loaded and applied.
|
||||
*/
|
||||
public static void notifyClientReady() {
|
||||
init();
|
||||
if (!initialized) return;
|
||||
clientReady = true;
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
notifyClientReady(registration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureDiscovered() {
|
||||
if (discovered) return;
|
||||
discovered = true;
|
||||
ENABLED_OVERRIDES.clear();
|
||||
ENABLED_OVERRIDES.putAll(AddonStateStore.loadEnabledOverrides());
|
||||
discoverEntrypoints();
|
||||
}
|
||||
|
||||
public static List<AddonSnapshot> snapshots() {
|
||||
init();
|
||||
return ADDONS.values().stream()
|
||||
.map(AddonRegistration::snapshot)
|
||||
.sorted(Comparator.comparing(AddonSnapshot::name, String.CASE_INSENSITIVE_ORDER))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static AddonSnapshot snapshot(String id) {
|
||||
init();
|
||||
AddonRegistration registration = ADDONS.get(normalizeId(id));
|
||||
return registration == null ? null : registration.snapshot();
|
||||
}
|
||||
|
||||
public static boolean isActive(String id) {
|
||||
init();
|
||||
AddonRegistration registration = ADDONS.get(normalizeId(id));
|
||||
return registration != null && registration.enabled && registration.status == AddonStatus.ACTIVE;
|
||||
}
|
||||
|
||||
public static List<AddonIssue> scan() {
|
||||
init();
|
||||
List<AddonIssue> out = new ArrayList<>();
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
validateRegistration(registration);
|
||||
out.addAll(registration.issues);
|
||||
}
|
||||
if (out.isEmpty()) {
|
||||
out.add(new AddonIssue("lovisual", AddonIssue.Severity.INFO, "No addon errors found", ""));
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
public static String moduleProfileOwnerId(String moduleId) {
|
||||
String addonId = MODULE_OWNERS.get(normalizeId(moduleId));
|
||||
return addonId == null ? "module:" + moduleId : "addon:" + addonId + ":module:" + moduleId;
|
||||
}
|
||||
|
||||
public static String draggableHudProfileOwnerId(String elementId) {
|
||||
String addonId = DRAGGABLE_HUD_OWNERS.get(normalizeId(elementId));
|
||||
return addonId == null ? "hud.draggable:" + elementId : "addon:" + addonId + ":hud.draggable:" + elementId;
|
||||
}
|
||||
|
||||
public static String staticHudProfileOwnerId(String elementId) {
|
||||
String addonId = STATIC_HUD_OWNERS.get(normalizeId(elementId));
|
||||
return addonId == null ? "hud.static:" + elementId : "addon:" + addonId + ":hud.static:" + elementId;
|
||||
}
|
||||
|
||||
public static String profileDisplayName(String ownerId, String displayName) {
|
||||
String addonId = addonIdFromProfileOwner(ownerId);
|
||||
if (addonId == null) return displayName;
|
||||
AddonRegistration registration = ADDONS.get(addonId);
|
||||
String addonName = registration == null ? addonId : registration.descriptor.name();
|
||||
return addonName + " / " + displayName;
|
||||
}
|
||||
|
||||
public static String addonIdFromProfileOwner(String ownerId) {
|
||||
if (ownerId == null || !ownerId.startsWith("addon:")) return null;
|
||||
int start = "addon:".length();
|
||||
int end = ownerId.indexOf(':', start);
|
||||
if (end <= start) return null;
|
||||
return normalizeId(ownerId.substring(start, end));
|
||||
}
|
||||
|
||||
public static boolean setEnabled(String id, boolean enabled) {
|
||||
init();
|
||||
String normalizedId = normalizeId(id);
|
||||
AddonRegistration registration = ADDONS.get(normalizedId);
|
||||
if (registration == null) return false;
|
||||
if (registration.enabled == enabled) return true;
|
||||
|
||||
registration.enabled = enabled;
|
||||
registration.restartRequired = false;
|
||||
ENABLED_OVERRIDES.put(normalizedId, enabled);
|
||||
AddonStateStore.saveEnabledOverrides(ENABLED_OVERRIDES);
|
||||
|
||||
if (enabled) {
|
||||
if (!registration.moduleConfigurationApplied) {
|
||||
configureAddonModules(registration);
|
||||
}
|
||||
if (!registration.initialized) {
|
||||
initializeAddon(registration);
|
||||
} else {
|
||||
resumeRuntimeContributions(registration);
|
||||
resumeAddon(registration, "enabled by user");
|
||||
if (registration.status != AddonStatus.ERROR) {
|
||||
registration.status = AddonStatus.ACTIVE;
|
||||
}
|
||||
}
|
||||
if (clientReady) {
|
||||
notifyClientReady(registration);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
registration.restartRequired = !registration.disabledBuiltInModules.isEmpty();
|
||||
if (!registration.initialized) {
|
||||
registration.status = AddonStatus.DISABLED;
|
||||
return true;
|
||||
}
|
||||
|
||||
suspendRuntimeContributions(registration);
|
||||
suspendAddon(registration, "disabled by user");
|
||||
registration.status = AddonStatus.DISABLED;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int activeCount() {
|
||||
int count = 0;
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.status == AddonStatus.ACTIVE) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void discoverEntrypoints() {
|
||||
for (var entrypoint : FabricLoader.getInstance()
|
||||
.getEntrypointContainers(LoVisualAddon.ENTRYPOINT_KEY, LoVisualAddon.class)) {
|
||||
ModMetadata metadata = entrypoint.getProvider().getMetadata();
|
||||
String id = normalizeId(metadata.getId());
|
||||
AddonDescriptor descriptor = descriptor(metadata, entrypoint.getDefinition());
|
||||
boolean enabled = ENABLED_OVERRIDES.getOrDefault(id, true);
|
||||
AddonStatus status = enabled ? AddonStatus.DISCOVERED : AddonStatus.DISABLED;
|
||||
AddonRegistration duplicate = ADDONS.get(id);
|
||||
if (duplicate != null) {
|
||||
duplicate.issue(AddonIssue.Severity.ERROR, "Duplicate addon id", metadata.getId());
|
||||
continue;
|
||||
}
|
||||
AddonRegistration registration = new AddonRegistration(descriptor, entrypoint, enabled, status);
|
||||
validateRegistration(registration);
|
||||
ADDONS.put(id, registration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void configureEnabledAddons() {
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.enabled) {
|
||||
configureAddonModules(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void configureAddonModules(AddonRegistration registration) {
|
||||
if (registration.moduleConfigurationApplied || !registration.enabled || registration.status == AddonStatus.ERROR) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
LoVisualAddon addon = addonInstance(registration);
|
||||
LoVisualModuleLoadContextImpl context = new LoVisualModuleLoadContextImpl(registration);
|
||||
addon.onConfigureModules(context);
|
||||
context.commit();
|
||||
registration.moduleConfigurationApplied = true;
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Module configuration failed", t.toString());
|
||||
DebugLog.error("Addon module configuration failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void reconcileModuleExclusions() {
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.disabledBuiltInModules.isEmpty()) continue;
|
||||
registration.disabledBuiltInModules.removeIf(reference -> {
|
||||
if (ModuleAutoLoader.wasDisableRequestMatched(reference, registration.descriptor.id())) {
|
||||
return false;
|
||||
}
|
||||
registration.issue(
|
||||
AddonIssue.Severity.WARNING,
|
||||
"Built-in module exclusion target was not found",
|
||||
reference
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static void initializeEnabledAddons() {
|
||||
for (AddonRegistration registration : ADDONS.values()) {
|
||||
if (registration.enabled && registration.status != AddonStatus.ERROR) {
|
||||
initializeAddon(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void initializeAddon(AddonRegistration registration) {
|
||||
if (registration.initialized || !registration.enabled || registration.status == AddonStatus.ERROR) return;
|
||||
if (!registration.moduleConfigurationApplied) {
|
||||
configureAddonModules(registration);
|
||||
if (registration.status == AddonStatus.ERROR) return;
|
||||
}
|
||||
try {
|
||||
LoVisualAddon addon = addonInstance(registration);
|
||||
addon.onInitialize(new LoVisualAddonContextImpl(registration));
|
||||
registration.initialized = true;
|
||||
registration.status = AddonStatus.ACTIVE;
|
||||
DebugLog.info("Addon initialized: %s", registration.descriptor.id());
|
||||
if (clientReady) {
|
||||
notifyClientReady(registration);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Initialization failed", t.toString());
|
||||
DebugLog.error("Addon initialization failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void notifyClientReady(AddonRegistration registration) {
|
||||
if (registration == null
|
||||
|| registration.clientReadyNotified
|
||||
|| !registration.initialized
|
||||
|| !registration.enabled
|
||||
|| registration.status != AddonStatus.ACTIVE) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
registration.addon.onClientReady(
|
||||
new LoVisualAddonRuntimeContextImpl(registration.descriptor.id())
|
||||
);
|
||||
registration.clientReadyNotified = true;
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Client ready callback failed", t.toString());
|
||||
DebugLog.error("Addon client ready callback failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static LoVisualAddon addonInstance(AddonRegistration registration) {
|
||||
LoVisualAddon addon = registration.addon;
|
||||
if (addon == null) {
|
||||
addon = registration.entrypoint.getEntrypoint();
|
||||
registration.addon = addon;
|
||||
}
|
||||
return addon;
|
||||
}
|
||||
|
||||
private static void suspendAddon(AddonRegistration registration, String reason) {
|
||||
if (registration.addon == null) return;
|
||||
try {
|
||||
registration.addon.onRuntimeSuspended(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Runtime suspend failed", t.toString());
|
||||
DebugLog.error("Addon runtime suspend failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void resumeAddon(AddonRegistration registration, String reason) {
|
||||
if (registration.addon == null) return;
|
||||
try {
|
||||
registration.addon.onRuntimeResumed(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
|
||||
} catch (Throwable t) {
|
||||
registration.status = AddonStatus.ERROR;
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Runtime resume failed", t.toString());
|
||||
DebugLog.error("Addon runtime resume failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void shutdownAddon(AddonRegistration registration, String reason) {
|
||||
if (registration.addon == null) return;
|
||||
try {
|
||||
registration.addon.onShutdown(new LoVisualAddonRuntimeContextImpl(registration.descriptor.id()));
|
||||
} catch (Throwable t) {
|
||||
registration.issue(AddonIssue.Severity.ERROR, "Shutdown failed", t.toString());
|
||||
DebugLog.error("Addon shutdown failed: %s", t, registration.descriptor.id());
|
||||
}
|
||||
}
|
||||
|
||||
private static void suspendRuntimeContributions(AddonRegistration registration) {
|
||||
registration.suspendedModules.clear();
|
||||
registration.suspendedDraggableHudElements.clear();
|
||||
registration.suspendedStaticHudElements.clear();
|
||||
for (String id : registration.modules) {
|
||||
Module module = ModuleManager.get(id);
|
||||
if (module != null) {
|
||||
registration.suspendedModules.put(id, module.isEnabled());
|
||||
ModuleManager.setRuntimeEnabledTransient(id, false);
|
||||
}
|
||||
}
|
||||
for (String id : registration.draggableHudElements) {
|
||||
DraggableHudElement element = DraggableHudElementRegistry.getById(id);
|
||||
if (element != null) {
|
||||
registration.suspendedDraggableHudElements.put(id, element.isEnabled());
|
||||
element.setRuntimeEnabledTransient(false);
|
||||
}
|
||||
}
|
||||
for (String id : registration.staticHudElements) {
|
||||
AbstractHudElement element = StaticHudElementRegistry.getById(id);
|
||||
if (element != null) {
|
||||
registration.suspendedStaticHudElements.put(id, element.isEnabled());
|
||||
element.setRuntimeEnabledTransient(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void resumeRuntimeContributions(AddonRegistration registration) {
|
||||
for (String id : registration.modules) {
|
||||
Boolean enabled = registration.suspendedModules.get(id);
|
||||
if (enabled != null) {
|
||||
ModuleManager.setRuntimeEnabledTransient(id, enabled);
|
||||
}
|
||||
}
|
||||
for (String id : registration.draggableHudElements) {
|
||||
Boolean enabled = registration.suspendedDraggableHudElements.get(id);
|
||||
DraggableHudElement element = DraggableHudElementRegistry.getById(id);
|
||||
if (enabled != null && element != null) {
|
||||
element.setRuntimeEnabledTransient(enabled);
|
||||
}
|
||||
}
|
||||
for (String id : registration.staticHudElements) {
|
||||
Boolean enabled = registration.suspendedStaticHudElements.get(id);
|
||||
AbstractHudElement element = StaticHudElementRegistry.getById(id);
|
||||
if (enabled != null && element != null) {
|
||||
element.setRuntimeEnabledTransient(enabled);
|
||||
}
|
||||
}
|
||||
registration.suspendedModules.clear();
|
||||
registration.suspendedDraggableHudElements.clear();
|
||||
registration.suspendedStaticHudElements.clear();
|
||||
}
|
||||
|
||||
public static void noteModuleOwner(String addonId, String moduleId) {
|
||||
|
||||
if (moduleId != null && !moduleId.isBlank()) {
|
||||
MODULE_OWNERS.put(normalizeId(moduleId), normalizeId(addonId));
|
||||
}
|
||||
}
|
||||
|
||||
public static void noteDraggableHudOwner(String addonId, String elementId) {
|
||||
|
||||
if (elementId != null && !elementId.isBlank()) {
|
||||
DRAGGABLE_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
|
||||
}
|
||||
}
|
||||
|
||||
public static void noteStaticHudOwner(String addonId, String elementId) {
|
||||
|
||||
if (elementId != null && !elementId.isBlank()) {
|
||||
STATIC_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateRegistration(AddonRegistration registration) {
|
||||
if (registration.descriptor.apiVersion() != LoVisualAddon.API_VERSION) {
|
||||
registration.issue(
|
||||
AddonIssue.Severity.WARNING,
|
||||
"Addon API version differs from client API",
|
||||
"addon=" + registration.descriptor.apiVersion() + ", client=" + LoVisualAddon.API_VERSION
|
||||
);
|
||||
}
|
||||
if (registration.descriptor.iconPath() == null || registration.descriptor.iconPath().isBlank()) {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Addon icon is missing", "Add icon in fabric.mod.json");
|
||||
}
|
||||
if (registration.descriptor.entrypointDefinition() == null
|
||||
|| registration.descriptor.entrypointDefinition().isBlank()) {
|
||||
registration.issue(AddonIssue.Severity.WARNING, "Entrypoint definition is unavailable", "");
|
||||
}
|
||||
}
|
||||
|
||||
private static AddonDescriptor descriptor(ModMetadata metadata, String entrypointDefinition) {
|
||||
List<String> authors = metadata.getAuthors().stream()
|
||||
.map(person -> person.getName() == null ? "" : person.getName())
|
||||
.filter(name -> !name.isBlank())
|
||||
.toList();
|
||||
return new AddonDescriptor(
|
||||
normalizeId(metadata.getId()),
|
||||
blankFallback(metadata.getName(), metadata.getId()),
|
||||
String.valueOf(metadata.getVersion()),
|
||||
metadata.getDescription() == null ? "" : metadata.getDescription(),
|
||||
authors,
|
||||
metadata.getIconPath(64).or(() -> metadata.getIconPath(32)).orElse(""),
|
||||
apiVersion(metadata),
|
||||
entrypointDefinition
|
||||
);
|
||||
}
|
||||
|
||||
private static int apiVersion(ModMetadata metadata) {
|
||||
CustomValue value = metadata.getCustomValue(ADDON_METADATA_KEY);
|
||||
if (value == null || value.getType() != CustomValue.CvType.OBJECT) return LoVisualAddon.API_VERSION;
|
||||
CustomValue api = value.getAsObject().get("api");
|
||||
if (api == null || api.getType() != CustomValue.CvType.NUMBER) return LoVisualAddon.API_VERSION;
|
||||
return api.getAsNumber().intValue();
|
||||
}
|
||||
|
||||
private static String blankFallback(String value, String fallback) {
|
||||
return value == null || value.isBlank() ? fallback : value;
|
||||
}
|
||||
|
||||
private static String normalizeId(String id) {
|
||||
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.core;
|
||||
|
||||
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
|
||||
import net.fabricmc.loader.api.entrypoint.EntrypointContainer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.core.AddonDescriptor;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonSnapshot;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStatus;
|
||||
|
||||
public final class AddonRegistration {
|
||||
public final AddonDescriptor descriptor;
|
||||
|
||||
public final EntrypointContainer<LoVisualAddon> entrypoint;
|
||||
|
||||
public final List<String> modules = new ArrayList<>();
|
||||
|
||||
public final List<String> disabledBuiltInModules = new ArrayList<>();
|
||||
|
||||
public final List<String> draggableHudElements = new ArrayList<>();
|
||||
|
||||
public final List<String> staticHudElements = new ArrayList<>();
|
||||
|
||||
public final List<String> commands = new ArrayList<>();
|
||||
|
||||
public final List<String> clickGuiSections = new ArrayList<>();
|
||||
|
||||
public final List<String> moduleExtensions = new ArrayList<>();
|
||||
|
||||
public final List<String> irisPatchManifests = new ArrayList<>();
|
||||
|
||||
public final List<String> renderCallbacks = new ArrayList<>();
|
||||
|
||||
public final List<String> postProcessPasses = new ArrayList<>();
|
||||
|
||||
final List<AddonIssue> issues = new ArrayList<>();
|
||||
final Map<String, Boolean> suspendedModules = new LinkedHashMap<>();
|
||||
final Map<String, Boolean> suspendedDraggableHudElements = new LinkedHashMap<>();
|
||||
final Map<String, Boolean> suspendedStaticHudElements = new LinkedHashMap<>();
|
||||
LoVisualAddon addon;
|
||||
boolean moduleConfigurationApplied;
|
||||
boolean initialized;
|
||||
boolean clientReadyNotified;
|
||||
AddonStatus status;
|
||||
boolean enabled;
|
||||
public boolean restartRequired;
|
||||
|
||||
|
||||
AddonRegistration(AddonDescriptor descriptor,
|
||||
EntrypointContainer<LoVisualAddon> entrypoint,
|
||||
boolean enabled,
|
||||
AddonStatus status) {
|
||||
this.descriptor = descriptor;
|
||||
this.entrypoint = entrypoint;
|
||||
this.enabled = enabled;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
AddonSnapshot snapshot() {
|
||||
return new AddonSnapshot(
|
||||
descriptor.id(),
|
||||
descriptor.name(),
|
||||
descriptor.version(),
|
||||
descriptor.description(),
|
||||
descriptor.authors(),
|
||||
descriptor.iconPath(),
|
||||
descriptor.apiVersion(),
|
||||
status,
|
||||
enabled,
|
||||
restartRequired,
|
||||
modules.size(),
|
||||
draggableHudElements.size(),
|
||||
staticHudElements.size(),
|
||||
commands.size(),
|
||||
clickGuiSections.size(),
|
||||
moduleExtensions.size(),
|
||||
irisPatchManifests.size(),
|
||||
List.copyOf(issues)
|
||||
);
|
||||
}
|
||||
|
||||
public void issue(AddonIssue.Severity severity, String message, String detail) {
|
||||
|
||||
issues.add(new AddonIssue(descriptor.id(), severity, message, detail));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.manager;
|
||||
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiRenderContext;
|
||||
import dev.loki.lovisual.features.gui.clickgui.render.ClickGuiRenderer;
|
||||
import dev.loki.lovisual.features.gui.clickgui.sections.ClickGuiSection;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
|
||||
public enum ClickGuiSectionManager {
|
||||
;
|
||||
|
||||
private static final Map<String, Entry> SECTIONS = new LinkedHashMap<>();
|
||||
|
||||
public static synchronized boolean register(String addonId,
|
||||
String sectionId,
|
||||
String label,
|
||||
LoVisualClickGuiSection section) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
String normalizedSectionId = normalize(sectionId);
|
||||
if (normalizedAddonId.isBlank() || normalizedSectionId.isBlank() || section == null) {
|
||||
return false;
|
||||
}
|
||||
String id = normalizedAddonId + ":" + normalizedSectionId;
|
||||
if (SECTIONS.containsKey(id)) {
|
||||
return false;
|
||||
}
|
||||
String title = label == null || label.isBlank() ? normalizedSectionId : label.trim();
|
||||
SECTIONS.put(id, new Entry(
|
||||
normalizedAddonId,
|
||||
id,
|
||||
normalizedSectionId,
|
||||
title,
|
||||
new AddonSectionAdapter(section)
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static synchronized void unregisterAddon(String addonId) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
SECTIONS.entrySet().removeIf(entry -> {
|
||||
if (!entry.getValue().addonId().equals(normalizedAddonId)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
entry.getValue().section().onDeselected();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static synchronized List<Entry> sections() {
|
||||
return SECTIONS.values().stream()
|
||||
.filter(entry -> AddonManager.isActive(entry.addonId()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public record Entry(String addonId,
|
||||
String id,
|
||||
String localId,
|
||||
String label,
|
||||
ClickGuiSection section) {
|
||||
}
|
||||
|
||||
private record AddonSectionAdapter(LoVisualClickGuiSection section) implements ClickGuiSection {
|
||||
@Override
|
||||
public void layout(float x, float y, float w, float h) {
|
||||
section.layout(x, y, w, h);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(float mouseX, float mouseY) {
|
||||
section.render(
|
||||
new LoVisualClickGuiRenderContext(
|
||||
ClickGuiRenderer.currentRenderer(),
|
||||
ClickGuiRenderer.getInterRegular(),
|
||||
ClickGuiRenderer.getInterMedium()
|
||||
),
|
||||
mouseX,
|
||||
mouseY
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void renderGlassPass(float alphaFactor) {
|
||||
section.renderGlassPass(alphaFactor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mousePressed(float mouseX, float mouseY, int button) {
|
||||
return section.mousePressed(mouseX, mouseY, button);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mouseReleased(float mouseX, float mouseY, int button) {
|
||||
section.mouseReleased(mouseX, mouseY, button);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseScrolled(float mouseX, float mouseY, double amount) {
|
||||
return section.mouseScrolled(mouseX, mouseY, amount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
|
||||
return section.keyPressed(keyCode, scanCode, modifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean charTyped(char chr, int modifiers) {
|
||||
return section.charTyped(chr, modifiers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSelected() {
|
||||
section.onSelected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeselected() {
|
||||
section.onDeselected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisible() {
|
||||
return section.isVisible();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.manager;
|
||||
|
||||
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.context.ModuleExtensionContextImpl;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
|
||||
public enum ModuleExtensionManager {
|
||||
;
|
||||
|
||||
private static final Map<String, List<RegisteredExtension>> EXTENSIONS = new LinkedHashMap<>();
|
||||
|
||||
public static boolean register(String addonId, String moduleId, LoVisualModuleExtension extension) {
|
||||
if (extension == null || moduleId == null || moduleId.isBlank()) return false;
|
||||
Module module = ModuleManager.get(moduleId);
|
||||
if (module == null) {
|
||||
DebugLog.warn("[Addons] Module extension target missing: addon=%s module=%s", addonId, moduleId);
|
||||
return false;
|
||||
}
|
||||
String normalized = normalize(moduleId);
|
||||
RegisteredExtension registered = new RegisteredExtension(addonId, extension);
|
||||
EXTENSIONS.computeIfAbsent(normalized, ignored -> new ArrayList<>()).add(registered);
|
||||
try {
|
||||
extension.onRegister(new ModuleExtensionContextImpl(addonId, module));
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Module extension registration failed: %s", t, normalized);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int count() {
|
||||
int count = 0;
|
||||
for (List<RegisteredExtension> list : EXTENSIONS.values()) {
|
||||
count += list.size();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public static boolean beforeEnable(Module module) {
|
||||
return all(module, extension -> extension.beforeEnable(module));
|
||||
}
|
||||
|
||||
public static void afterEnable(Module module) {
|
||||
each(module, extension -> extension.afterEnable(module));
|
||||
}
|
||||
|
||||
public static boolean beforeDisable(Module module) {
|
||||
return all(module, extension -> extension.beforeDisable(module));
|
||||
}
|
||||
|
||||
public static void afterDisable(Module module) {
|
||||
each(module, extension -> extension.afterDisable(module));
|
||||
}
|
||||
|
||||
public static boolean beforeTick(Module module) {
|
||||
return all(module, extension -> extension.beforeTick(module));
|
||||
}
|
||||
|
||||
public static void afterTick(Module module) {
|
||||
each(module, extension -> extension.afterTick(module));
|
||||
}
|
||||
|
||||
public static boolean beforeFrame(Module module, float frameDeltaTicks) {
|
||||
return all(module, extension -> extension.beforeFrame(module, frameDeltaTicks));
|
||||
}
|
||||
|
||||
public static void afterFrame(Module module, float frameDeltaTicks) {
|
||||
each(module, extension -> extension.afterFrame(module, frameDeltaTicks));
|
||||
}
|
||||
|
||||
public static boolean beforeHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
return all(module, extension -> extension.beforeHudRender(module, renderer, textRenderer, ctx, tickDelta));
|
||||
}
|
||||
|
||||
public static void afterHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
each(module, extension -> extension.afterHudRender(module, renderer, textRenderer, ctx, tickDelta));
|
||||
}
|
||||
|
||||
public static boolean beforeWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
return all(module, extension -> extension.beforeWorldRender(module, renderer, depthRenderer, tickDelta));
|
||||
}
|
||||
|
||||
public static void afterWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
each(module, extension -> extension.afterWorldRender(module, renderer, depthRenderer, tickDelta));
|
||||
}
|
||||
|
||||
private static boolean all(Module module, ExtensionBooleanCall call) {
|
||||
List<RegisteredExtension> extensions = extensions(module);
|
||||
if (extensions.isEmpty()) return true;
|
||||
boolean proceed = true;
|
||||
for (RegisteredExtension registered : extensions) {
|
||||
if (!AddonManager.isActive(registered.addonId())) continue;
|
||||
try {
|
||||
proceed &= call.invoke(registered.extension());
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Module extension hook failed: addon=%s module=%s",
|
||||
t, registered.addonId(), module == null ? "" : module.name());
|
||||
}
|
||||
}
|
||||
return proceed;
|
||||
}
|
||||
|
||||
private static void each(Module module, ExtensionVoidCall call) {
|
||||
List<RegisteredExtension> extensions = extensions(module);
|
||||
if (extensions.isEmpty()) return;
|
||||
for (RegisteredExtension registered : extensions) {
|
||||
if (!AddonManager.isActive(registered.addonId())) continue;
|
||||
try {
|
||||
call.invoke(registered.extension());
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Module extension hook failed: addon=%s module=%s",
|
||||
t, registered.addonId(), module == null ? "" : module.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<RegisteredExtension> extensions(Module module) {
|
||||
if (module == null) return List.of();
|
||||
List<RegisteredExtension> list = EXTENSIONS.get(normalize(module.name()));
|
||||
return list == null ? List.of() : List.copyOf(list);
|
||||
}
|
||||
|
||||
private static String normalize(String id) {
|
||||
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ExtensionBooleanCall {
|
||||
boolean invoke(LoVisualModuleExtension extension);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ExtensionVoidCall {
|
||||
void invoke(LoVisualModuleExtension extension);
|
||||
}
|
||||
|
||||
private record RegisteredExtension(String addonId, LoVisualModuleExtension extension) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,194 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessContext;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderContext;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import dev.loki.lovisual.features.module.phase.HudPhase;
|
||||
import dev.loki.lovisual.features.module.phase.WorldPhase;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessManager;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
|
||||
public enum AddonRenderPipelineManager {
|
||||
;
|
||||
|
||||
private static final Map<LoVisualRenderStage, List<RegisteredRenderCallback>> CALLBACKS =
|
||||
new EnumMap<>(LoVisualRenderStage.class);
|
||||
|
||||
static {
|
||||
for (LoVisualRenderStage stage : LoVisualRenderStage.values()) {
|
||||
CALLBACKS.put(stage, new ArrayList<>());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized boolean register(String addonId,
|
||||
String callbackId,
|
||||
LoVisualRenderStage stage,
|
||||
LoVisualRenderCallback callback) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
String normalizedCallbackId = normalize(callbackId);
|
||||
if (normalizedAddonId.isBlank() || normalizedCallbackId.isBlank() || stage == null || callback == null) {
|
||||
return false;
|
||||
}
|
||||
List<RegisteredRenderCallback> callbacks = CALLBACKS.get(stage);
|
||||
for (RegisteredRenderCallback registered : callbacks) {
|
||||
if (registered.addonId().equals(normalizedAddonId) && registered.callbackId().equals(normalizedCallbackId)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
callbacks.add(new RegisteredRenderCallback(normalizedAddonId, normalizedCallbackId, callback));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean hasActiveCallbacks(LoVisualRenderStage stage) {
|
||||
if (stage == null) return false;
|
||||
List<RegisteredRenderCallback> callbacks;
|
||||
synchronized (AddonRenderPipelineManager.class) {
|
||||
callbacks = List.copyOf(CALLBACKS.get(stage));
|
||||
}
|
||||
for (RegisteredRenderCallback callback : callbacks) {
|
||||
if (AddonManager.isActive(callback.addonId())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean registerPostProcess(String addonId,
|
||||
String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
int priority,
|
||||
LoVisualPostProcessCallback callback) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
String normalizedPassId = normalize(passId);
|
||||
if (normalizedAddonId.isBlank() || normalizedPassId.isBlank() || phase == null || callback == null) {
|
||||
return false;
|
||||
}
|
||||
PostProcessManager.register(new AddonPostProcessPass(normalizedAddonId, normalizedPassId, phase, priority, callback));
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void render2D(LoVisualRenderStage stage,
|
||||
HudPhase hudPhase,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor guiContext,
|
||||
float tickDelta) {
|
||||
render(stage, hudPhase, null, renderer, null, null, textRenderer, guiContext, null, tickDelta);
|
||||
}
|
||||
|
||||
public static void render3D(LoVisualRenderStage stage,
|
||||
WorldPhase worldPhase,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
PoseStack poseStack,
|
||||
float tickDelta) {
|
||||
render(stage, null, worldPhase, null, renderer, depthRenderer, null, null, poseStack, tickDelta);
|
||||
}
|
||||
|
||||
public static synchronized void unregisterAddon(String addonId) {
|
||||
String normalizedAddonId = normalize(addonId);
|
||||
for (List<RegisteredRenderCallback> callbacks : CALLBACKS.values()) {
|
||||
callbacks.removeIf(callback -> callback.addonId().equals(normalizedAddonId));
|
||||
}
|
||||
}
|
||||
|
||||
private static void render(LoVisualRenderStage stage,
|
||||
HudPhase hudPhase,
|
||||
WorldPhase worldPhase,
|
||||
Renderer2D renderer2D,
|
||||
Renderer3D renderer3D,
|
||||
Renderer3D depthRenderer3D,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor guiContext,
|
||||
PoseStack poseStack,
|
||||
float tickDelta) {
|
||||
List<RegisteredRenderCallback> callbacks;
|
||||
synchronized (AddonRenderPipelineManager.class) {
|
||||
callbacks = List.copyOf(CALLBACKS.get(stage));
|
||||
}
|
||||
for (RegisteredRenderCallback registered : callbacks) {
|
||||
if (!AddonManager.isActive(registered.addonId())) continue;
|
||||
try {
|
||||
registered.callback().render(new LoVisualRenderContext(
|
||||
registered.addonId(),
|
||||
registered.callbackId(),
|
||||
stage,
|
||||
hudPhase,
|
||||
worldPhase,
|
||||
renderer2D,
|
||||
renderer3D,
|
||||
depthRenderer3D,
|
||||
textRenderer,
|
||||
guiContext,
|
||||
poseStack,
|
||||
tickDelta
|
||||
));
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Render callback failed: addon=%s id=%s",
|
||||
t, registered.addonId(), registered.callbackId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String id) {
|
||||
return id == null ? "" : id.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private record RegisteredRenderCallback(String addonId,
|
||||
String callbackId,
|
||||
LoVisualRenderCallback callback) {
|
||||
}
|
||||
|
||||
private record AddonPostProcessPass(String addonId,
|
||||
String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
int priority,
|
||||
LoVisualPostProcessCallback callback) implements PostProcessPass {
|
||||
@Override
|
||||
public boolean isActive() {
|
||||
return AddonManager.isActive(addonId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean render(GpuTextureView src, GpuTextureView dst, float tickDelta) {
|
||||
if (!isActive()) return false;
|
||||
try {
|
||||
return callback.render(new LoVisualPostProcessContext(addonId, passId, phase, src, dst, tickDelta));
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("[Addons] Post-process callback failed: addon=%s id=%s", t, addonId, passId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority() {
|
||||
return priority;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Phase getPhase() {
|
||||
return phase;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.addon.core.AddonIssue;
|
||||
import dev.loki.lovisual.addon.pipeline.AddonStatus;
|
||||
|
||||
public record AddonSnapshot(
|
||||
String id,
|
||||
String name,
|
||||
String version,
|
||||
String description,
|
||||
List<String> authors,
|
||||
String iconPath,
|
||||
int apiVersion,
|
||||
AddonStatus status,
|
||||
boolean enabled,
|
||||
boolean restartRequired,
|
||||
int modules,
|
||||
int draggableHudElements,
|
||||
int staticHudElements,
|
||||
int commands,
|
||||
int clickGuiSections,
|
||||
int moduleExtensions,
|
||||
int irisPatchManifests,
|
||||
List<AddonIssue> issues
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class AddonStateStore {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private AddonStateStore() {
|
||||
}
|
||||
|
||||
public static Map<String, Boolean> loadEnabledOverrides() {
|
||||
|
||||
Path file = stateFile();
|
||||
if (!Files.isRegularFile(file)) return new HashMap<>();
|
||||
try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
|
||||
State state = GSON.fromJson(reader, State.class);
|
||||
if (state == null || state.enabled == null) return new HashMap<>();
|
||||
return new HashMap<>(state.enabled);
|
||||
} catch (Throwable ignored) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveEnabledOverrides(Map<String, Boolean> enabled) {
|
||||
|
||||
Path file = stateFile();
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
State state = new State();
|
||||
state.enabled = new HashMap<>(enabled);
|
||||
try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
|
||||
GSON.toJson(state, writer);
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static Path stateFile() {
|
||||
return FabricLoader.getInstance().getConfigDir()
|
||||
.resolve("lovisual")
|
||||
.resolve("addons.json");
|
||||
}
|
||||
|
||||
private static final class State {
|
||||
Map<String, Boolean> enabled = new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.addon.pipeline;
|
||||
|
||||
public enum AddonStatus {
|
||||
DISCOVERED,
|
||||
DISABLED,
|
||||
ACTIVE,
|
||||
SUSPENDED,
|
||||
ERROR,
|
||||
SHUTDOWN
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
/**
|
||||
* Fabric entrypoint contract for LoVisual addons.
|
||||
*
|
||||
* <p>Declare it in fabric.mod.json under the {@value #ENTRYPOINT_KEY} entrypoint.
|
||||
*/
|
||||
public interface LoVisualAddon {
|
||||
String ENTRYPOINT_KEY = "lovisual:addon";
|
||||
int API_VERSION = 0;
|
||||
|
||||
/**
|
||||
* Called before LoVisual auto-loads its built-in modules.
|
||||
*
|
||||
* <p>Use this hook only for startup module exclusions. Normal addon registration
|
||||
* still belongs in {@link #onInitialize(LoVisualAddonContext)}.</p>
|
||||
*/
|
||||
default void onConfigureModules(LoVisualModuleLoadContext context) {
|
||||
}
|
||||
|
||||
void onInitialize(LoVisualAddonContext context);
|
||||
|
||||
/**
|
||||
* Called after all built-in and addon module configs have been loaded and applied.
|
||||
* This is the safe startup hook for mutating settings of existing modules.
|
||||
*/
|
||||
default void onClientReady(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
|
||||
default void onRuntimeSuspended(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
|
||||
default void onRuntimeResumed(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
|
||||
default void onShutdown(LoVisualAddonRuntimeContext context) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
import dev.loki.lovisual.events.meta.UsedImplicitly;
|
||||
import dev.loki.lovisual.features.command.util.ClientCommand;
|
||||
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualPostProcessCallback;
|
||||
import dev.loki.lovisual.api.v0.render.callback.LoVisualRenderCallback;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import net.fabricmc.loader.api.ModContainer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public interface LoVisualAddonContext extends LoVisualAddonRuntimeContext {
|
||||
@UsedImplicitly
|
||||
ModContainer modContainer();
|
||||
@UsedImplicitly
|
||||
Path gameDir();
|
||||
|
||||
Path configDir();
|
||||
@UsedImplicitly
|
||||
Path addonConfigDir();
|
||||
@UsedImplicitly
|
||||
void registerModule(Module module);
|
||||
@UsedImplicitly
|
||||
void registerDraggableHudElement(DraggableHudElement element);
|
||||
@UsedImplicitly
|
||||
void registerStaticHudElement(AbstractHudElement element);
|
||||
@UsedImplicitly
|
||||
void registerCommand(ClientCommand command);
|
||||
@UsedImplicitly
|
||||
void registerClickGuiSection(String sectionId, String label, LoVisualClickGuiSection section);
|
||||
@UsedImplicitly
|
||||
void registerModuleExtension(String moduleId, LoVisualModuleExtension extension);
|
||||
@UsedImplicitly
|
||||
void registerIrisShaderPatchManifest(String manifestResourcePath);
|
||||
@UsedImplicitly
|
||||
void registerRenderCallback(String callbackId, LoVisualRenderStage stage, LoVisualRenderCallback callback);
|
||||
@UsedImplicitly
|
||||
void registerPostProcessPass(String passId, PostProcessPass.Phase phase, int priority, LoVisualPostProcessCallback callback);
|
||||
@UsedImplicitly
|
||||
RenderPipeline registerRenderPipeline(RenderPipeline pipeline);
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
|
||||
|
||||
public interface LoVisualAddonRuntimeContext {
|
||||
String addonId();
|
||||
|
||||
LoVisualClientApi client();
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.addon;
|
||||
|
||||
import dev.loki.lovisual.events.meta.UsedImplicitly;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleInfo;
|
||||
|
||||
/**
|
||||
* Early addon context used before LoVisual's built-in modules are instantiated.
|
||||
*
|
||||
* <p>Only enabled addons receive this callback. Exclusions are startup-only: changing
|
||||
* an addon's enabled state after module discovery requires a client restart for the
|
||||
* built-in module set to be rebuilt.</p>
|
||||
*/
|
||||
public interface LoVisualModuleLoadContext {
|
||||
@UsedImplicitly
|
||||
String addonId();
|
||||
|
||||
/**
|
||||
* Prevents an auto-loaded built-in module from being instantiated.
|
||||
*
|
||||
* <p>The reference may be a {@code ModuleInfo.id}, module alias, simple class name,
|
||||
* or fully-qualified class name.</p>
|
||||
*
|
||||
* @return {@code true} when the exclusion was accepted for the current startup;
|
||||
* {@code false} when the reference is invalid or module discovery has already started
|
||||
*/
|
||||
@UsedImplicitly
|
||||
boolean disableBuiltInModule(String moduleReference);
|
||||
|
||||
/**
|
||||
* Class-based convenience overload for addons that directly depend on a built-in module type.
|
||||
*/
|
||||
@UsedImplicitly
|
||||
default boolean disableBuiltInModule(Class<? extends Module> moduleType) {
|
||||
return moduleType != null && disableBuiltInModule(moduleType.getName());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.clickgui;
|
||||
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
|
||||
public record LoVisualClickGuiRenderContext(
|
||||
Renderer2D renderer,
|
||||
TextRenderer regularFont,
|
||||
TextRenderer mediumFont
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.clickgui;
|
||||
|
||||
public interface LoVisualClickGuiSection {
|
||||
default void layout(float x, float y, float w, float h) {
|
||||
}
|
||||
|
||||
default void render(LoVisualClickGuiRenderContext context, float mouseX, float mouseY) {
|
||||
}
|
||||
|
||||
default void renderGlassPass(float alphaFactor) {
|
||||
}
|
||||
|
||||
default boolean mousePressed(float mouseX, float mouseY, int button) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default void mouseReleased(float mouseX, float mouseY, int button) {
|
||||
}
|
||||
|
||||
default boolean mouseScrolled(float mouseX, float mouseY, double amount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default boolean keyPressed(int keyCode, int scanCode, int modifiers) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default boolean charTyped(char chr, int modifiers) {
|
||||
return false;
|
||||
}
|
||||
|
||||
default void onSelected() {
|
||||
}
|
||||
|
||||
default void onDeselected() {
|
||||
}
|
||||
|
||||
default boolean isVisible() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.client;
|
||||
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class LoVisualClientApi {
|
||||
private static final LoVisualClientApi INSTANCE = new LoVisualClientApi();
|
||||
|
||||
private LoVisualClientApi() {
|
||||
}
|
||||
|
||||
public static LoVisualClientApi get() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public List<Module> modules() {
|
||||
return ModuleManager.getModules();
|
||||
}
|
||||
|
||||
public Module module(String id) {
|
||||
return ModuleManager.get(id);
|
||||
}
|
||||
|
||||
public boolean isModuleEnabled(String id) {
|
||||
return ModuleManager.isEnabled(id);
|
||||
}
|
||||
|
||||
public void setModuleEnabled(String id, boolean enabled) {
|
||||
ModuleManager.setEnabled(id, enabled);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.module;
|
||||
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
public interface LoVisualModuleExtension {
|
||||
default void onRegister(ModuleExtensionContext context) {
|
||||
}
|
||||
|
||||
default boolean beforeEnable(Module module) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterEnable(Module module) {
|
||||
}
|
||||
|
||||
default boolean beforeDisable(Module module) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterDisable(Module module) {
|
||||
}
|
||||
|
||||
default boolean beforeTick(Module module) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterTick(Module module) {
|
||||
}
|
||||
|
||||
default boolean beforeFrame(Module module, float frameDeltaTicks) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterFrame(Module module, float frameDeltaTicks) {
|
||||
}
|
||||
|
||||
default boolean beforeHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterHudRender(Module module,
|
||||
Renderer2D renderer,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor ctx,
|
||||
float tickDelta) {
|
||||
}
|
||||
|
||||
default boolean beforeWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
return true;
|
||||
}
|
||||
|
||||
default void afterWorldRender(Module module,
|
||||
Renderer3D renderer,
|
||||
Renderer3D depthRenderer,
|
||||
float tickDelta) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.module;
|
||||
|
||||
import dev.loki.lovisual.config.definition.SettingDef;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
public interface ModuleExtensionContext {
|
||||
String addonId();
|
||||
|
||||
String moduleId();
|
||||
|
||||
Module module();
|
||||
|
||||
void addSetting(SettingDef setting);
|
||||
|
||||
ConfigValue<?> getConfigValue(String configName);
|
||||
|
||||
boolean addModeOption(String configName, String option);
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render;
|
||||
|
||||
import com.mojang.blaze3d.PrimitiveTopology;
|
||||
import com.mojang.blaze3d.pipeline.BlendFunction;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import com.mojang.blaze3d.shaders.UniformType;
|
||||
import com.mojang.blaze3d.vertex.VertexFormat;
|
||||
import dev.loki.lovisual.render.engine.pipeline.LoVisualRenderPipelines;
|
||||
import dev.loki.lovisual.render.engine.pipeline.DepthTestFunction;
|
||||
import dev.loki.lovisual.render.engine.pipeline.ExtendedRenderPipelineBuilder;
|
||||
import dev.loki.lovisual.render.engine.rhi.clip.ShapeClipRenderPassContract;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public final class LoVisualRenderPipelineBuilder {
|
||||
private final ExtendedRenderPipelineBuilder delegate;
|
||||
|
||||
private LoVisualRenderPipelineBuilder(RenderPipeline.Snippet... snippets) {
|
||||
this.delegate = new ExtendedRenderPipelineBuilder(snippets);
|
||||
}
|
||||
|
||||
public static LoVisualRenderPipelineBuilder create(RenderPipeline.Snippet... snippets) {
|
||||
return new LoVisualRenderPipelineBuilder(snippets);
|
||||
}
|
||||
|
||||
public static RenderPipeline.Snippet meshUniforms() {
|
||||
return LoVisualRenderPipelines.meshUniforms();
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder location(Identifier id) {
|
||||
delegate.withLocation(id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder vertexFormat(VertexFormat format, PrimitiveTopology mode) {
|
||||
delegate.withVertexFormat(format, mode);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder vertexShader(Identifier id) {
|
||||
delegate.withVertexShader(id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder fragmentShader(Identifier id) {
|
||||
delegate.withFragmentShader(id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder depthTest(DepthTestFunction function) {
|
||||
delegate.withDepthTestFunction(function);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder depthWrite(boolean write) {
|
||||
delegate.withDepthWrite(write);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder blend(BlendFunction blend) {
|
||||
delegate.withBlend(blend);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder cull(boolean cull) {
|
||||
delegate.withCull(cull);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder sampler(String name) {
|
||||
delegate.withSampler(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder uniform(String name, UniformType type) {
|
||||
delegate.withUniform(name, type);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder lineSmooth() {
|
||||
delegate.withLineSmooth();
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder shapeClipSupport() {
|
||||
delegate.withShapeClipSupport();
|
||||
return this;
|
||||
}
|
||||
|
||||
public LoVisualRenderPipelineBuilder shapeClipContract(ShapeClipRenderPassContract contract) {
|
||||
delegate.withShapeClipContract(contract);
|
||||
return this;
|
||||
}
|
||||
|
||||
public RenderPipeline build() {
|
||||
return delegate.build();
|
||||
}
|
||||
|
||||
public RenderPipeline buildAndRegister() {
|
||||
return LoVisualRenderPipelines.registerAddonPipeline(build());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render;
|
||||
|
||||
public enum LoVisualRenderStage {
|
||||
HUD_RAW,
|
||||
HUD_SCALED,
|
||||
HUD_LOGICAL,
|
||||
HUD_RAW_FOREGROUND,
|
||||
HUD_SCALED_FOREGROUND,
|
||||
HUD_LOGICAL_FOREGROUND,
|
||||
WORLD_BEFORE_TRANSLUCENT,
|
||||
WORLD_END_MAIN,
|
||||
WORLD_POST_PROCESS,
|
||||
SCREEN_BEFORE_VANILLA_GUI,
|
||||
SCREEN_AFTER_VANILLA_GUI
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render;
|
||||
|
||||
import com.mojang.blaze3d.buffers.GpuBufferSlice;
|
||||
import dev.loki.lovisual.render.engine.core.system.LoVisualRenderSystem;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public enum LoVisualUniforms {
|
||||
;
|
||||
|
||||
public static GpuBufferSlice write(String name,
|
||||
int std140Size,
|
||||
int expectedWritesPerFrame,
|
||||
UniformWriter writer) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException("Uniform name cannot be blank");
|
||||
}
|
||||
if (std140Size <= 0) {
|
||||
throw new IllegalArgumentException("Uniform std140 size must be positive");
|
||||
}
|
||||
if (writer == null) {
|
||||
throw new IllegalArgumentException("Uniform writer cannot be null");
|
||||
}
|
||||
return LoVisualRenderSystem.uniforms().write(name, std140Size, expectedWritesPerFrame, writer::write);
|
||||
}
|
||||
|
||||
public static GpuBufferSlice writeCached(String name,
|
||||
int std140Size,
|
||||
int expectedWritesPerFrame,
|
||||
int updateEveryFrames,
|
||||
boolean force,
|
||||
UniformWriter writer) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException("Uniform name cannot be blank");
|
||||
}
|
||||
if (std140Size <= 0) {
|
||||
throw new IllegalArgumentException("Uniform std140 size must be positive");
|
||||
}
|
||||
if (writer == null) {
|
||||
throw new IllegalArgumentException("Uniform writer cannot be null");
|
||||
}
|
||||
return LoVisualRenderSystem.uniforms().writeCached(
|
||||
name,
|
||||
std140Size,
|
||||
expectedWritesPerFrame,
|
||||
updateEveryFrames,
|
||||
force,
|
||||
writer::write
|
||||
);
|
||||
}
|
||||
|
||||
public static GpuBufferSlice current(String name) {
|
||||
if (name == null || name.isBlank()) return null;
|
||||
return LoVisualRenderSystem.uniforms().current(name);
|
||||
}
|
||||
|
||||
public static void invalidate(String name) {
|
||||
if (name == null || name.isBlank()) return;
|
||||
LoVisualRenderSystem.uniforms().invalidate(name);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface UniformWriter {
|
||||
void write(ByteBuffer buffer);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface LoVisualPostProcessCallback {
|
||||
public boolean render(LoVisualPostProcessContext context);
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
|
||||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import dev.loki.lovisual.render.engine.postprocess.post.PostProcessPass;
|
||||
import net.minecraft.client.Minecraft;
|
||||
|
||||
public record LoVisualPostProcessContext(
|
||||
String addonId,
|
||||
String passId,
|
||||
PostProcessPass.Phase phase,
|
||||
GpuTextureView source,
|
||||
GpuTextureView destination,
|
||||
float tickDelta
|
||||
) {
|
||||
public Minecraft client() {
|
||||
return Minecraft.getInstance();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface LoVisualRenderCallback {
|
||||
public void render(LoVisualRenderContext context);
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.api.v0.render.callback;
|
||||
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
|
||||
|
||||
|
||||
import com.mojang.blaze3d.vertex.PoseStack;
|
||||
import dev.loki.lovisual.features.module.phase.HudPhase;
|
||||
import dev.loki.lovisual.features.module.phase.WorldPhase;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
|
||||
import dev.loki.lovisual.render.engine.text.render.TextRenderer;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
|
||||
public record LoVisualRenderContext(
|
||||
String addonId,
|
||||
String callbackId,
|
||||
LoVisualRenderStage stage,
|
||||
HudPhase hudPhase,
|
||||
WorldPhase worldPhase,
|
||||
Renderer2D renderer2D,
|
||||
Renderer3D renderer3D,
|
||||
Renderer3D depthRenderer3D,
|
||||
TextRenderer textRenderer,
|
||||
GuiGraphicsExtractor guiContext,
|
||||
PoseStack poseStack,
|
||||
float tickDelta
|
||||
) {
|
||||
public Minecraft client() {
|
||||
return Minecraft.getInstance();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xaero.common.minimap.waypoints.Waypoint;
|
||||
import xaero.map.mods.SupportXaeroMinimap;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Kept as a no-op compatibility bridge for older mixin code paths.
|
||||
* @xwp markers are now inserted into Xaero's real waypoint sets by {@link XaeroWaypointRuntime},
|
||||
* otherwise World Map/minimap hover, open and delete logic cannot see them.
|
||||
*/
|
||||
public enum XaeroCommandWaypointCompat {
|
||||
;
|
||||
|
||||
public static List<Waypoint> getMinimapWaypoints() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public static List<xaero.map.mods.gui.Waypoint> getWorldMapWaypoints(@Nullable SupportXaeroMinimap minimap) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,229 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.Level;
|
||||
import xaero.common.HudMod;
|
||||
import xaero.common.minimap.waypoints.Waypoint;
|
||||
import xaero.hud.minimap.BuiltInHudModules;
|
||||
import xaero.hud.minimap.module.MinimapSession;
|
||||
import xaero.hud.minimap.waypoint.WaypointColor;
|
||||
import xaero.hud.minimap.waypoint.WaypointPurpose;
|
||||
import xaero.hud.minimap.waypoint.set.WaypointSet;
|
||||
import xaero.hud.minimap.world.MinimapWorld;
|
||||
import xaero.hud.minimap.world.MinimapWorldManager;
|
||||
import xaero.hud.path.XaeroPath;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class XaeroWaypointRuntime {
|
||||
private XaeroWaypointRuntime() {
|
||||
}
|
||||
|
||||
static XaeroWaypointStore.RuntimeAddResult addFromCurrentDimension(int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
boolean dualDefault) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.level == null) {
|
||||
return fail("No client world is loaded.");
|
||||
}
|
||||
|
||||
MinimapSession session = currentSession();
|
||||
if (session == null) {
|
||||
return fail("Xaero minimap session is not ready.");
|
||||
}
|
||||
|
||||
List<XaeroWaypointStore.Marker> added = new ArrayList<>(2);
|
||||
ResourceKey<Level> currentDim = mc.level.dimension();
|
||||
boolean overworld = currentDim == Level.OVERWORLD;
|
||||
boolean nether = currentDim == Level.NETHER;
|
||||
|
||||
if (dualDefault && overworld) {
|
||||
addToWorld(session, Level.OVERWORLD, x, y, z, name, "overworld", added);
|
||||
addToWorld(session, Level.NETHER, XaeroWaypointStore.netherCoord(x), y, XaeroWaypointStore.netherCoord(z), name, "nether", added);
|
||||
return new XaeroWaypointStore.RuntimeAddResult(true,
|
||||
"Added dual Xaero marker: " + XaeroWaypointStore.format(x, y, z)
|
||||
+ " / Nether " + XaeroWaypointStore.format(XaeroWaypointStore.netherCoord(x), y, XaeroWaypointStore.netherCoord(z)) + ".",
|
||||
List.copyOf(added));
|
||||
}
|
||||
if (dualDefault && nether) {
|
||||
addToWorld(session, Level.NETHER, x, y, z, name, "nether", added);
|
||||
addToWorld(session, Level.OVERWORLD, x * 8, y, z * 8, name, "overworld", added);
|
||||
return new XaeroWaypointStore.RuntimeAddResult(true,
|
||||
"Added dual Xaero marker: Nether " + XaeroWaypointStore.format(x, y, z)
|
||||
+ " / Overworld " + XaeroWaypointStore.format(x * 8, y, z * 8) + ".",
|
||||
List.copyOf(added));
|
||||
}
|
||||
|
||||
addToWorld(session, currentDim, x, y, z, name, XaeroWaypointStore.dimensionId(currentDim.identifier()), added);
|
||||
return new XaeroWaypointStore.RuntimeAddResult(true,
|
||||
"Added Xaero marker: " + XaeroWaypointStore.format(x, y, z) + ".",
|
||||
List.copyOf(added));
|
||||
}
|
||||
|
||||
static boolean remove(XaeroWaypointStore.Marker marker) {
|
||||
if (!(marker.waypointSetHandle() instanceof WaypointSet set)
|
||||
|| !(marker.waypointHandle() instanceof Waypoint waypoint)) {
|
||||
return true;
|
||||
}
|
||||
set.remove(waypoint);
|
||||
markChanged();
|
||||
return true;
|
||||
}
|
||||
|
||||
static boolean exists(XaeroWaypointStore.Marker marker) {
|
||||
if (!(marker.waypointSetHandle() instanceof WaypointSet set)
|
||||
|| !(marker.waypointHandle() instanceof Waypoint waypoint)) {
|
||||
return false;
|
||||
}
|
||||
for (Waypoint existing : set.getWaypoints()) {
|
||||
if (existing == waypoint) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void addToWorld(MinimapSession session,
|
||||
ResourceKey<Level> dimension,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
String kind,
|
||||
List<XaeroWaypointStore.Marker> out) {
|
||||
MinimapWorld world = resolveWorld(session, dimension);
|
||||
if (world == null) {
|
||||
throw new IllegalStateException("Could not resolve Xaero world for " + dimension.identifier());
|
||||
}
|
||||
|
||||
WaypointSet set = currentSet(world);
|
||||
Waypoint waypoint = new Waypoint(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
XaeroWaypointStore.displayName(name, kind),
|
||||
XaeroWaypointStore.DEFAULT_SYMBOL,
|
||||
WaypointColor.GOLD,
|
||||
WaypointPurpose.NORMAL,
|
||||
true,
|
||||
true
|
||||
);
|
||||
waypoint.setTemporary(true);
|
||||
waypoint.setYIncluded(true);
|
||||
waypoint.setDisabled(false);
|
||||
set.add(waypoint);
|
||||
out.add(XaeroWaypointStore.createMarker(
|
||||
XaeroWaypointStore.dimensionId(dimension.identifier()),
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
waypoint.getName(),
|
||||
waypoint.getSymbol(),
|
||||
set.getName(),
|
||||
kind,
|
||||
set,
|
||||
waypoint
|
||||
));
|
||||
markChanged();
|
||||
}
|
||||
|
||||
private static WaypointSet currentSet(MinimapWorld world) {
|
||||
WaypointSet set = world.getCurrentWaypointSet();
|
||||
if (set != null) {
|
||||
return set;
|
||||
}
|
||||
String setId = world.getCurrentWaypointSetId();
|
||||
if (setId == null || setId.isBlank()) {
|
||||
setId = XaeroWaypointStore.SET;
|
||||
world.setCurrentWaypointSetId(setId);
|
||||
}
|
||||
set = world.getWaypointSet(setId);
|
||||
if (set == null) {
|
||||
world.addWaypointSet(setId);
|
||||
set = world.getWaypointSet(setId);
|
||||
}
|
||||
if (set == null) {
|
||||
throw new IllegalStateException("Could not resolve Xaero waypoint set.");
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
private static MinimapWorld resolveWorld(MinimapSession session, ResourceKey<Level> dimension) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
MinimapWorldManager manager = session.getWorldManager();
|
||||
if (mc != null && mc.level != null && mc.level.dimension() == dimension) {
|
||||
return manager.getCurrentWorld();
|
||||
}
|
||||
|
||||
XaeroPath rootPath = session.getWorldState().getCurrentRootContainerPath();
|
||||
XaeroPath currentWorldPath = session.getWorldState().getCurrentWorldPath();
|
||||
if (rootPath == null || currentWorldPath == null) {
|
||||
return manager.getCurrentWorld();
|
||||
}
|
||||
|
||||
String dimensionNode = session.getDimensionHelper().getDimensionDirectoryName(dimension);
|
||||
if (dimensionNode == null || dimensionNode.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String worldNode = null;
|
||||
try {
|
||||
boolean worldMap = HudMod.INSTANCE != null
|
||||
&& HudMod.INSTANCE.getSupportMods() != null
|
||||
&& HudMod.INSTANCE.getSupportMods().worldmap();
|
||||
worldNode = session.getWorldStateUpdater().getPotentialWorldNode(dimension, worldMap);
|
||||
} catch (Throwable ignored) {
|
||||
// Fallback below keeps the marker in the same multiworld node as the current dimension.
|
||||
}
|
||||
if (worldNode == null || worldNode.isBlank()) {
|
||||
worldNode = currentWorldPath.getLastNode();
|
||||
}
|
||||
|
||||
XaeroPath worldPath = rootPath.resolve(dimensionNode).resolve(worldNode);
|
||||
MinimapWorld world = manager.getWorld(worldPath);
|
||||
if (world != null) {
|
||||
world.setDimId(dimension);
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
private static MinimapSession currentSession() {
|
||||
Object session = BuiltInHudModules.MINIMAP.getCurrentSession();
|
||||
return session instanceof MinimapSession minimapSession ? minimapSession : null;
|
||||
}
|
||||
|
||||
private static void markChanged() {
|
||||
MinimapSession session = currentSession();
|
||||
if (session != null && session.getWaypointSession() != null) {
|
||||
session.getWaypointSession().setSetChangedTime(System.currentTimeMillis());
|
||||
}
|
||||
requestWorldMapRefresh();
|
||||
}
|
||||
|
||||
private static void requestWorldMapRefresh() {
|
||||
try {
|
||||
Class<?> supportMods = Class.forName("xaero.map.mods.SupportMods");
|
||||
Object support = supportMods.getField("xaeroMinimap").get(null);
|
||||
if (support != null) {
|
||||
support.getClass().getMethod("requestWaypointsRefresh").invoke(support);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
// World Map is optional; minimap hover/list deletion works through the real Xaero set without it.
|
||||
}
|
||||
}
|
||||
|
||||
private static XaeroWaypointStore.RuntimeAddResult fail(String message) {
|
||||
return new XaeroWaypointStore.RuntimeAddResult(false, message, List.of());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,249 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.level.Level;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
public enum XaeroWaypointStore {
|
||||
;
|
||||
|
||||
public static final String SET = "lovisual";
|
||||
public static final String DEFAULT_NAME = "LoVisual";
|
||||
public static final String DEFAULT_SYMBOL = "C";
|
||||
|
||||
private static final AtomicLong NEXT_ID = new AtomicLong(1L);
|
||||
private static final CopyOnWriteArrayList<Marker> MARKERS = new CopyOnWriteArrayList<>();
|
||||
|
||||
public static AddResult addFromCurrentDimension(int x, int y, int z, String name, boolean dualDefault) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.level == null) {
|
||||
return new AddResult(false, 0, "No client world is loaded.");
|
||||
}
|
||||
|
||||
String safeName = sanitizeName(name);
|
||||
try {
|
||||
RuntimeAddResult runtime = XaeroWaypointRuntime.addFromCurrentDimension(x, y, z, safeName, dualDefault);
|
||||
if (!runtime.success()) {
|
||||
return new AddResult(false, 0, runtime.message());
|
||||
}
|
||||
MARKERS.addAll(runtime.markers());
|
||||
return new AddResult(true, runtime.markers().size(), runtime.message());
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError error) {
|
||||
return new AddResult(false, 0, "Xaero waypoint runtime is not available.");
|
||||
} catch (Throwable throwable) {
|
||||
return new AddResult(false, 0, "Failed to add Xaero marker: " + throwable.getClass().getSimpleName() + ".");
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Marker> currentDimensionMarkers() {
|
||||
pruneMissing();
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.level == null || MARKERS.isEmpty()) return List.of();
|
||||
String dim = dimensionId(mc.level.dimension().identifier());
|
||||
List<Marker> out = new ArrayList<>();
|
||||
for (Marker marker : MARKERS) {
|
||||
if (marker.dimensionId().equals(dim)) {
|
||||
out.add(marker);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static List<Marker> markers() {
|
||||
pruneMissing();
|
||||
return List.copyOf(MARKERS);
|
||||
}
|
||||
|
||||
public static RemoveResult remove(String selector) {
|
||||
pruneMissing();
|
||||
if (MARKERS.isEmpty()) {
|
||||
return new RemoveResult(true, 0, "No LoVisual Xaero markers to remove.");
|
||||
}
|
||||
|
||||
List<Marker> targets = select(selector);
|
||||
if (targets.isEmpty()) {
|
||||
return new RemoveResult(false, 0, "No matching LoVisual Xaero marker: " + selector + ".");
|
||||
}
|
||||
|
||||
int removed = 0;
|
||||
for (Marker marker : targets) {
|
||||
if (removeMarker(marker)) {
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
if (removed == 0) {
|
||||
return new RemoveResult(false, 0, "No LoVisual Xaero markers were removed.");
|
||||
}
|
||||
return new RemoveResult(true, removed, "Removed Xaero markers: " + removed + ".");
|
||||
}
|
||||
|
||||
public static int clear() {
|
||||
return remove(null).count();
|
||||
}
|
||||
|
||||
static Marker createMarker(String dimensionId,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
String symbol,
|
||||
String set,
|
||||
String kind,
|
||||
Object waypointSetHandle,
|
||||
Object waypointHandle) {
|
||||
return new Marker(
|
||||
NEXT_ID.getAndIncrement(),
|
||||
dimensionId,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
name,
|
||||
symbol,
|
||||
set,
|
||||
kind,
|
||||
System.currentTimeMillis(),
|
||||
waypointSetHandle,
|
||||
waypointHandle
|
||||
);
|
||||
}
|
||||
|
||||
private static List<Marker> select(String selector) {
|
||||
String normalized = selector == null ? "" : selector.trim();
|
||||
if (normalized.isEmpty()
|
||||
|| "all".equalsIgnoreCase(normalized)
|
||||
|| "*".equals(normalized)) {
|
||||
return new ArrayList<>(MARKERS);
|
||||
}
|
||||
|
||||
Integer index = parsePositiveInt(normalized);
|
||||
if (index != null) {
|
||||
List<Marker> snapshot = markers();
|
||||
int zeroIndex = index - 1;
|
||||
if (zeroIndex >= 0 && zeroIndex < snapshot.size()) {
|
||||
return List.of(snapshot.get(zeroIndex));
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String lower = normalized.toLowerCase(Locale.ROOT);
|
||||
List<Marker> out = new ArrayList<>();
|
||||
for (Marker marker : MARKERS) {
|
||||
if (marker.name().toLowerCase(Locale.ROOT).contains(lower)
|
||||
|| marker.kind().toLowerCase(Locale.ROOT).contains(lower)
|
||||
|| marker.dimensionId().toLowerCase(Locale.ROOT).contains(lower)) {
|
||||
out.add(marker);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean removeMarker(Marker marker) {
|
||||
boolean removedFromXaero = true;
|
||||
try {
|
||||
removedFromXaero = XaeroWaypointRuntime.remove(marker);
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError ignored) {
|
||||
removedFromXaero = true;
|
||||
} catch (Throwable ignored) {
|
||||
removedFromXaero = false;
|
||||
}
|
||||
boolean removedFromStore = MARKERS.remove(marker);
|
||||
return removedFromStore && removedFromXaero;
|
||||
}
|
||||
|
||||
private static void pruneMissing() {
|
||||
if (MARKERS.isEmpty()) return;
|
||||
try {
|
||||
Iterator<Marker> iterator = MARKERS.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Marker marker = iterator.next();
|
||||
if (!XaeroWaypointRuntime.exists(marker)) {
|
||||
MARKERS.remove(marker);
|
||||
}
|
||||
}
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError ignored) {
|
||||
MARKERS.clear();
|
||||
} catch (Throwable ignored) {
|
||||
// Keep the in-memory index if Xaero is mid-session reload or unavailable for a tick.
|
||||
}
|
||||
}
|
||||
|
||||
static int netherCoord(int overworldCoord) {
|
||||
return (int) Math.round(overworldCoord / 8.0);
|
||||
}
|
||||
|
||||
static String dimensionId(Identifier id) {
|
||||
return id == null ? "" : id.toString();
|
||||
}
|
||||
|
||||
static String sanitizeName(String name) {
|
||||
if (name == null || name.isBlank()) return DEFAULT_NAME;
|
||||
String trimmed = name.trim();
|
||||
return trimmed.length() > 40 ? trimmed.substring(0, 40) : trimmed;
|
||||
}
|
||||
|
||||
static String displayName(String name, String kind) {
|
||||
String safeName = sanitizeName(name);
|
||||
if (kind == null || kind.isBlank() || kind.contains(":")) return safeName;
|
||||
return safeName + " " + kind;
|
||||
}
|
||||
|
||||
static String format(int x, int y, int z) {
|
||||
return String.format(Locale.ROOT, "%d %d %d", x, y, z);
|
||||
}
|
||||
|
||||
private static Integer parsePositiveInt(String value) {
|
||||
try {
|
||||
int parsed = Integer.parseInt(value);
|
||||
return parsed <= 0 ? null : parsed;
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isOverworld() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
return mc != null && mc.level != null && mc.level.dimension() == Level.OVERWORLD;
|
||||
}
|
||||
|
||||
static boolean isNether() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
return mc != null && mc.level != null && mc.level.dimension() == Level.NETHER;
|
||||
}
|
||||
|
||||
public record Marker(long id,
|
||||
String dimensionId,
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
String name,
|
||||
String symbol,
|
||||
String set,
|
||||
String kind,
|
||||
long createdAtMs,
|
||||
Object waypointSetHandle,
|
||||
Object waypointHandle) {
|
||||
}
|
||||
|
||||
public record AddResult(boolean success, int count, String message) {
|
||||
}
|
||||
|
||||
public record RemoveResult(boolean success, int count, String message) {
|
||||
}
|
||||
|
||||
static record RuntimeAddResult(boolean success, String message, List<Marker> markers) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero.triangulator;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xaero.common.minimap.waypoints.Waypoint;
|
||||
import xaero.hud.minimap.waypoint.WaypointColor;
|
||||
import xaero.hud.minimap.waypoint.WaypointPurpose;
|
||||
|
||||
public enum TriangulatorXaeroMinimapCompat {
|
||||
;
|
||||
private static Waypoint hudWaypoint;
|
||||
private static Waypoint minimapWaypoint;
|
||||
private static boolean hudActive;
|
||||
private static boolean minimapActive;
|
||||
|
||||
@Nullable
|
||||
public static Waypoint getHudWaypoint() {
|
||||
sync();
|
||||
return hudActive ? hudWaypoint : null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Waypoint getMinimapWaypoint() {
|
||||
sync();
|
||||
return minimapActive ? minimapWaypoint : null;
|
||||
}
|
||||
|
||||
private static void sync() {
|
||||
TriangulatorXaeroState.XaeroSnapshot snapshot = TriangulatorXaeroState.snapshot();
|
||||
if (snapshot == null) {
|
||||
hudActive = false;
|
||||
minimapActive = false;
|
||||
return;
|
||||
}
|
||||
|
||||
TriangulatorXaeroState.SyncPoint point = TriangulatorXaeroState.toCurrentDimension(snapshot);
|
||||
WaypointColor color = snapshot.ready() ? WaypointColor.GOLD : WaypointColor.RED;
|
||||
|
||||
hudWaypoint = syncWaypoint(hudWaypoint, point, color);
|
||||
minimapWaypoint = syncWaypoint(minimapWaypoint, point, color);
|
||||
hudActive = true;
|
||||
minimapActive = true;
|
||||
}
|
||||
|
||||
private static Waypoint syncWaypoint(@Nullable Waypoint waypoint,
|
||||
TriangulatorXaeroState.SyncPoint point,
|
||||
WaypointColor color) {
|
||||
Waypoint result = waypoint;
|
||||
if (result == null) {
|
||||
result = new Waypoint(
|
||||
point.x(),
|
||||
point.y(),
|
||||
point.z(),
|
||||
TriangulatorXaeroState.NAME,
|
||||
TriangulatorXaeroState.SYMBOL,
|
||||
color,
|
||||
WaypointPurpose.NORMAL
|
||||
);
|
||||
result.setTemporary(false);
|
||||
result.setYIncluded(false);
|
||||
}
|
||||
result.setX(point.x());
|
||||
result.setY(point.y());
|
||||
result.setZ(point.z());
|
||||
result.setWaypointColor(color);
|
||||
result.setDisabled(false);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero.triangulator;
|
||||
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public enum TriangulatorXaeroState {
|
||||
;
|
||||
public static final String NAME = "Stronghold";
|
||||
public static final String SYMBOL = "S";
|
||||
public static final String SET = "lovisual";
|
||||
public static final int DEFAULT_Y = 64;
|
||||
|
||||
@Nullable
|
||||
public static XaeroSnapshot snapshot() {
|
||||
DraggableHudElement triangulator = DraggableHudElementRegistry.getById("triangulator");
|
||||
if (triangulator == null) return null;
|
||||
try {
|
||||
Object raw = triangulator.getClass().getMethod("getXaeroSnapshot").invoke(triangulator);
|
||||
if (raw == null) return null;
|
||||
return new XaeroSnapshot(
|
||||
readDouble(raw, "overworldX"),
|
||||
readDouble(raw, "overworldZ"),
|
||||
readBoolean(raw, "ready"),
|
||||
readDouble(raw, "confidence"),
|
||||
readInt(raw, "eyeCount")
|
||||
);
|
||||
} catch (ReflectiveOperationException | ClassCastException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static SyncPoint toCurrentDimension(XaeroSnapshot snapshot) {
|
||||
boolean nether = isNetherView();
|
||||
double factor = nether ? 0.125 : 1.0;
|
||||
return new SyncPoint(
|
||||
(int) Math.round(snapshot.overworldX() * factor),
|
||||
DEFAULT_Y,
|
||||
(int) Math.round(snapshot.overworldZ() * factor)
|
||||
);
|
||||
}
|
||||
|
||||
public static boolean isNetherView() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
return mc != null && mc.level != null && mc.level.dimension() == Level.NETHER;
|
||||
}
|
||||
|
||||
private static double readDouble(Object target, String method) throws ReflectiveOperationException {
|
||||
Object value = invoke(target, method);
|
||||
if (value instanceof Number number) return number.doubleValue();
|
||||
throw new ClassCastException(method);
|
||||
}
|
||||
|
||||
private static boolean readBoolean(Object target, String method) throws ReflectiveOperationException {
|
||||
Object value = invoke(target, method);
|
||||
if (value instanceof Boolean bool) return bool;
|
||||
throw new ClassCastException(method);
|
||||
}
|
||||
|
||||
private static int readInt(Object target, String method) throws ReflectiveOperationException {
|
||||
Object value = invoke(target, method);
|
||||
if (value instanceof Number number) return number.intValue();
|
||||
throw new ClassCastException(method);
|
||||
}
|
||||
|
||||
private static Object invoke(Object target, String method) throws ReflectiveOperationException {
|
||||
Method accessor = target.getClass().getMethod(method);
|
||||
return accessor.invoke(target);
|
||||
}
|
||||
|
||||
public record XaeroSnapshot(double overworldX, double overworldZ, boolean ready, double confidence, int eyeCount) {
|
||||
}
|
||||
|
||||
public record SyncPoint(int x, int y, int z) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.compat.xaero.triangulator;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import xaero.common.minimap.waypoints.Waypoint;
|
||||
import xaero.hud.minimap.waypoint.WaypointColor;
|
||||
import xaero.hud.minimap.waypoint.WaypointPurpose;
|
||||
import xaero.map.mods.SupportXaeroMinimap;
|
||||
|
||||
public enum TriangulatorXaeroWorldMapCompat {
|
||||
;
|
||||
|
||||
@Nullable
|
||||
public static xaero.map.mods.gui.Waypoint getWaypoint(SupportXaeroMinimap minimap) {
|
||||
TriangulatorXaeroState.XaeroSnapshot snapshot = TriangulatorXaeroState.snapshot();
|
||||
if (snapshot == null || minimap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Waypoint baseWaypoint = new Waypoint(
|
||||
(int) Math.round(snapshot.overworldX()),
|
||||
TriangulatorXaeroState.DEFAULT_Y,
|
||||
(int) Math.round(snapshot.overworldZ()),
|
||||
TriangulatorXaeroState.NAME,
|
||||
TriangulatorXaeroState.SYMBOL,
|
||||
snapshot.ready() ? WaypointColor.GOLD : WaypointColor.RED,
|
||||
WaypointPurpose.NORMAL
|
||||
);
|
||||
baseWaypoint.setTemporary(false);
|
||||
baseWaypoint.setYIncluded(false);
|
||||
baseWaypoint.setDisabled(false);
|
||||
return minimap.convertWaypoint(baseWaypoint, false, TriangulatorXaeroState.SET, minimap.getDimDiv());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common;
|
||||
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public interface CommonBooleanGroupSchema extends CommonSettingSchema {
|
||||
Map<String, Boolean> defaults();
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CommonSettingSchema {
|
||||
String commonI18nKey();
|
||||
|
||||
default List<String> commonI18nKeys() {
|
||||
String key = commonI18nKey();
|
||||
return key == null || key.isBlank() ? List.of() : List.of(key);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,219 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common;
|
||||
|
||||
import dev.loki.lovisual.config.common.impl.common.CombatPriority;
|
||||
import dev.loki.lovisual.config.common.impl.common.CombatProtocolHeuristicSources;
|
||||
import dev.loki.lovisual.config.common.impl.common.CommonKey;
|
||||
import dev.loki.lovisual.config.common.impl.common.FakeLagFlushOn;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationMode;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationMovementCorrection;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationResetThreshold;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationResetTicks;
|
||||
import dev.loki.lovisual.config.common.impl.wall.RotationThroughWalls;
|
||||
import dev.loki.lovisual.config.common.impl.wall.RotationTiming;
|
||||
import dev.loki.lovisual.config.common.impl.wall.TargetFilters;
|
||||
import dev.loki.lovisual.features.module.modules.visuals.esp.ESP;
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
import dev.loki.lovisual.config.common.impl.common.CombatPriority;
|
||||
import dev.loki.lovisual.config.common.impl.common.CombatProtocolHeuristicSources;
|
||||
import dev.loki.lovisual.config.common.impl.common.CommonKey;
|
||||
import dev.loki.lovisual.config.common.impl.common.FakeLagFlushOn;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationMode;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationMovementCorrection;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationResetThreshold;
|
||||
import dev.loki.lovisual.config.common.impl.rotation.RotationResetTicks;
|
||||
import dev.loki.lovisual.config.common.impl.wall.RotationThroughWalls;
|
||||
import dev.loki.lovisual.config.common.impl.wall.RotationTiming;
|
||||
import dev.loki.lovisual.config.common.impl.wall.TargetFilters;
|
||||
|
||||
public enum CommonSettingSchemas {
|
||||
;
|
||||
|
||||
public static final TargetFilters TARGET_FILTERS = new TargetFilters();
|
||||
|
||||
public static final CombatPriority COMBAT_PRIORITY = new CombatPriority();
|
||||
|
||||
public static final RotationMovementCorrection ROTATION_MOVEMENT_CORRECTION = new RotationMovementCorrection();
|
||||
public static final RotationResetTicks ROTATION_RESET_TICKS = new RotationResetTicks();
|
||||
public static final RotationResetThreshold ROTATION_RESET_THRESHOLD = new RotationResetThreshold();
|
||||
public static final RotationTiming ROTATION_TIMING = new RotationTiming();
|
||||
public static final RotationMode ROTATION_MODE = new RotationMode();
|
||||
public static final RotationThroughWalls ROTATION_THROUGH_WALLS = new RotationThroughWalls();
|
||||
|
||||
// Generic repeated combat/action labels.
|
||||
public static final CommonSettingSchema PLACE = key("place");
|
||||
public static final CommonSettingSchema EXPLODE = key("explode");
|
||||
public static final CommonSettingSchema BREAK = key("break");
|
||||
public static final CommonSettingSchema TIMING = key("timing");
|
||||
public static final CommonSettingSchema CALC_DELAY = key("calc_delay");
|
||||
public static final CommonSettingSchema LOW_PLACE_DELAY = key("low_place_delay");
|
||||
public static final CommonSettingSchema LOW_EXPLODE_DELAY = key("low_explode_delay");
|
||||
public static final CommonSettingSchema AIR_PLACE = key("air_place");
|
||||
public static final CommonSettingSchema MIN_DAMAGE = key("min_damage");
|
||||
public static final CommonSettingSchema FACEPLACE_HEALTH = key("faceplace_health");
|
||||
public static final CommonSettingSchema MAX_SELF_DAMAGE = key("max_self_damage");
|
||||
public static final CommonSettingSchema SELF_PREDICT_TICKS = key("self_predict_ticks");
|
||||
public static final CommonSettingSchema UNSAFE_DIMENSION_ONLY = key("unsafe_dimension_only");
|
||||
public static final CommonSettingSchema PAUSE_MINING = key("pause_mining");
|
||||
public static final CommonSettingSchema PAUSE_EATING = key("pause_eating");
|
||||
public static final CommonSettingSchema RENDER_SELF_DAMAGE = key("render_self_damage");
|
||||
public static final CommonSettingSchema RENDER_DAMAGE = key("render_damage");
|
||||
public static final CommonSettingSchema FILL_COLOR = key("fill_color");
|
||||
public static final CommonSettingSchema LINE_COLOR = key("line_color");
|
||||
public static final CommonSettingSchema LINE_WIDTH = key("line_width");
|
||||
public static final CommonSettingSchema TEXT_COLOR = key("text_color");
|
||||
public static final CommonSettingSchema SLIDE_DELAY = key("slide_delay");
|
||||
public static final CommonSettingSchema FADE_TIME = key("fade_time");
|
||||
public static final CommonSettingSchema MODE = key("mode");
|
||||
|
||||
// Sprint Reset
|
||||
public static final CommonSettingSchema COMBAT_CRITICALS = key("combat.criticals");
|
||||
public static final CommonSettingSchema COMBAT_SPRINT_RESET = key("combat.sprint_reset");
|
||||
public static final CommonSettingSchema COMBAT_WHEN_SPRINTING = key("combat.when_sprinting");
|
||||
public static final CommonSettingSchema COMBAT_STOP_SPRINTING = key("combat.stop_sprinting");
|
||||
public static final CommonSettingSchema COMBAT_ATTACK_MODE = key("combat.attack_mode");
|
||||
public static final CommonSettingSchema COMBAT_CPS_MIN = key("combat.cps_min");
|
||||
public static final CommonSettingSchema COMBAT_CPS_MAX = key("combat.cps_max");
|
||||
public static final CommonSettingSchema COMBAT_PROTOCOL = key("combat.protocol");
|
||||
public static final CombatProtocolHeuristicSources COMBAT_PROTOCOL_HEURISTICS = new CombatProtocolHeuristicSources();
|
||||
public static final CommonSettingSchema COMBAT_RANGE = key("combat.range", "target_range", "range");
|
||||
public static final CommonSettingSchema COMBAT_REACH_MODE = key("combat.reach_mode");
|
||||
public static final CommonSettingSchema COMBAT_RANGE_INCREMENT = key("combat.range_increment");
|
||||
public static final CommonSettingSchema COMBAT_WALL_RANGE = key("combat.wall_range");
|
||||
public static final CommonSettingSchema COMBAT_FOV = key("combat.fov", "target_fov", "fov");
|
||||
public static final CommonSettingSchema COMBAT_CORRECTION_TYPE = key("combat.correction_type");
|
||||
public static final CommonSettingSchema COMBAT_RAYCAST = key("combat.raycast");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_TARGET_MODE = key("combat.backtrack.target_mode", "target_mode");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_RANGE_MIN = key("combat.backtrack.range_min", "range_min");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_RANGE_MAX = key("combat.backtrack.range_max", "range_max");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_DELAY_MIN = key("combat.backtrack.delay_min", "delay_min");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_DELAY_MAX = key("combat.backtrack.delay_max", "delay_max");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_NEXT_DELAY_MIN = key("combat.backtrack.next_delay_min", "next_delay_min");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_NEXT_DELAY_MAX = key("combat.backtrack.next_delay_max", "next_delay_max");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_TRACKING_BUFFER = key("combat.backtrack.tracking_buffer", "tracking_buffer");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_CHANCE = key("combat.backtrack.chance", "chance");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_PAUSE_ON_HURT_TIME = key("combat.backtrack.pause_on_hurt_time", "pause_on_hurt_time");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_HURT_TIME = key("combat.backtrack.hurt_time", "hurt_time");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_LAST_ATTACK_TIME = key("combat.backtrack.last_attack_time", "last_attack_time");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_RENDER = key("combat.backtrack.render", "render");
|
||||
public static final CommonSettingSchema COMBAT_BACKTRACK_LINE_WIDTH = key("combat.backtrack.line_width", "line_width");
|
||||
public static final CommonSettingSchema COMBAT_WEAPON = key("combat.weapon");
|
||||
public static final CommonSettingSchema COMBAT_OBJECTIVE = key("combat.objective");
|
||||
public static final CommonSettingSchema COMBAT_ON_ITEM_USE = key("combat.on_item_use");
|
||||
public static final CommonSettingSchema COMBAT_CRYSTAL_DISTANCE = key("combat.crystal_distance");
|
||||
public static final CommonSettingSchema COMBAT_BREAK_SHIELDS = key("combat.break_shields");
|
||||
public static final CommonSettingSchema INTERACTION_IGNORE_OPEN_INVENTORY = key("interaction.ignore_open_inventory", "ignore_open_inventory");
|
||||
public static final CommonSettingSchema COMBAT_ONLY_PLAYERS = key("combat.only_players");
|
||||
public static final CommonSettingSchema COMBAT_ONLY_BLOCKING = key("combat.only_blocking");
|
||||
public static final CommonSettingSchema COMBAT_MIN_FALL_DISTANCE = key("combat.min_fall_distance", "min_fall_distance");
|
||||
public static final CommonSettingSchema COMBAT_RESPECT_COOLDOWN = key("combat.respect_cooldown");
|
||||
public static final CommonSettingSchema ITEMS_PROJECTILES = key("items.projectiles");
|
||||
public static final CommonSettingSchema ITEMS_SAVE_UNENCHANTED = key("items.save_unenchanted");
|
||||
//Placement
|
||||
public static final CommonSettingSchema PLACEMENT_RANGE = key("placement.range", "place_range");
|
||||
public static final CommonSettingSchema PLACEMENT_WALL_RANGE = key("placement.wall_range", "wall_range");
|
||||
public static final CommonSettingSchema PLACEMENT_BREAK_RANGE = key("placement.break_range", "break_range");
|
||||
public static final CommonSettingSchema PLACEMENT_BREAK_WALL_RANGE = key("placement.break_wall_range", "break_wall_range");
|
||||
public static final CommonSettingSchema PLACEMENT_MODE = key("placement.mode", "placement_mode");
|
||||
public static final CommonSettingSchema PLACEMENT_SPEED = key("placement.speed", "placement_speed");
|
||||
public static final CommonSettingSchema PLACEMENT_DELAY = key("placement.delay", "place_delay");
|
||||
public static final CommonSettingSchema PLACEMENT_BREAK_DELAY = key("placement.break_delay", "break_delay", "explode_delay");
|
||||
public static final CommonSettingSchema PLACEMENT_PREDICTION = key("placement.prediction", "predict_ticks");
|
||||
public static final CommonSettingSchema PLACEMENT_RENDER = key("placement.render", "render");
|
||||
public static final CommonSettingSchema PLACEMENT_RENDER_MODE = key("placement.render_mode", "render_mode");
|
||||
public static final CommonSettingSchema PLACEMENT_ROTATION_TIMING = key("placement.rotation_timing", "rotation.rotation_timing", "rotation_timing");
|
||||
public static final CommonSettingSchema PLACEMENT_MOVEMENT_CORRECTION = key("placement.movement_correction", "rotation.movement_correction", "movement_correction");
|
||||
public static final CommonSettingSchema PLACEMENT_ROTATION_RESET_TICKS = key("placement.rotation_reset_ticks", "rotation.rotation_reset_ticks", "rotation_reset_ticks");
|
||||
public static final CommonSettingSchema PLACEMENT_ROTATION_RESET_THRESHOLD = key("placement.rotation_reset_threshold", "rotation.rotation_reset_threshold", "rotation_reset_threshold");
|
||||
|
||||
public static final CommonSettingSchema PLAYER_HEALTH_THRESHOLD = key("player.health_threshold", "pause_health", "health_threshold");
|
||||
public static final CommonSettingSchema PLAYER_ELYTRA_HEALTH = key("player.elytra_health");
|
||||
public static final CommonSettingSchema PLAYER_FALL_CHECK = key("player.fall_check");
|
||||
public static final CommonSettingSchema PLAYER_USE_RELATIONS = key("player.use_relations");
|
||||
public static final CommonSettingSchema TOTEM_POP_COUNTER = key("totem_pop.counter", "totem_pop_counter");
|
||||
public static final CommonSettingSchema TOTEM_POP_RESET_SECONDS = key("totem_pop.reset_seconds", "totem_pop_reset_seconds");
|
||||
public static final CommonSettingSchema PLAYER_FAKELAG_MODE = key("player.fakelag.mode");
|
||||
public static final CommonSettingSchema PLAYER_FAKELAG_RANGE_MIN = key("player.fakelag.range_min", "min_range", "range_min");
|
||||
public static final CommonSettingSchema PLAYER_FAKELAG_RANGE_MAX = key("player.fakelag.range_max", "max_range", "range_max");
|
||||
public static final CommonSettingSchema PLAYER_FAKELAG_DELAY_MIN = key("player.fakelag.delay_min", "delay_min");
|
||||
public static final CommonSettingSchema PLAYER_FAKELAG_DELAY_MAX = key("player.fakelag.delay_max", "delay_max");
|
||||
public static final CommonSettingSchema PLAYER_FAKELAG_RECOIL_TIME = key("player.fakelag.recoil_time", "recoil_time");
|
||||
public static final FakeLagFlushOn PLAYER_FAKELAG_FLUSH_ON = new FakeLagFlushOn();
|
||||
// Elytra target / fireworks
|
||||
public static final CommonSettingSchema ELYTRA_HITBOX_EXPAND = key("elytra.hitbox_expand");
|
||||
public static final CommonSettingSchema ELYTRA_EXPAND_WHEN_READY = key("elytra.expand_when_ready");
|
||||
public static final CommonSettingSchema ELYTRA_FIREWORK_SPEED = key("elytra.firework_speed", "firework_speed");
|
||||
public static final CommonSettingSchema ELYTRA_TARGET_MUST_FLY = key("elytra.target_must_fly");
|
||||
public static final CommonSettingSchema ELYTRA_PREPARE_ROTATIONS = key("elytra.prepare_rotations", "prepare_rotations");
|
||||
public static final CommonSettingSchema ELYTRA_VELOCITY_TUNE = key("elytra.velocity_tune");
|
||||
public static final CommonSettingSchema ELYTRA_CUSTOM_VELOCITY_TABLE = key("elytra.custom_velocity_table");
|
||||
public static final CommonSettingSchema ELYTRA_FIREWORK_SILENT_SWAP = key("elytra.firework_silent_swap", "silent_swap", "firework_silent_swap");
|
||||
// ESP / world scan
|
||||
public static final CommonSettingSchema ESP_SCAN_MODE = key("esp.scan_mode");
|
||||
public static final CommonSettingSchema ESP_LIMIT_DISTANCE = key("esp.limit_distance");
|
||||
public static final CommonSettingSchema ESP_MAX_DISTANCE = key("esp.max_distance", "max_distance");
|
||||
public static final CommonSettingSchema ESP_SCAN_DELAY = key("esp.scan_delay", "scan_delay");
|
||||
public static final CommonSettingSchema ESP_MAX_TARGETS = key("esp.max_targets", "max_targets");
|
||||
public static final CommonSettingSchema ESP_USE_TRACERS = key("esp.use_tracers");
|
||||
public static final CommonSettingSchema ESP_LINE_WIDTH = key("esp.line_width", "line_width");
|
||||
public static final CommonSettingSchema ESP_OUTLINE_SHAPE = key("esp.outline_shape", "outline_shape");
|
||||
public static final CommonSettingSchema ESP_BOX_MODE = key("esp.box_mode");
|
||||
public static final CommonSettingSchema ESP_HEALTH_BAR = key("esp.health_bar");
|
||||
public static final CommonSettingSchema ESP_HEALTH_BAR_GRADIENT = key("esp.health_bar_gradient");
|
||||
public static final CommonSettingSchema ESP_HEALTH_BAR_DISTANCE = key("esp.health_bar_distance", "health_bar_distance");
|
||||
// AngleSmooth generic
|
||||
public static final CommonSettingSchema ANGLESMOOTH_HORIZONTAL_MIN = key("rotation.anglesmooth.horizontal_min");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_HORIZONTAL_MAX = key("rotation.anglesmooth.horizontal_max");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_VERTICAL_MIN = key("rotation.anglesmooth.vertical_min");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_VERTICAL_MAX = key("rotation.anglesmooth.vertical_max");
|
||||
// Sigmoid
|
||||
public static final CommonSettingSchema ANGLESMOOTH_STEEPNESS = key("rotation.anglesmooth.steepness");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_MIDPOINT = key("rotation.anglesmooth.midpoint");
|
||||
// Smart
|
||||
public static final CommonSettingSchema ANGLESMOOTH_YAW_MIN = key("rotation.anglesmooth.yaw_min");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_YAW_MAX = key("rotation.anglesmooth.yaw_max");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_PITCH_MIN = key("rotation.anglesmooth.pitch_min");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_PITCH_MAX = key("rotation.anglesmooth.pitch_max");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_SNAP_THRESHOLD = key("rotation.anglesmooth.snap_threshold");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_JITTER_YAW = key("rotation.anglesmooth.jitter_yaw");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_JITTER_PITCH = key("rotation.anglesmooth.jitter_pitch");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_DECELERATE_ENABLED = key("rotation.anglesmooth.decelerate_enabled");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_DECELERATE_ANGLE = key("rotation.anglesmooth.decelerate_angle");
|
||||
public static final CommonSettingSchema ANGLESMOOTH_DECELERATE_MIN_FACTOR = key("rotation.anglesmooth.decelerate_min_factor");
|
||||
// Lazy aim
|
||||
public static final CommonSettingSchema LAZY_AIM_ENABLED = key("rotation.lazy_aim.enabled");
|
||||
public static final CommonSettingSchema LAZY_AIM_THRESHOLD = key("rotation.lazy_aim.threshold");
|
||||
public static final CommonSettingSchema LAZY_AIM_FOLLOW_FACTOR = key("rotation.lazy_aim.follow_factor");
|
||||
// Shake aim
|
||||
public static final CommonSettingSchema SHAKE_AIM_ENABLED = key("rotation.shake_aim.enabled");
|
||||
public static final CommonSettingSchema SHAKE_AIM_YAW_AMPLITUDE = key("rotation.shake_aim.yaw_amplitude");
|
||||
public static final CommonSettingSchema SHAKE_AIM_PITCH_AMPLITUDE = key("rotation.shake_aim.pitch_amplitude");
|
||||
public static final CommonSettingSchema SHAKE_AIM_SPEED = key("rotation.shake_aim.speed");
|
||||
// Fail
|
||||
public static final CommonSettingSchema FAIL_ENABLED = key("rotation.fail.enabled");
|
||||
public static final CommonSettingSchema FAIL_RATE = key("rotation.fail.rate");
|
||||
public static final CommonSettingSchema FAIL_FACTOR = key("rotation.fail.factor");
|
||||
public static final CommonSettingSchema FAIL_STRENGTH_HORIZONTAL_MIN = key("rotation.fail.strength_horizontal_min");
|
||||
public static final CommonSettingSchema FAIL_STRENGTH_HORIZONTAL_MAX = key("rotation.fail.strength_horizontal_max");
|
||||
public static final CommonSettingSchema FAIL_STRENGTH_VERTICAL_MIN = key("rotation.fail.strength_vertical_min");
|
||||
public static final CommonSettingSchema FAIL_STRENGTH_VERTICAL_MAX = key("rotation.fail.strength_vertical_max");
|
||||
public static final CommonSettingSchema FAIL_TRANSITION_MIN = key("rotation.fail.transition_min");
|
||||
public static final CommonSettingSchema FAIL_TRANSITION_MAX = key("rotation.fail.transition_max");
|
||||
public static final CommonSettingSchema ANTICHEAT_MODE = key("anticheat.mode");
|
||||
public static final CommonSettingSchema RENDER_COLOR_MODE = key("render.color_mode", "color_mode");
|
||||
public static final CommonSettingSchema RENDER_COLOR_SPEED = key("render.color_speed", "color_speed");
|
||||
public static final CommonSettingSchema RENDER_PRIMARY_COLOR = key("render.primary_color", "primary_color");
|
||||
public static final CommonSettingSchema RENDER_SECONDARY_COLOR = key("render.secondary_color", "secondary_color");
|
||||
public static final CommonSettingSchema RENDER_DEPTH_TEST = key("render.depth_test", "depth_test");
|
||||
public static final CommonSettingSchema RENDER_SCALE = key("render.scale", "scale");
|
||||
|
||||
private static CommonSettingSchema key(String key, String... aliases) {
|
||||
return new CommonKey(key, aliases);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.common;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class CombatPriority implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "combat.priority";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.common;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonBooleanGroupSchema;
|
||||
import dev.loki.lovisual.util.combat.protocol.heuristics.CombatProtocolHeuristics;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public final class CombatProtocolHeuristicSources implements CommonBooleanGroupSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "combat.protocol_heuristics";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Boolean> defaults() {
|
||||
return CombatProtocolHeuristics.defaultSourceToggles();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.common;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class CommonKey implements CommonSettingSchema {
|
||||
private final List<String> keys;
|
||||
|
||||
public CommonKey(String key, String... aliases) {
|
||||
ArrayList<String> out = new ArrayList<>();
|
||||
add(out, key);
|
||||
if (aliases != null) {
|
||||
for (String alias : aliases) {
|
||||
add(out, alias);
|
||||
}
|
||||
}
|
||||
this.keys = List.copyOf(out);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return keys.isEmpty() ? null : keys.get(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> commonI18nKeys() {
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static void add(ArrayList<String> out, String key) {
|
||||
if (key == null) return;
|
||||
String normalized = key.trim();
|
||||
if (!normalized.isBlank() && !out.contains(normalized)) {
|
||||
out.add(normalized);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.common;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonBooleanGroupSchema;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class FakeLagFlushOn implements CommonBooleanGroupSchema {
|
||||
public static final String ENTITY_INTERACT = "entity_interact";
|
||||
public static final String BLOCK_INTERACT = "block_interact";
|
||||
public static final String ACTION = "action";
|
||||
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "fakelag.flush_on";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Boolean> defaults() {
|
||||
Map<String, Boolean> defaults = new LinkedHashMap<>();
|
||||
defaults.put(ENTITY_INTERACT, false);
|
||||
defaults.put(BLOCK_INTERACT, false);
|
||||
defaults.put(ACTION, false);
|
||||
return defaults;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.rotation;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class RotationMode implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "rotation.rotation_mode";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.rotation;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class RotationMovementCorrection implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "rotation.movement_correction";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.rotation;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class RotationResetThreshold implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "rotation.rotation_reset_threshold";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.rotation;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class RotationResetTicks implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "rotation.rotation_reset_ticks";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.wall;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class RotationThroughWalls implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "rotation.rotation_through_walls";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.wall;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
|
||||
public final class RotationTiming implements CommonSettingSchema {
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "rotation.rotation_timing";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.common.impl.wall;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonBooleanGroupSchema;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class TargetFilters implements CommonBooleanGroupSchema {
|
||||
|
||||
public static final String PLAYERS_ONLY = "players_only";
|
||||
public static final String IGNORE_FRIENDS = "ignore_friends";
|
||||
public static final String IGNORE_STAFF = "ignore_staff";
|
||||
public static final String IGNORE_ENEMIES = "ignore_enemies";
|
||||
public static final String IGNORE_NAKED = "ignore_naked";
|
||||
public static final String IGNORE_ENTITIES = "ignore_entities";
|
||||
public static final String VISIBLE_ONLY = "visible_only";
|
||||
|
||||
@Override
|
||||
public String commonI18nKey() {
|
||||
return "target";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Boolean> defaults() {
|
||||
Map<String, Boolean> defaults = new LinkedHashMap<>();
|
||||
defaults.put(PLAYERS_ONLY, true);
|
||||
defaults.put(IGNORE_FRIENDS, true);
|
||||
defaults.put(IGNORE_STAFF, true);
|
||||
defaults.put(IGNORE_ENEMIES, false);
|
||||
defaults.put(IGNORE_NAKED, false);
|
||||
defaults.put(IGNORE_ENTITIES, false);
|
||||
defaults.put(VISIBLE_ONLY, false);
|
||||
return defaults;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.definition;
|
||||
|
||||
/**
|
||||
* Optional stable config name override (used for file names).
|
||||
*/
|
||||
public interface ConfigNameProvider {
|
||||
String getConfigName();
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.definition;
|
||||
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ConfigObject {
|
||||
List<ConfigValue<?>> getConfigValues();
|
||||
}
|
||||
|
|
@ -0,0 +1,385 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.definition;
|
||||
|
||||
import dev.loki.lovisual.config.common.CommonSettingSchema;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.collection.ItemCooldownRulesValue;
|
||||
import dev.loki.lovisual.config.values.collection.ItemIdSetValue;
|
||||
import dev.loki.lovisual.config.values.collection.SetValue;
|
||||
import dev.loki.lovisual.config.values.color.KeyBindValue;
|
||||
import dev.loki.lovisual.config.values.color.RGBAColorValue;
|
||||
import dev.loki.lovisual.config.values.color.RGBColorValue;
|
||||
import dev.loki.lovisual.config.values.mode.BindMode;
|
||||
import dev.loki.lovisual.config.values.mode.EnumValue;
|
||||
import dev.loki.lovisual.config.values.mode.ModeValue;
|
||||
import dev.loki.lovisual.config.values.primitive.BooleanMapValue;
|
||||
import dev.loki.lovisual.config.values.primitive.BooleanValue;
|
||||
import dev.loki.lovisual.config.values.primitive.NumberValue;
|
||||
import dev.loki.lovisual.config.values.primitive.StringValue;
|
||||
import dev.loki.lovisual.features.gui.clickgui.settings.text.list.TextListSetting;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
import dev.loki.lovisual.config.i18n.DisableSettingI18n;
|
||||
|
||||
/**
|
||||
* GUI-neutral setting descriptor. UI layer can build actual widgets from these.
|
||||
*/
|
||||
public final class SettingDef {
|
||||
|
||||
private final Kind kind;
|
||||
private final String id;
|
||||
private final ConfigValue<?> value;
|
||||
private final BindMode bindMode;
|
||||
private final TextListSetting.PickerMode pickerMode;
|
||||
private Supplier<Boolean> visibility;
|
||||
private Supplier<String> unavailableReason;
|
||||
private final List<String> commonI18nKeys = new ArrayList<>();
|
||||
private boolean i18nNameEnabled = true;
|
||||
private boolean i18nOptionsEnabled = true;
|
||||
private SettingDef(Kind kind, String id, ConfigValue<?> value) {
|
||||
this(kind, id, value, null, null);
|
||||
}
|
||||
|
||||
private SettingDef(Kind kind, String id, ConfigValue<?> value, BindMode bindMode) {
|
||||
this(kind, id, value, bindMode, null);
|
||||
}
|
||||
|
||||
private SettingDef(Kind kind,
|
||||
String id,
|
||||
ConfigValue<?> value,
|
||||
BindMode bindMode,
|
||||
TextListSetting.PickerMode pickerMode) {
|
||||
this.kind = kind;
|
||||
this.id = id;
|
||||
this.value = value;
|
||||
this.bindMode = bindMode;
|
||||
this.pickerMode = pickerMode;
|
||||
}
|
||||
|
||||
public static SettingDef bool(String id, BooleanValue value) {
|
||||
return new SettingDef(Kind.BOOLEAN, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef bool(BooleanValue value) {
|
||||
return new SettingDef(Kind.BOOLEAN, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef number(String id, NumberValue<?> value) {
|
||||
return new SettingDef(Kind.NUMBER, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef number(NumberValue<?> value) {
|
||||
return new SettingDef(Kind.NUMBER, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef mode(String id, ModeValue value) {
|
||||
return new SettingDef(Kind.MODE, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef mode(String id, EnumValue<?> value) {
|
||||
return new SettingDef(Kind.MODE, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef mode(ModeValue value) {
|
||||
return new SettingDef(Kind.MODE, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef mode(EnumValue<?> value) {
|
||||
return new SettingDef(Kind.MODE, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef color(String id, RGBAColorValue value) {
|
||||
return new SettingDef(Kind.COLOR, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef color(RGBAColorValue value) {
|
||||
return new SettingDef(Kind.COLOR, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef colorNoAlpha(String id, RGBColorValue value) {
|
||||
return new SettingDef(Kind.COLOR_NO_ALPHA, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef colorNoAlpha(RGBColorValue value) {
|
||||
return new SettingDef(Kind.COLOR_NO_ALPHA, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef text(String id, StringValue value) {
|
||||
return new SettingDef(Kind.TEXT, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef text(StringValue value) {
|
||||
return new SettingDef(Kind.TEXT, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef textList(String id, SetValue value) {
|
||||
return new SettingDef(Kind.TEXT_LIST, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef textList(String id,
|
||||
SetValue value,
|
||||
TextListSetting.PickerMode pickerMode) {
|
||||
return new SettingDef(Kind.TEXT_LIST, id, value, null, pickerMode);
|
||||
}
|
||||
|
||||
public static SettingDef textList(SetValue value) {
|
||||
return new SettingDef(Kind.TEXT_LIST, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef textList(SetValue value,
|
||||
TextListSetting.PickerMode pickerMode) {
|
||||
return new SettingDef(Kind.TEXT_LIST, value.getName(), value, null, pickerMode);
|
||||
}
|
||||
|
||||
public static SettingDef textList(String id, ItemIdSetValue value) {
|
||||
return new SettingDef(Kind.TEXT_LIST, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef textList(String id,
|
||||
ItemIdSetValue value,
|
||||
TextListSetting.PickerMode pickerMode) {
|
||||
return new SettingDef(Kind.TEXT_LIST, id, value, null, pickerMode);
|
||||
}
|
||||
|
||||
public static SettingDef textList(ItemIdSetValue value) {
|
||||
return new SettingDef(Kind.TEXT_LIST, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef textList(ItemIdSetValue value,
|
||||
TextListSetting.PickerMode pickerMode) {
|
||||
return new SettingDef(Kind.TEXT_LIST, value.getName(), value, null, pickerMode);
|
||||
}
|
||||
|
||||
public static SettingDef cooldownRules(String id, ItemCooldownRulesValue value) {
|
||||
return new SettingDef(Kind.COOLDOWN_RULES, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef cooldownRules(ItemCooldownRulesValue value) {
|
||||
return new SettingDef(Kind.COOLDOWN_RULES, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef protocolHeuristics(String id, BooleanMapValue value) {
|
||||
return new SettingDef(Kind.PROTOCOL_HEURISTICS, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef protocolHeuristics(BooleanMapValue value) {
|
||||
return new SettingDef(Kind.PROTOCOL_HEURISTICS, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef group(String id, BooleanMapValue value) {
|
||||
return new SettingDef(Kind.GROUP, id, value);
|
||||
}
|
||||
|
||||
public static SettingDef group(BooleanMapValue value) {
|
||||
return new SettingDef(Kind.GROUP, value.getName(), value);
|
||||
}
|
||||
|
||||
public static SettingDef bind(String id, KeyBindValue value, BindMode mode) {
|
||||
return new SettingDef(Kind.BIND, id, value, mode);
|
||||
}
|
||||
|
||||
public static SettingDef bind(KeyBindValue value, BindMode mode) {
|
||||
return new SettingDef(Kind.BIND, value.getName(), value, mode);
|
||||
}
|
||||
|
||||
public static SettingDef bind(String id, KeyBindValue value) {
|
||||
return new SettingDef(Kind.BIND, id, value, BindMode.PRESS);
|
||||
}
|
||||
|
||||
public static SettingDef bind(KeyBindValue value) {
|
||||
return new SettingDef(Kind.BIND, value.getName(), value, BindMode.PRESS);
|
||||
}
|
||||
|
||||
public static void applyI18nAnnotations(Object owner, Iterable<SettingDef> defs) {
|
||||
if (owner == null || defs == null) return;
|
||||
|
||||
Map<ConfigValue<?>, SettingDef> defsByValue = new IdentityHashMap<>();
|
||||
for (SettingDef def : defs) {
|
||||
if (def != null && def.value() != null) {
|
||||
defsByValue.put(def.value(), def);
|
||||
}
|
||||
}
|
||||
if (defsByValue.isEmpty()) return;
|
||||
|
||||
Class<?> type = owner.getClass();
|
||||
while (type != null && type != Object.class) {
|
||||
for (Field field : type.getDeclaredFields()) {
|
||||
DisableSettingI18n annotation = field.getAnnotation(DisableSettingI18n.class);
|
||||
if (annotation == null) continue;
|
||||
if (!ConfigValue.class.isAssignableFrom(field.getType())) continue;
|
||||
|
||||
boolean accessible = field.canAccess(owner);
|
||||
try {
|
||||
if (!accessible) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
if (field.get(owner) instanceof ConfigValue<?> value) {
|
||||
SettingDef def = defsByValue.get(value);
|
||||
if (def != null) {
|
||||
def.disableI18n(annotation.name(), annotation.options());
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
} finally {
|
||||
if (!accessible) {
|
||||
try {
|
||||
field.setAccessible(false);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
type = type.getSuperclass();
|
||||
}
|
||||
}
|
||||
|
||||
public Kind kind() {
|
||||
return kind;
|
||||
}
|
||||
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public ConfigValue<?> value() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public BindMode bindMode() {
|
||||
return bindMode;
|
||||
}
|
||||
|
||||
public TextListSetting.PickerMode pickerMode() {
|
||||
return pickerMode;
|
||||
}
|
||||
|
||||
public Supplier<Boolean> visibility() {
|
||||
return visibility;
|
||||
}
|
||||
|
||||
public Supplier<String> unavailableReason() {
|
||||
return unavailableReason;
|
||||
}
|
||||
|
||||
public String commonI18nKey() {
|
||||
return commonI18nKeys.isEmpty() ? null : commonI18nKeys.get(0);
|
||||
}
|
||||
|
||||
public List<String> commonI18nKeys() {
|
||||
return List.copyOf(commonI18nKeys);
|
||||
}
|
||||
|
||||
public boolean i18nNameEnabled() {
|
||||
return i18nNameEnabled;
|
||||
}
|
||||
|
||||
public boolean i18nOptionsEnabled() {
|
||||
return i18nOptionsEnabled;
|
||||
}
|
||||
|
||||
public SettingDef visibleWhen(Supplier<Boolean> supplier) {
|
||||
this.visibility = supplier;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SettingDef unavailableWhen(Supplier<Boolean> supplier, String reason) {
|
||||
return unavailableWhen(supplier, () -> reason);
|
||||
}
|
||||
|
||||
public SettingDef unavailableWhen(Supplier<Boolean> supplier, Supplier<String> reason) {
|
||||
if (supplier == null) {
|
||||
this.unavailableReason = null;
|
||||
return this;
|
||||
}
|
||||
this.unavailableReason = () -> {
|
||||
boolean unavailable;
|
||||
try {
|
||||
unavailable = supplier.get();
|
||||
} catch (Exception ignored) {
|
||||
unavailable = false;
|
||||
}
|
||||
if (!unavailable) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return reason == null ? "" : reason.get();
|
||||
} catch (Exception ignored) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
return this;
|
||||
}
|
||||
|
||||
public SettingDef availableWhen(Supplier<Boolean> supplier, String reasonWhenUnavailable) {
|
||||
return availableWhen(supplier, () -> reasonWhenUnavailable);
|
||||
}
|
||||
|
||||
public SettingDef availableWhen(Supplier<Boolean> supplier, Supplier<String> reasonWhenUnavailable) {
|
||||
if (supplier == null) {
|
||||
this.unavailableReason = null;
|
||||
return this;
|
||||
}
|
||||
return unavailableWhen(() -> !supplier.get(), reasonWhenUnavailable);
|
||||
}
|
||||
|
||||
public SettingDef common(String key) {
|
||||
addCommonKey(key);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SettingDef common(CommonSettingSchema schema) {
|
||||
if (schema != null) {
|
||||
for (String key : schema.commonI18nKeys()) {
|
||||
addCommonKey(key);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private void addCommonKey(String key) {
|
||||
if (key == null) return;
|
||||
String normalized = key.trim();
|
||||
if (!normalized.isBlank() && !commonI18nKeys.contains(normalized)) {
|
||||
commonI18nKeys.add(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
public SettingDef disableI18n(boolean name, boolean options) {
|
||||
if (name) {
|
||||
this.i18nNameEnabled = false;
|
||||
}
|
||||
if (options) {
|
||||
this.i18nOptionsEnabled = false;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public enum Kind {
|
||||
BOOLEAN,
|
||||
NUMBER,
|
||||
MODE,
|
||||
COLOR,
|
||||
COLOR_NO_ALPHA,
|
||||
TEXT,
|
||||
TEXT_LIST,
|
||||
COOLDOWN_RULES,
|
||||
PROTOCOL_HEURISTICS,
|
||||
GROUP,
|
||||
BIND
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.definition;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
|
||||
/**
|
||||
* Owner of GUI settings. Allows settings to save config and build i18n keys
|
||||
* without tying them to Module.
|
||||
*/
|
||||
public interface SettingOwner {
|
||||
String name();
|
||||
|
||||
void saveConfig();
|
||||
|
||||
default String getTranslationKeyPrefix() {
|
||||
String name = name();
|
||||
if (name == null || name.isBlank()) return null;
|
||||
return "setting." + name;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.i18n;
|
||||
|
||||
import net.minecraft.client.resources.language.I18n;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public enum ConfigLang {
|
||||
;
|
||||
|
||||
public static String getName(ConfigValue<?> v) {
|
||||
String key = "config." + v.getName() + ".name";
|
||||
return translateOrFallback(key, v.getName());
|
||||
}
|
||||
|
||||
public static String getDesc(ConfigValue<?> v) {
|
||||
String key = "config." + v.getName() + ".desc";
|
||||
return translateOrFallback(key, "");
|
||||
}
|
||||
|
||||
private static String translateOrFallback(String key, String fallback) {
|
||||
String translated = I18n.get(key);
|
||||
return translated.equals(key) ? fallback : translated;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.i18n;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ConfigValueAliasProvider {
|
||||
List<String> getLegacyValueNames(String currentValueName);
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.i18n;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Opts a setting out of i18n lookup. Use this for user/content values where raw ids
|
||||
* are the intended labels, for example selectable sound ids.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface DisableSettingI18n {
|
||||
boolean name() default true;
|
||||
|
||||
boolean options() default true;
|
||||
}
|
||||
301
mod/src/main/java/dev/loki/lovisual/config/i18n/MainConfig.java
Normal file
301
mod/src/main/java/dev/loki/lovisual/config/i18n/MainConfig.java
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.i18n;
|
||||
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.collection.SetValue;
|
||||
import dev.loki.lovisual.config.values.mode.EnumValue;
|
||||
import dev.loki.lovisual.config.values.mode.ModeValue;
|
||||
import dev.loki.lovisual.config.values.primitive.BooleanValue;
|
||||
import dev.loki.lovisual.config.values.primitive.NumberValue;
|
||||
import dev.loki.lovisual.render.iris.runtime.IrisRuntime;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
import dev.loki.lovisual.util.logging.DebugMode;
|
||||
import net.minecraft.client.resources.language.I18n;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import dev.loki.lovisual.config.definition.ConfigNameProvider;
|
||||
import dev.loki.lovisual.config.definition.ConfigObject;
|
||||
import dev.loki.lovisual.config.definition.SettingDef;
|
||||
import dev.loki.lovisual.config.definition.SettingOwner;
|
||||
import dev.loki.lovisual.config.io.ConfigSerializer;
|
||||
|
||||
public final class MainConfig implements ConfigObject, ConfigNameProvider, SettingOwner {
|
||||
|
||||
public static final MainConfig INSTANCE = new MainConfig();
|
||||
private static final String IRIS_MSAA_REASON_KEY = "setting.main_config.msaa3d.iris_blocked";
|
||||
private static final String IRIS_MSAA_REASON_FALLBACK = "Iris shaderpack pipeline is active.";
|
||||
|
||||
//@CFGComment("Debug logging mode: off / error_only / error_and_warnings / info / config / render_thread / stencil / serverdebug / all")
|
||||
private final ModeValue debug =
|
||||
new ModeValue("debug", "off", "off", "error_only", "error_and_warnings", "info", "config", "render_thread", "stencil", "serverdebug", "all");
|
||||
|
||||
//@CFGComment("Menu background shader: off / waves / aurora")
|
||||
private final ModeValue menuBg =
|
||||
new ModeValue("menuBg", "waves", "off", "waves", "aurora");
|
||||
|
||||
//@CFGComment("Use ClickGUI theme colors for menu background shader")
|
||||
private final BooleanValue menuBgUseTheme =
|
||||
new BooleanValue("menuBgUseTheme", true);
|
||||
|
||||
//@CFGComment("Show seconds in the custom main menu clock")
|
||||
private final BooleanValue menuClockShowSeconds =
|
||||
new BooleanValue("menuClockShowSeconds", true);
|
||||
|
||||
//@CFGComment("MSAA for world render: off / 2x / 4x")
|
||||
private final ModeValue msaa3d =
|
||||
new ModeValue("msaa3d", "off", "off", "2x", "4x");
|
||||
|
||||
//@CFGComment("Show ClickGUI modules hotkey hints")
|
||||
private final BooleanValue clickGuiModulesHints =
|
||||
new BooleanValue("clickGuiModulesHints", true);
|
||||
|
||||
//@CFGComment("Show ClickGUI HUD editor hotkey hints")
|
||||
private final BooleanValue clickGuiHudEditorHints =
|
||||
new BooleanValue("clickGuiHudEditorHints", true);
|
||||
|
||||
//@CFGComment("Hard-disable narrator and narrator hotkey")
|
||||
private final BooleanValue disableNarrator =
|
||||
new BooleanValue("disableNarrator", true);
|
||||
|
||||
//@CFGComment("Always-on backdoor protection master switch")
|
||||
private final BooleanValue backdoorProtection =
|
||||
new BooleanValue("backdoorProtection", true);
|
||||
|
||||
//@CFGComment("Filter non-whitelisted translation keys in server-controlled sign/anvil text")
|
||||
private final BooleanValue backdoorTranslationFilter =
|
||||
new BooleanValue("backdoorTranslationFilter", true);
|
||||
|
||||
//@CFGComment("Filter non-vanilla keybind text keys in server-controlled text")
|
||||
private final BooleanValue backdoorKeybindFilter =
|
||||
new BooleanValue("backdoorKeybindFilter", true);
|
||||
|
||||
//@CFGComment("Block remote servers from redirecting resource-pack downloads into local/private network addresses")
|
||||
private final BooleanValue backdoorLocalHttpGuard =
|
||||
new BooleanValue("backdoorLocalHttpGuard", true);
|
||||
|
||||
//@CFGComment("Isolate downloaded server-pack cache by account UUID to reduce pack-cache fingerprinting")
|
||||
private final BooleanValue backdoorPackCacheIsolation =
|
||||
new BooleanValue("backdoorPackCacheIsolation", true);
|
||||
|
||||
//@CFGComment("Allow local/private HTTP requests when connected to local/integrated server")
|
||||
private final BooleanValue backdoorAllowLocalHttpWhenServerLocal =
|
||||
new BooleanValue("backdoorAllowLocalHttpWhenServerLocal", true);
|
||||
|
||||
//@CFGComment("Extra allowed translation resource-pack ids for server-controlled text")
|
||||
private final SetValue backdoorAllowedTranslationPacks =
|
||||
new SetValue("backdoorAllowedTranslationPacks", defaultAllowedTranslationPacks());
|
||||
|
||||
//@CFGComment("Extra allowed keybind ids for server-controlled text")
|
||||
private final SetValue backdoorAllowedKeybinds =
|
||||
new SetValue("backdoorAllowedKeybinds");
|
||||
|
||||
private MainConfig() {
|
||||
ConfigSerializer.load(this);
|
||||
applyDebugMode();
|
||||
}
|
||||
|
||||
public static MainConfig get() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private static Set<String> defaultAllowedTranslationPacks() {
|
||||
LinkedHashSet<String> out = new LinkedHashSet<>();
|
||||
out.add("vanilla");
|
||||
return out;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getConfigName() {
|
||||
return "mainconfig";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "main_config";
|
||||
}
|
||||
|
||||
// ================= DEBUG =================
|
||||
|
||||
@Override
|
||||
public void saveConfig() {
|
||||
applyDebugMode();
|
||||
ConfigSerializer.requestSave(this);
|
||||
}
|
||||
|
||||
public DebugMode getDebugMode() {
|
||||
try {
|
||||
return DebugMode.valueOf(debug.get().toUpperCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return DebugMode.OFF;
|
||||
}
|
||||
}
|
||||
|
||||
public void setDebugMode(DebugMode mode) {
|
||||
if (mode == null) mode = DebugMode.OFF;
|
||||
debug.set(mode.name().toLowerCase());
|
||||
applyDebugMode();
|
||||
ConfigSerializer.requestSave(this);
|
||||
}
|
||||
|
||||
private void applyDebugMode() {
|
||||
DebugLog.setMode(getDebugMode());
|
||||
}
|
||||
|
||||
public String getMenuBackgroundMode() {
|
||||
return menuBg.get();
|
||||
}
|
||||
|
||||
public boolean isMenuBackgroundUseTheme() {
|
||||
return menuBgUseTheme.get();
|
||||
}
|
||||
|
||||
public boolean isMenuClockShowSeconds() {
|
||||
return menuClockShowSeconds.get();
|
||||
}
|
||||
|
||||
public int getMsaa3dSamples() {
|
||||
if (IrisRuntime.isShaderpackRendererActive()) return 0;
|
||||
String v = msaa3d.get();
|
||||
if (v == null) return 0;
|
||||
if (v.equalsIgnoreCase("2x")) return 2;
|
||||
if (v.equalsIgnoreCase("4x")) return 4;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public boolean isClickGuiModulesHintsEnabled() {
|
||||
return clickGuiModulesHints.get();
|
||||
}
|
||||
|
||||
public boolean isClickGuiHintsEnabled() {
|
||||
return clickGuiModulesHints.get();
|
||||
}
|
||||
|
||||
public void setClickGuiModulesHintsEnabled(boolean enabled) {
|
||||
clickGuiModulesHints.set(enabled);
|
||||
ConfigSerializer.requestSave(this);
|
||||
}
|
||||
|
||||
public void setClickGuiHintsEnabled(boolean enabled) {
|
||||
setClickGuiModulesHintsEnabled(enabled);
|
||||
}
|
||||
|
||||
public boolean isClickGuiHudEditorHintsEnabled() {
|
||||
return clickGuiHudEditorHints.get();
|
||||
}
|
||||
|
||||
public void setClickGuiHudEditorHintsEnabled(boolean enabled) {
|
||||
clickGuiHudEditorHints.set(enabled);
|
||||
ConfigSerializer.requestSave(this);
|
||||
}
|
||||
|
||||
public List<SettingDef> getImageSettingDefs() {
|
||||
List<SettingDef> list = new ArrayList<>();
|
||||
list.add(SettingDef.mode(msaa3d)
|
||||
.unavailableWhen(IrisRuntime::isShaderpackRendererActive, MainConfig::irisMsaaReason));
|
||||
list.add(SettingDef.mode(menuBg));
|
||||
list.add(SettingDef.bool(menuClockShowSeconds));
|
||||
list.add(SettingDef.bool(menuBgUseTheme));
|
||||
return list;
|
||||
}
|
||||
|
||||
private static String irisMsaaReason() {
|
||||
String translated = I18n.get(IRIS_MSAA_REASON_KEY);
|
||||
return IRIS_MSAA_REASON_KEY.equals(translated) ? IRIS_MSAA_REASON_FALLBACK : translated;
|
||||
}
|
||||
|
||||
public List<SettingDef> getMiscellaneousSettingDefs() {
|
||||
List<SettingDef> list = new ArrayList<>();
|
||||
list.add(SettingDef.mode(debug));
|
||||
list.add(SettingDef.bool(disableNarrator));
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<SettingDef> getSecuritySettingDefs() {
|
||||
List<SettingDef> list = new ArrayList<>();
|
||||
list.add(SettingDef.bool(backdoorProtection));
|
||||
list.add(SettingDef.bool(backdoorTranslationFilter).visibleWhen(backdoorProtection::get));
|
||||
list.add(SettingDef.bool(backdoorKeybindFilter).visibleWhen(backdoorProtection::get));
|
||||
list.add(SettingDef.bool(backdoorLocalHttpGuard).visibleWhen(backdoorProtection::get));
|
||||
list.add(SettingDef.bool(backdoorPackCacheIsolation).visibleWhen(backdoorProtection::get));
|
||||
list.add(SettingDef.bool(backdoorAllowLocalHttpWhenServerLocal).visibleWhen(backdoorProtection::get));
|
||||
list.add(SettingDef.textList(backdoorAllowedTranslationPacks)
|
||||
.visibleWhen(() -> backdoorProtection.get() && backdoorTranslationFilter.get()));
|
||||
list.add(SettingDef.textList(backdoorAllowedKeybinds)
|
||||
.visibleWhen(() -> backdoorProtection.get() && backdoorKeybindFilter.get()));
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<SettingDef> getUtilitySettingDefs() {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
public boolean isNarratorDisabled() {
|
||||
return disableNarrator.get();
|
||||
}
|
||||
|
||||
public boolean isBackdoorProtectionEnabled() {
|
||||
return backdoorProtection.get();
|
||||
}
|
||||
|
||||
public boolean isBackdoorTranslationFilterEnabled() {
|
||||
return backdoorProtection.get() && backdoorTranslationFilter.get();
|
||||
}
|
||||
|
||||
public boolean isBackdoorKeybindFilterEnabled() {
|
||||
return backdoorProtection.get() && backdoorKeybindFilter.get();
|
||||
}
|
||||
|
||||
public boolean isBackdoorLocalHttpGuardEnabled() {
|
||||
return backdoorProtection.get() && backdoorLocalHttpGuard.get();
|
||||
}
|
||||
|
||||
public boolean isBackdoorPackCacheIsolationEnabled() {
|
||||
return backdoorProtection.get() && backdoorPackCacheIsolation.get();
|
||||
}
|
||||
|
||||
public boolean isBackdoorAllowLocalHttpWhenServerLocal() {
|
||||
return backdoorAllowLocalHttpWhenServerLocal.get();
|
||||
}
|
||||
|
||||
public Set<String> getBackdoorAllowedTranslationPacks() {
|
||||
return new LinkedHashSet<>(backdoorAllowedTranslationPacks.get());
|
||||
}
|
||||
|
||||
// ================= CONFIG =================
|
||||
|
||||
public Set<String> getBackdoorAllowedKeybinds() {
|
||||
return new LinkedHashSet<>(backdoorAllowedKeybinds.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ConfigValue<?>> getConfigValues() {
|
||||
List<ConfigValue<?>> list = new ArrayList<>();
|
||||
list.add(debug);
|
||||
list.add(menuBg);
|
||||
list.add(menuClockShowSeconds);
|
||||
list.add(menuBgUseTheme);
|
||||
list.add(msaa3d);
|
||||
list.add(clickGuiModulesHints);
|
||||
list.add(clickGuiHudEditorHints);
|
||||
list.add(disableNarrator);
|
||||
list.add(backdoorProtection);
|
||||
list.add(backdoorTranslationFilter);
|
||||
list.add(backdoorKeybindFilter);
|
||||
list.add(backdoorLocalHttpGuard);
|
||||
list.add(backdoorPackCacheIsolation);
|
||||
list.add(backdoorAllowLocalHttpWhenServerLocal);
|
||||
list.add(backdoorAllowedTranslationPacks);
|
||||
list.add(backdoorAllowedKeybinds);
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.io;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public enum ConfigPaths {
|
||||
;
|
||||
|
||||
// TODO: make the user config root configurable, including base directory and visible folder name.
|
||||
// Keep config/lovisual as the default for compatibility with existing installs.
|
||||
public static Path root() {
|
||||
return Paths.get("config", legacyNamespaceName());
|
||||
}
|
||||
|
||||
public static Path profilesRoot() {
|
||||
return root().resolve("profiles");
|
||||
}
|
||||
|
||||
public static String legacyNamespaceName() {
|
||||
return new String(new char[]{'l', 'o', 'v', 'i', 's', 'u', 'a', 'l'});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,668 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.io;
|
||||
|
||||
import com.google.gson.*;
|
||||
import de.marhali.json5.*;
|
||||
import io.github.classgraph.ClassGraph;
|
||||
import io.github.classgraph.ClassInfo;
|
||||
import io.github.classgraph.ScanResult;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.config.HudGlobalConfig;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.relations.EntityFilters;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import dev.loki.lovisual.config.definition.ConfigNameProvider;
|
||||
import dev.loki.lovisual.config.definition.ConfigObject;
|
||||
import dev.loki.lovisual.config.i18n.ConfigValueAliasProvider;
|
||||
import dev.loki.lovisual.config.io.ConfigPaths;
|
||||
import dev.loki.lovisual.config.io.JsonConfigObject;
|
||||
|
||||
public enum ConfigSerializer {
|
||||
;
|
||||
|
||||
private static final Path CONFIG_DIR = ConfigPaths.root();
|
||||
private static final long SAVE_DEBOUNCE_MS = 220L;
|
||||
private static final ScheduledExecutorService SAVE_EXECUTOR =
|
||||
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "LoVisual-ConfigSaver");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
private static final Object SAVE_LOCK = new Object();
|
||||
private static final Map<Path, String> PENDING_TEXT = new HashMap<>();
|
||||
private static final Map<Path, ScheduledFuture<?>> PENDING_TASKS = new HashMap<>();
|
||||
private static final Map<Path, Long> PENDING_TOKENS = new HashMap<>();
|
||||
// One Json5 instance for utilities (player relations, filters, debug config, etc.)
|
||||
private static final Json5 JSON5 = Json5.builder(builder -> builder
|
||||
.trailingComma() // allow trailing commas
|
||||
.indentFactor(2) // pretty output
|
||||
.quoteSingle() // use " quotes
|
||||
.build()
|
||||
);
|
||||
// Gson serializer for modules (strict JSON)
|
||||
private static final Gson GSON = new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.disableHtmlEscaping()
|
||||
.create();
|
||||
private static long SAVE_TOKEN_SEQ = 0L;
|
||||
|
||||
// =============================================================
|
||||
// Bulk load / save helpers
|
||||
// =============================================================
|
||||
|
||||
@SuppressWarnings("unused") // kept for bulk-loading singletons via ClassGraph
|
||||
public static void loadAll() {
|
||||
try (ScanResult sc = new ClassGraph()
|
||||
.enableClassInfo()
|
||||
.acceptPackages("dev.loki.lovisual")
|
||||
.scan()) {
|
||||
|
||||
for (ClassInfo ci : sc.getClassesImplementing(ConfigObject.class)) {
|
||||
Class<?> cls = ci.loadClass();
|
||||
ConfigObject inst = singletonConfigObjectFor(cls);
|
||||
if (inst != null) {
|
||||
load(inst);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("ConfigSerializer.loadAll failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveAll() {
|
||||
try (ScanResult sc = new ClassGraph()
|
||||
.enableClassInfo()
|
||||
.acceptPackages("dev.loki.lovisual")
|
||||
.scan()) {
|
||||
|
||||
for (ClassInfo ci : sc.getClassesImplementing(ConfigObject.class)) {
|
||||
Class<?> cls = ci.loadClass();
|
||||
ConfigObject inst = singletonConfigObjectFor(cls);
|
||||
if (inst != null) {
|
||||
save(inst);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("ConfigSerializer.saveAll failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ConfigObject singletonConfigObjectFor(Class<?> cls) throws IllegalAccessException {
|
||||
if (cls == null) return null;
|
||||
|
||||
for (Field field : cls.getDeclaredFields()) {
|
||||
if (!Modifier.isStatic(field.getModifiers())) continue;
|
||||
if (!ConfigObject.class.isAssignableFrom(field.getType())) continue;
|
||||
|
||||
field.setAccessible(true);
|
||||
Object value = field.get(null);
|
||||
if (value instanceof ConfigObject configObject) {
|
||||
return configObject;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// Dispatch
|
||||
// =============================================================
|
||||
|
||||
public static void save(ConfigObject obj) {
|
||||
if (obj instanceof HudGlobalConfig) return;
|
||||
saveNow(obj);
|
||||
}
|
||||
|
||||
public static void requestSave(ConfigObject obj) {
|
||||
if (obj == null || obj instanceof HudGlobalConfig) return;
|
||||
PendingWrite write;
|
||||
try {
|
||||
write = buildWrite(obj);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
|
||||
return;
|
||||
}
|
||||
if (write == null) return;
|
||||
|
||||
long token;
|
||||
synchronized (SAVE_LOCK) {
|
||||
token = ++SAVE_TOKEN_SEQ;
|
||||
PENDING_TEXT.put(write.path, write.text);
|
||||
PENDING_TOKENS.put(write.path, token);
|
||||
|
||||
ScheduledFuture<?> prev = PENDING_TASKS.get(write.path);
|
||||
if (prev != null) prev.cancel(false);
|
||||
|
||||
ScheduledFuture<?> task = SAVE_EXECUTOR.schedule(
|
||||
() -> flushPending(write.path, token),
|
||||
SAVE_DEBOUNCE_MS,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
PENDING_TASKS.put(write.path, task);
|
||||
}
|
||||
}
|
||||
|
||||
public static void load(ConfigObject obj) {
|
||||
if (obj instanceof HudGlobalConfig) return;
|
||||
if (isModule(obj)) {
|
||||
loadModule(obj);
|
||||
} else if (isJsonConfig(obj)) {
|
||||
loadJson(obj);
|
||||
} else {
|
||||
loadJson5(obj);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isModule(ConfigObject obj) {
|
||||
return obj instanceof Module;
|
||||
}
|
||||
|
||||
private static boolean isJsonConfig(ConfigObject obj) {
|
||||
return obj instanceof JsonConfigObject;
|
||||
}
|
||||
|
||||
private static String configNameOf(ConfigObject obj) {
|
||||
String name = null;
|
||||
if (obj instanceof ConfigNameProvider provider) {
|
||||
name = provider.getConfigName();
|
||||
}
|
||||
if (name == null || name.isBlank()) {
|
||||
name = obj.getClass().getSimpleName();
|
||||
}
|
||||
return sanitizeConfigName(name);
|
||||
}
|
||||
|
||||
private static String sanitizeConfigName(String name) {
|
||||
if (name == null) return "config";
|
||||
String base = name.trim().toLowerCase(Locale.ROOT);
|
||||
if (base.isEmpty()) return "config";
|
||||
StringBuilder out = new StringBuilder(base.length());
|
||||
for (int i = 0; i < base.length(); i++) {
|
||||
char c = base.charAt(i);
|
||||
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') {
|
||||
out.append(c);
|
||||
} else {
|
||||
out.append('_');
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static Path namedJsonFile(String configName) {
|
||||
return CONFIG_DIR.resolve(sanitizeConfigName(configName) + ".json");
|
||||
}
|
||||
|
||||
private static Path namedJson5File(String configName) {
|
||||
return CONFIG_DIR.resolve(sanitizeConfigName(configName) + ".json5");
|
||||
}
|
||||
|
||||
private static Path moduleFile(ConfigObject obj) {
|
||||
String category = "uncategorized";
|
||||
if (obj instanceof Module module && module.getCategory() != null) {
|
||||
category = sanitizeConfigName(module.getCategory().name());
|
||||
}
|
||||
return CONFIG_DIR.resolve("modules")
|
||||
.resolve(category)
|
||||
.resolve(configNameOf(obj) + ".json");
|
||||
}
|
||||
|
||||
private static Path jsonFile(ConfigObject obj) {
|
||||
if (obj instanceof DraggableHudElement) {
|
||||
return CONFIG_DIR.resolve("hud")
|
||||
.resolve("draggable")
|
||||
.resolve(configNameOf(obj) + ".json");
|
||||
}
|
||||
if (obj instanceof AbstractHudElement) {
|
||||
return CONFIG_DIR.resolve("hud")
|
||||
.resolve("nondraggable")
|
||||
.resolve(configNameOf(obj) + ".json");
|
||||
}
|
||||
return namedJsonFile(configNameOf(obj));
|
||||
}
|
||||
|
||||
private static Path utilFile(ConfigObject obj) {
|
||||
return isJsonConfig(obj)
|
||||
? jsonFile(obj)
|
||||
: namedJson5File(configNameOf(obj));
|
||||
}
|
||||
|
||||
private static Path fileOf(ConfigObject obj) {
|
||||
return isModule(obj) ? moduleFile(obj) : utilFile(obj);
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// Module (Gson JSON)
|
||||
// =============================================================
|
||||
|
||||
private static PendingWrite buildModuleWrite(ConfigObject obj) {
|
||||
try {
|
||||
JsonObject root = new JsonObject();
|
||||
for (ConfigValue<?> v : obj.getConfigValues()) {
|
||||
root.add(v.getName(), toJsonElement(v.toJson()));
|
||||
}
|
||||
|
||||
String text = GSON.toJson(root) + "\n";
|
||||
Path out = moduleFile(obj);
|
||||
return new PendingWrite(out, text);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadModule(ConfigObject obj) {
|
||||
try {
|
||||
Path path = moduleFile(obj);
|
||||
|
||||
if (!Files.exists(path)) {
|
||||
DebugLog.config("Config defaults created: %s", path.toAbsolutePath());
|
||||
save(obj);
|
||||
return;
|
||||
}
|
||||
|
||||
DebugLog.config("Config loading: %s", path.toAbsolutePath());
|
||||
|
||||
String txt = Files.readString(path);
|
||||
JsonElement parsed = GSON.fromJson(txt, JsonElement.class);
|
||||
if (!(parsed instanceof JsonObject root)) return;
|
||||
|
||||
Module module = (Module) obj;
|
||||
|
||||
JsonElement legacySettings = root.get("settings");
|
||||
if (legacySettings != null) {
|
||||
module.applyLegacySettings(unwrapJsonElement(legacySettings));
|
||||
}
|
||||
|
||||
boolean usedLegacyAlias = false;
|
||||
for (ConfigValue<?> v : obj.getConfigValues()) {
|
||||
JsonLookup lookup = findJsonElement(obj, root, v.getName());
|
||||
if (lookup.element() != null) {
|
||||
v.fromJson(unwrapJsonElement(lookup.element()));
|
||||
usedLegacyAlias |= lookup.alias();
|
||||
}
|
||||
}
|
||||
|
||||
module.syncSettingsAfterLoad();
|
||||
if (usedLegacyAlias) {
|
||||
requestSave(obj);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to load config %s", e, fileOf(obj).toAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// JSON (Gson) for non-Module configs
|
||||
// =============================================================
|
||||
|
||||
private static PendingWrite buildJsonWrite(ConfigObject obj) {
|
||||
try {
|
||||
JsonObject root = new JsonObject();
|
||||
for (ConfigValue<?> v : obj.getConfigValues()) {
|
||||
root.add(v.getName(), toJsonElement(v.toJson()));
|
||||
}
|
||||
|
||||
String text = GSON.toJson(root) + "\n";
|
||||
Path out = jsonFile(obj);
|
||||
return new PendingWrite(out, text);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadJson(ConfigObject obj) {
|
||||
try {
|
||||
Path path = jsonFile(obj);
|
||||
if (!Files.exists(path)) {
|
||||
DebugLog.config("Config defaults created: %s", path.toAbsolutePath());
|
||||
save(obj);
|
||||
return;
|
||||
}
|
||||
|
||||
DebugLog.config("Config loading: %s", path.toAbsolutePath());
|
||||
|
||||
String txt = Files.readString(path);
|
||||
JsonElement parsed = GSON.fromJson(txt, JsonElement.class);
|
||||
if (!(parsed instanceof JsonObject root)) return;
|
||||
|
||||
boolean missing = false;
|
||||
boolean usedLegacyAlias = false;
|
||||
for (ConfigValue<?> v : obj.getConfigValues()) {
|
||||
JsonLookup lookup = findJsonElement(obj, root, v.getName());
|
||||
if (lookup.element() != null) {
|
||||
v.fromJson(unwrapJsonElement(lookup.element()));
|
||||
usedLegacyAlias |= lookup.alias();
|
||||
} else {
|
||||
missing = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (missing || usedLegacyAlias) {
|
||||
requestSave(obj);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to load config %s", e, fileOf(obj).toAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// Utilities (Json5)
|
||||
// =============================================================
|
||||
|
||||
private static PendingWrite buildJson5Write(ConfigObject obj) {
|
||||
try {
|
||||
Json5Object root = new Json5Object();
|
||||
|
||||
for (ConfigValue<?> v : obj.getConfigValues()) {
|
||||
Object raw = v.toJson();
|
||||
root.add(v.getName(), toJson5Element(raw));
|
||||
}
|
||||
|
||||
String text = JSON5.serialize(root);
|
||||
|
||||
String sb = text + "\n";
|
||||
|
||||
Path out = utilFile(obj);
|
||||
if (obj instanceof EntityFilters) {
|
||||
DebugLog.config("[EntityFilters][SAVE] to=%s data=%s", out.toAbsolutePath(), text);
|
||||
}
|
||||
return new PendingWrite(out, sb);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadJson5(ConfigObject obj) {
|
||||
try {
|
||||
Path path = utilFile(obj);
|
||||
if (!Files.exists(path)) {
|
||||
DebugLog.config("Config defaults created: %s", path.toAbsolutePath());
|
||||
save(obj);
|
||||
return;
|
||||
}
|
||||
|
||||
DebugLog.config("Config loading: %s", path.toAbsolutePath());
|
||||
|
||||
String txt = Files.readString(path);
|
||||
Json5Element parsed = JSON5.parse(txt);
|
||||
|
||||
if (!(parsed instanceof Json5Object root)) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, Json5Element> map = root.asMap();
|
||||
|
||||
boolean missing = false;
|
||||
boolean usedLegacyAlias = false;
|
||||
for (ConfigValue<?> v : obj.getConfigValues()) {
|
||||
Json5Lookup lookup = findJson5Element(obj, map, v.getName());
|
||||
if (lookup.element() != null) {
|
||||
v.fromJson(unwrapJson5(lookup.element()));
|
||||
usedLegacyAlias |= lookup.alias();
|
||||
} else {
|
||||
missing = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (obj instanceof Module module) {
|
||||
module.syncSettingsAfterLoad();
|
||||
}
|
||||
if (missing || usedLegacyAlias) {
|
||||
requestSave(obj);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to load config %s", e, fileOf(obj).toAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonLookup findJsonElement(ConfigObject obj, JsonObject root, String valueName) {
|
||||
if (root == null || valueName == null) return JsonLookup.missing();
|
||||
JsonElement direct = root.get(valueName);
|
||||
if (direct != null && !direct.isJsonNull()) {
|
||||
return new JsonLookup(direct, false);
|
||||
}
|
||||
if (obj instanceof ConfigValueAliasProvider provider) {
|
||||
List<String> aliases = provider.getLegacyValueNames(valueName);
|
||||
if (aliases != null) {
|
||||
for (String alias : aliases) {
|
||||
if (alias == null || alias.isBlank()) continue;
|
||||
JsonElement legacy = root.get(alias);
|
||||
if (legacy != null && !legacy.isJsonNull()) {
|
||||
return new JsonLookup(legacy, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return JsonLookup.missing();
|
||||
}
|
||||
|
||||
private static Json5Lookup findJson5Element(ConfigObject obj, Map<String, Json5Element> map, String valueName) {
|
||||
if (map == null || valueName == null) return Json5Lookup.missing();
|
||||
Json5Element direct = map.get(valueName);
|
||||
if (direct != null) {
|
||||
return new Json5Lookup(direct, false);
|
||||
}
|
||||
if (obj instanceof ConfigValueAliasProvider provider) {
|
||||
List<String> aliases = provider.getLegacyValueNames(valueName);
|
||||
if (aliases != null) {
|
||||
for (String alias : aliases) {
|
||||
if (alias == null || alias.isBlank()) continue;
|
||||
Json5Element legacy = map.get(alias);
|
||||
if (legacy != null) {
|
||||
return new Json5Lookup(legacy, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Json5Lookup.missing();
|
||||
}
|
||||
|
||||
private static JsonElement toJsonElement(Object v) {
|
||||
if (v == null) return JsonNull.INSTANCE;
|
||||
if (v instanceof JsonElement el) return el;
|
||||
if (v instanceof Boolean b) return new JsonPrimitive(b);
|
||||
if (v instanceof Number n) return new JsonPrimitive(n);
|
||||
if (v instanceof CharSequence s) return new JsonPrimitive(s.toString());
|
||||
if (v instanceof Map<?, ?> map) {
|
||||
JsonObject obj = new JsonObject();
|
||||
for (var e : map.entrySet()) {
|
||||
obj.add(String.valueOf(e.getKey()), toJsonElement(e.getValue()));
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
if (v instanceof Iterable<?> it) {
|
||||
JsonArray arr = new JsonArray();
|
||||
for (Object el : it) arr.add(toJsonElement(el));
|
||||
return arr;
|
||||
}
|
||||
return new JsonPrimitive(String.valueOf(v));
|
||||
}
|
||||
|
||||
private static Json5Element toJson5Element(Object v) {
|
||||
if (v == null) {
|
||||
return Json5Primitive.fromNull();
|
||||
}
|
||||
if (v instanceof Json5Element el) {
|
||||
return el;
|
||||
}
|
||||
if (v instanceof Boolean b) {
|
||||
return Json5Primitive.fromBoolean(b);
|
||||
}
|
||||
if (v instanceof Number n) {
|
||||
return Json5Primitive.fromNumber(n);
|
||||
}
|
||||
if (v instanceof CharSequence s) {
|
||||
return Json5Primitive.fromString(s.toString());
|
||||
}
|
||||
if (v instanceof Map<?, ?> map) {
|
||||
Json5Object obj = new Json5Object();
|
||||
for (var e : map.entrySet()) {
|
||||
String key = String.valueOf(e.getKey());
|
||||
obj.add(key, toJson5Element(e.getValue()));
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
if (v instanceof Iterable<?> it) {
|
||||
Json5Array arr = new Json5Array();
|
||||
for (Object el : it) {
|
||||
arr.add(toJson5Element(el));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
return Json5Primitive.fromString(String.valueOf(v));
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// Helpers
|
||||
// =============================================================
|
||||
|
||||
private static Object unwrapJsonElement(JsonElement el) {
|
||||
if (el == null || el.isJsonNull()) return null;
|
||||
if (el.isJsonPrimitive()) {
|
||||
JsonPrimitive p = el.getAsJsonPrimitive();
|
||||
if (p.isBoolean()) return p.getAsBoolean();
|
||||
if (p.isNumber()) return p.getAsNumber();
|
||||
return p.getAsString();
|
||||
}
|
||||
if (el.isJsonArray()) {
|
||||
List<Object> out = new ArrayList<>();
|
||||
for (JsonElement child : el.getAsJsonArray()) {
|
||||
out.add(unwrapJsonElement(child));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (el.isJsonObject()) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (var e : el.getAsJsonObject().entrySet()) {
|
||||
out.put(e.getKey(), unwrapJsonElement(e.getValue()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Object unwrapJson5(Json5Element el) {
|
||||
if (el == null || el.isJson5Null()) return null;
|
||||
if (el.isJson5Primitive()) {
|
||||
Json5Primitive p = el.getAsJson5Primitive();
|
||||
if (p.isBoolean()) return p.getAsBoolean();
|
||||
if (p.isNumber()) return p.getAsNumber();
|
||||
return p.getAsString();
|
||||
}
|
||||
if (el.isJson5Array()) {
|
||||
List<Object> out = new ArrayList<>();
|
||||
for (Json5Element child : el.getAsJson5Array()) {
|
||||
out.add(unwrapJson5(child));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (el.isJson5Object()) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (var e : el.getAsJson5Object().asMap().entrySet()) {
|
||||
out.put(e.getKey(), unwrapJson5(e.getValue()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static PendingWrite buildWrite(ConfigObject obj) {
|
||||
if (obj == null) return null;
|
||||
if (isModule(obj)) return buildModuleWrite(obj);
|
||||
if (isJsonConfig(obj)) return buildJsonWrite(obj);
|
||||
return buildJson5Write(obj);
|
||||
}
|
||||
|
||||
private static void saveNow(ConfigObject obj) {
|
||||
PendingWrite write;
|
||||
try {
|
||||
write = buildWrite(obj);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to serialize config %s", e, fileOf(obj).toAbsolutePath());
|
||||
return;
|
||||
}
|
||||
if (write == null) return;
|
||||
clearPending(write.path);
|
||||
writeConfig(write.path, write.text);
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// Async write helpers
|
||||
// =============================================================
|
||||
|
||||
private static void flushPending(Path path, long token) {
|
||||
String text;
|
||||
synchronized (SAVE_LOCK) {
|
||||
Long current = PENDING_TOKENS.get(path);
|
||||
if (current == null || current != token) return;
|
||||
text = PENDING_TEXT.remove(path);
|
||||
PENDING_TOKENS.remove(path);
|
||||
PENDING_TASKS.remove(path);
|
||||
}
|
||||
if (text != null) {
|
||||
writeConfig(path, text);
|
||||
}
|
||||
}
|
||||
|
||||
private static void clearPending(Path path) {
|
||||
synchronized (SAVE_LOCK) {
|
||||
ScheduledFuture<?> prev = PENDING_TASKS.remove(path);
|
||||
if (prev != null) prev.cancel(false);
|
||||
PENDING_TEXT.remove(path);
|
||||
PENDING_TOKENS.remove(path);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeConfig(Path out, String text) {
|
||||
try {
|
||||
Path parent = out.getParent();
|
||||
Files.createDirectories(parent != null ? parent : CONFIG_DIR);
|
||||
Files.writeString(out, text);
|
||||
DebugLog.config("Config saved: %s", out.toAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
DebugLog.error("Failed to save config %s", e, out.toAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
private record JsonLookup(JsonElement element, boolean alias) {
|
||||
static JsonLookup missing() {
|
||||
return new JsonLookup(null, false);
|
||||
}
|
||||
}
|
||||
|
||||
private record Json5Lookup(Json5Element element, boolean alias) {
|
||||
static Json5Lookup missing() {
|
||||
return new Json5Lookup(null, false);
|
||||
}
|
||||
}
|
||||
|
||||
private record PendingWrite(Path path, String text) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.io;
|
||||
import dev.loki.lovisual.config.definition.ConfigObject;
|
||||
|
||||
/**
|
||||
* Marker for config objects that must be stored as JSON (not JSON5).
|
||||
*/
|
||||
public interface JsonConfigObject extends ConfigObject {
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.io;
|
||||
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.config.definition.SettingDef;
|
||||
|
||||
/**
|
||||
* Provides GUI-neutral setting definitions.
|
||||
*/
|
||||
public interface SettingDefProvider {
|
||||
List<SettingDef> getSettingDefs();
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.codec;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.DeflaterOutputStream;
|
||||
import java.util.zip.InflaterInputStream;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileEntry;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileValueCodec;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileMeta;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileSnapshot;
|
||||
|
||||
public final class ConfigProfileBinaryCodec {
|
||||
public static final int VERSION = 1;
|
||||
static final int MAGIC = 0x43424346; // CBCF
|
||||
private static final int FLAG_COMPRESSED = 1;
|
||||
|
||||
public ConfigProfileBinaryCodec() {
|
||||
}
|
||||
|
||||
public byte[] write(ConfigProfileSnapshot snapshot) throws IOException {
|
||||
if (snapshot == null) throw new IllegalArgumentException("snapshot is null");
|
||||
ByteArrayOutputStream payloadRaw = new ByteArrayOutputStream();
|
||||
try (DataOutputStream payload = new DataOutputStream(payloadRaw)) {
|
||||
writePayload(payload, snapshot.entries());
|
||||
}
|
||||
|
||||
byte[] payloadBytes = compress(payloadRaw.toByteArray());
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(payloadBytes);
|
||||
|
||||
ByteArrayOutputStream fileRaw = new ByteArrayOutputStream();
|
||||
try (DataOutputStream out = new DataOutputStream(fileRaw)) {
|
||||
ConfigProfileMeta meta = snapshot.meta();
|
||||
out.writeInt(MAGIC);
|
||||
out.writeByte(VERSION);
|
||||
out.writeByte(meta.type().wireId());
|
||||
out.writeShort(FLAG_COMPRESSED);
|
||||
out.writeLong(meta.createdAt());
|
||||
out.writeLong(meta.updatedAt());
|
||||
ConfigProfileValueCodec.writeString(out, meta.author());
|
||||
ConfigProfileValueCodec.writeString(out, meta.name());
|
||||
ConfigProfileValueCodec.writeString(out, meta.getId());
|
||||
ConfigProfileValueCodec.writeVarInt(out, payloadBytes.length);
|
||||
out.write(payloadBytes);
|
||||
out.writeInt((int) crc.getValue());
|
||||
}
|
||||
return fileRaw.toByteArray();
|
||||
}
|
||||
|
||||
public ConfigProfileMeta readMeta(byte[] bytes) throws IOException {
|
||||
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
|
||||
Header header = readHeader(in);
|
||||
return header.meta();
|
||||
}
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot read(byte[] bytes) throws IOException {
|
||||
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
|
||||
Header header = readHeader(in);
|
||||
byte[] payload = new byte[header.payloadLength()];
|
||||
in.readFully(payload);
|
||||
int expectedCrc = in.readInt();
|
||||
CRC32 crc = new CRC32();
|
||||
crc.update(payload);
|
||||
if ((int) crc.getValue() != expectedCrc) {
|
||||
throw new IOException("Config profile checksum mismatch: " + header.meta().name());
|
||||
}
|
||||
byte[] rawPayload = (header.flags() & FLAG_COMPRESSED) != 0 ? decompress(payload) : payload;
|
||||
List<ConfigProfileEntry> entries;
|
||||
try (DataInputStream payloadIn = new DataInputStream(new ByteArrayInputStream(rawPayload))) {
|
||||
entries = readPayload(payloadIn);
|
||||
}
|
||||
return new ConfigProfileSnapshot(header.meta(), entries);
|
||||
}
|
||||
}
|
||||
|
||||
private Header readHeader(DataInputStream in) throws IOException {
|
||||
int magic = in.readInt();
|
||||
if (magic != MAGIC) throw new IOException("Invalid profile magic");
|
||||
int version = in.readUnsignedByte();
|
||||
if (version != VERSION) throw new IOException("Unsupported profile version: " + version);
|
||||
ConfigProfileType type = ConfigProfileType.fromWireId(in.readUnsignedByte());
|
||||
int flags = in.readUnsignedShort();
|
||||
long createdAt = in.readLong();
|
||||
long updatedAt = in.readLong();
|
||||
String author = ConfigProfileValueCodec.readString(in);
|
||||
String name = ConfigProfileValueCodec.readString(in);
|
||||
String id = ConfigProfileValueCodec.readString(in);
|
||||
int payloadLength = ConfigProfileValueCodec.readVarInt(in);
|
||||
if (payloadLength < 0) throw new IOException("Negative payload length");
|
||||
ConfigProfileMeta meta = new ConfigProfileMeta(id, name, type, author, createdAt, updatedAt, version);
|
||||
return new Header(meta, flags, payloadLength);
|
||||
}
|
||||
|
||||
private void writePayload(DataOutputStream out, List<ConfigProfileEntry> entries) throws IOException {
|
||||
ConfigProfileValueCodec.writeVarInt(out, entries.size());
|
||||
for (ConfigProfileEntry entry : entries) {
|
||||
ConfigProfileValueCodec.writeString(out, entry.ownerId());
|
||||
ConfigProfileValueCodec.writeString(out, entry.displayName());
|
||||
ConfigProfileValueCodec.writeVarInt(out, entry.values().size());
|
||||
for (Map.Entry<String, Object> value : entry.values().entrySet()) {
|
||||
ConfigProfileValueCodec.writeString(out, value.getKey());
|
||||
ConfigProfileValueCodec.writeValue(out, value.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<ConfigProfileEntry> readPayload(DataInputStream in) throws IOException {
|
||||
int entryCount = ConfigProfileValueCodec.readVarInt(in);
|
||||
List<ConfigProfileEntry> entries = new ArrayList<>(Math.max(0, entryCount));
|
||||
for (int i = 0; i < entryCount; i++) {
|
||||
String ownerId = ConfigProfileValueCodec.readString(in);
|
||||
String displayName = ConfigProfileValueCodec.readString(in);
|
||||
int valueCount = ConfigProfileValueCodec.readVarInt(in);
|
||||
java.util.Map<String, Object> values = new java.util.LinkedHashMap<>();
|
||||
for (int j = 0; j < valueCount; j++) {
|
||||
values.put(ConfigProfileValueCodec.readString(in), ConfigProfileValueCodec.readValue(in));
|
||||
}
|
||||
entries.add(new ConfigProfileEntry(ownerId, displayName, values));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private byte[] compress(byte[] bytes) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
Deflater deflater = new Deflater(Deflater.BEST_SPEED);
|
||||
try (DeflaterOutputStream zip = new DeflaterOutputStream(out, deflater)) {
|
||||
zip.write(bytes);
|
||||
} finally {
|
||||
deflater.end();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private byte[] decompress(byte[] bytes) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (InflaterInputStream zip = new InflaterInputStream(new ByteArrayInputStream(bytes))) {
|
||||
zip.transferTo(out);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private record Header(ConfigProfileMeta meta, int flags, int payloadLength) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.codec;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public record ConfigProfileEntry(
|
||||
String ownerId,
|
||||
String displayName,
|
||||
Map<String, Object> values
|
||||
) {
|
||||
public ConfigProfileEntry {
|
||||
if (ownerId == null) ownerId = "";
|
||||
if (displayName == null || displayName.isBlank()) displayName = ownerId;
|
||||
Map<String, Object> copy = new LinkedHashMap<>();
|
||||
if (values != null) copy.putAll(values);
|
||||
values = Collections.unmodifiableMap(copy);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.codec;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum ConfigProfileType {
|
||||
MODULES((byte) 0, "modules"),
|
||||
HUD((byte) 1, "hud"),
|
||||
THEMES((byte) 2, "themes");
|
||||
|
||||
private final byte wireId;
|
||||
private final String folderName;
|
||||
|
||||
ConfigProfileType(byte wireId, String folderName) {
|
||||
this.wireId = wireId;
|
||||
this.folderName = folderName;
|
||||
}
|
||||
|
||||
public static ConfigProfileType fromWireId(int id) {
|
||||
for (ConfigProfileType type : values()) {
|
||||
if ((type.wireId & 0xFF) == id) return type;
|
||||
}
|
||||
throw new IllegalArgumentException("Unknown profile type id: " + id);
|
||||
}
|
||||
|
||||
public static ConfigProfileType fromName(String name) {
|
||||
if (name == null) return MODULES;
|
||||
String normalized = name.trim().toLowerCase(Locale.ROOT);
|
||||
for (ConfigProfileType type : values()) {
|
||||
if (type.name().toLowerCase(Locale.ROOT).equals(normalized) || type.folderName.equals(normalized)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
return MODULES;
|
||||
}
|
||||
|
||||
public byte wireId() {
|
||||
return wireId;
|
||||
}
|
||||
|
||||
public String folderName() {
|
||||
return folderName;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.codec;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public enum ConfigProfileValueCodec {
|
||||
;
|
||||
private static final byte NULL = 0;
|
||||
private static final byte BOOLEAN = 1;
|
||||
private static final byte INT = 2;
|
||||
private static final byte LONG = 3;
|
||||
private static final byte FLOAT = 4;
|
||||
private static final byte DOUBLE = 5;
|
||||
private static final byte STRING = 6;
|
||||
private static final byte LIST = 7;
|
||||
private static final byte MAP = 8;
|
||||
|
||||
public static void writeValue(DataOutputStream out, Object value) throws IOException {
|
||||
|
||||
if (value == null) {
|
||||
out.writeByte(NULL);
|
||||
} else if (value instanceof Boolean b) {
|
||||
out.writeByte(BOOLEAN);
|
||||
out.writeBoolean(b);
|
||||
} else if (value instanceof Integer i) {
|
||||
out.writeByte(INT);
|
||||
writeVarInt(out, i);
|
||||
} else if (value instanceof Long l) {
|
||||
out.writeByte(LONG);
|
||||
out.writeLong(l);
|
||||
} else if (value instanceof Float f) {
|
||||
out.writeByte(FLOAT);
|
||||
out.writeFloat(f);
|
||||
} else if (value instanceof Number n) {
|
||||
out.writeByte(DOUBLE);
|
||||
out.writeDouble(n.doubleValue());
|
||||
} else if (value instanceof CharSequence s) {
|
||||
out.writeByte(STRING);
|
||||
writeString(out, s.toString());
|
||||
} else if (value instanceof Iterable<?> iterable) {
|
||||
out.writeByte(LIST);
|
||||
List<Object> list = new ArrayList<>();
|
||||
for (Object item : iterable) list.add(item);
|
||||
writeVarInt(out, list.size());
|
||||
for (Object item : list) writeValue(out, item);
|
||||
} else if (value instanceof Map<?, ?> map) {
|
||||
out.writeByte(MAP);
|
||||
writeVarInt(out, map.size());
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
writeString(out, String.valueOf(entry.getKey()));
|
||||
writeValue(out, entry.getValue());
|
||||
}
|
||||
} else {
|
||||
out.writeByte(STRING);
|
||||
writeString(out, String.valueOf(value));
|
||||
}
|
||||
}
|
||||
|
||||
public static Object readValue(DataInputStream in) throws IOException {
|
||||
|
||||
int type = in.readUnsignedByte();
|
||||
return switch (type) {
|
||||
case NULL -> null;
|
||||
case BOOLEAN -> in.readBoolean();
|
||||
case INT -> readVarInt(in);
|
||||
case LONG -> in.readLong();
|
||||
case FLOAT -> in.readFloat();
|
||||
case DOUBLE -> in.readDouble();
|
||||
case STRING -> readString(in);
|
||||
case LIST -> {
|
||||
int size = readVarInt(in);
|
||||
List<Object> list = new ArrayList<>(Math.max(0, size));
|
||||
for (int i = 0; i < size; i++) list.add(readValue(in));
|
||||
yield list;
|
||||
}
|
||||
case MAP -> {
|
||||
int size = readVarInt(in);
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
for (int i = 0; i < size; i++) {
|
||||
map.put(readString(in), readValue(in));
|
||||
}
|
||||
yield map;
|
||||
}
|
||||
default -> throw new IOException("Unknown profile value type: " + type);
|
||||
};
|
||||
}
|
||||
|
||||
static void writeString(DataOutputStream out, String value) throws IOException {
|
||||
if (value == null) value = "";
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
writeVarInt(out, bytes.length);
|
||||
out.write(bytes);
|
||||
}
|
||||
|
||||
static String readString(DataInputStream in) throws IOException {
|
||||
int length = readVarInt(in);
|
||||
if (length < 0) throw new IOException("Negative string length: " + length);
|
||||
byte[] bytes = new byte[length];
|
||||
in.readFully(bytes);
|
||||
return new String(bytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static void writeVarInt(DataOutputStream out, int value) throws IOException {
|
||||
int v = value;
|
||||
while ((v & 0xFFFFFF80) != 0L) {
|
||||
out.writeByte((v & 0x7F) | 0x80);
|
||||
v >>>= 7;
|
||||
}
|
||||
out.writeByte(v & 0x7F);
|
||||
}
|
||||
|
||||
static int readVarInt(DataInputStream in) throws IOException {
|
||||
int numRead = 0;
|
||||
int result = 0;
|
||||
byte read;
|
||||
do {
|
||||
read = in.readByte();
|
||||
int value = (read & 0x7F);
|
||||
result |= (value << (7 * numRead));
|
||||
numRead++;
|
||||
if (numRead > 5) throw new IOException("VarInt is too big");
|
||||
} while ((read & 0x80) != 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.diff;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileMeta;
|
||||
|
||||
public enum ConfigProfileDateFormatter {
|
||||
;
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("dd.MM.yyyy");
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm");
|
||||
|
||||
public static String created(ConfigProfileMeta meta) {
|
||||
return DATE.format(toDate(meta.createdAt()));
|
||||
}
|
||||
|
||||
public static String updated(ConfigProfileMeta meta) {
|
||||
LocalDate created = toDate(meta.createdAt());
|
||||
LocalDate updated = toDate(meta.updatedAt());
|
||||
String text = DATE.format(updated);
|
||||
if (created.equals(updated)) {
|
||||
text += " (" + TIME.format(Instant.ofEpochMilli(meta.updatedAt()).atZone(ZoneId.systemDefault())) + ")";
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
private static LocalDate toDate(long epochMillis) {
|
||||
return Instant.ofEpochMilli(epochMillis).atZone(ZoneId.systemDefault()).toLocalDate();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.diff;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
|
||||
public record ConfigProfileDiff(
|
||||
ConfigProfileType type,
|
||||
List<Entry> entries
|
||||
) {
|
||||
public ConfigProfileDiff {
|
||||
if (type == null) type = ConfigProfileType.MODULES;
|
||||
List<Entry> copy = new ArrayList<>();
|
||||
if (entries != null) copy.addAll(entries);
|
||||
entries = Collections.unmodifiableList(copy);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return entries.isEmpty();
|
||||
}
|
||||
|
||||
public int valueChangeCount() {
|
||||
int count = 0;
|
||||
for (Entry entry : entries) count += entry.values().size();
|
||||
return count;
|
||||
}
|
||||
|
||||
public enum Kind {
|
||||
ADDED,
|
||||
REMOVED,
|
||||
CHANGED
|
||||
}
|
||||
|
||||
public record Entry(String ownerId, String displayName, List<Value> values) {
|
||||
public Entry {
|
||||
if (ownerId == null) ownerId = "";
|
||||
if (displayName == null || displayName.isBlank()) displayName = ownerId;
|
||||
List<Value> copy = new ArrayList<>();
|
||||
if (values != null) copy.addAll(values);
|
||||
values = Collections.unmodifiableList(copy);
|
||||
}
|
||||
}
|
||||
|
||||
public record Value(String key, Object currentValue, Object selectedValue, Kind kind) {
|
||||
public Value {
|
||||
if (key == null) key = "";
|
||||
if (kind == null) kind = Kind.CHANGED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.diff;
|
||||
|
||||
import java.util.*;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileEntry;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.diff.ConfigProfileDiff;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileSnapshot;
|
||||
|
||||
public final class ConfigProfileDiffEngine {
|
||||
public ConfigProfileDiff compare(ConfigProfileSnapshot current, ConfigProfileSnapshot selected) {
|
||||
if (current == null || selected == null) {
|
||||
return new ConfigProfileDiff(ConfigProfileType.MODULES, List.of());
|
||||
}
|
||||
ConfigProfileType type = selected.meta().type();
|
||||
Map<String, ConfigProfileEntry> currentMap = mapByOwner(current);
|
||||
Map<String, ConfigProfileEntry> selectedMap = mapByOwner(selected);
|
||||
|
||||
Set<String> owners = new LinkedHashSet<>();
|
||||
owners.addAll(currentMap.keySet());
|
||||
owners.addAll(selectedMap.keySet());
|
||||
|
||||
List<ConfigProfileDiff.Entry> entries = new ArrayList<>();
|
||||
for (String ownerId : owners) {
|
||||
ConfigProfileEntry c = currentMap.get(ownerId);
|
||||
ConfigProfileEntry s = selectedMap.get(ownerId);
|
||||
String displayName = s != null ? s.displayName() : c != null ? c.displayName() : ownerId;
|
||||
Map<String, Object> cv = c != null ? c.values() : Map.of();
|
||||
Map<String, Object> sv = s != null ? s.values() : Map.of();
|
||||
|
||||
Set<String> keys = new LinkedHashSet<>();
|
||||
keys.addAll(cv.keySet());
|
||||
keys.addAll(sv.keySet());
|
||||
|
||||
List<ConfigProfileDiff.Value> values = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
boolean hasCurrent = cv.containsKey(key);
|
||||
boolean hasSelected = sv.containsKey(key);
|
||||
Object currentValue = cv.get(key);
|
||||
Object selectedValue = sv.get(key);
|
||||
if (hasCurrent && hasSelected && Objects.equals(currentValue, selectedValue)) continue;
|
||||
ConfigProfileDiff.Kind kind;
|
||||
if (!hasCurrent) kind = ConfigProfileDiff.Kind.ADDED;
|
||||
else if (!hasSelected) kind = ConfigProfileDiff.Kind.REMOVED;
|
||||
else kind = ConfigProfileDiff.Kind.CHANGED;
|
||||
values.add(new ConfigProfileDiff.Value(key, currentValue, selectedValue, kind));
|
||||
}
|
||||
if (!values.isEmpty()) {
|
||||
entries.add(new ConfigProfileDiff.Entry(ownerId, displayName, values));
|
||||
}
|
||||
}
|
||||
return new ConfigProfileDiff(type, entries);
|
||||
}
|
||||
|
||||
private Map<String, ConfigProfileEntry> mapByOwner(ConfigProfileSnapshot snapshot) {
|
||||
Map<String, ConfigProfileEntry> map = new LinkedHashMap<>();
|
||||
for (ConfigProfileEntry entry : snapshot.entries()) {
|
||||
map.put(entry.ownerId(), entry);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.service;
|
||||
|
||||
import dev.loki.lovisual.features.theme.Theme;
|
||||
import dev.loki.lovisual.config.definition.ConfigObject;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
import dev.loki.lovisual.features.gui.hud.base.BaseHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.theme.Themes;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileEntry;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileSnapshot;
|
||||
|
||||
public final class ConfigProfileApplier {
|
||||
public ApplyResult apply(ConfigProfileSnapshot snapshot) {
|
||||
if (snapshot == null) return new ApplyResult(0, 0, 0);
|
||||
ApplyCounter counter = new ApplyCounter();
|
||||
if (snapshot.meta().type() == ConfigProfileType.MODULES) {
|
||||
ModuleManager.runSilentConfigApply(() -> applyEntries(snapshot, counter));
|
||||
} else {
|
||||
applyEntries(snapshot, counter);
|
||||
}
|
||||
return new ApplyResult(counter.appliedOwners, counter.missingOwners, counter.missingValues);
|
||||
}
|
||||
|
||||
private void applyEntries(ConfigProfileSnapshot snapshot, ApplyCounter counter) {
|
||||
if (snapshot.meta().type() == ConfigProfileType.THEMES) {
|
||||
applyThemeEntries(snapshot, counter);
|
||||
return;
|
||||
}
|
||||
for (ConfigProfileEntry entry : snapshot.entries()) {
|
||||
ConfigObject owner = resolveOwner(entry.ownerId());
|
||||
if (owner == null) {
|
||||
counter.missingOwners++;
|
||||
DebugLog.config("Config profile missing owner: %s", entry.ownerId());
|
||||
continue;
|
||||
}
|
||||
applyValues(owner, entry, counter);
|
||||
counter.appliedOwners++;
|
||||
afterOwnerApplied(owner);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyThemeEntries(ConfigProfileSnapshot snapshot, ApplyCounter counter) {
|
||||
String currentId = null;
|
||||
for (ConfigProfileEntry entry : snapshot.entries()) {
|
||||
String ownerId = entry.ownerId();
|
||||
if (ownerId == null) {
|
||||
counter.missingOwners++;
|
||||
continue;
|
||||
}
|
||||
if (ownerId.equals("theme-state:current")) {
|
||||
Object current = entry.values().get("current");
|
||||
if (current instanceof CharSequence s && !s.toString().isBlank()) {
|
||||
currentId = s.toString();
|
||||
}
|
||||
counter.appliedOwners++;
|
||||
continue;
|
||||
}
|
||||
if (!ownerId.startsWith("theme:")) {
|
||||
counter.missingOwners++;
|
||||
continue;
|
||||
}
|
||||
String id = ownerId.substring("theme:".length());
|
||||
try {
|
||||
Themes.importProfileValues(id, entry.displayName(), entry.values());
|
||||
counter.appliedOwners++;
|
||||
} catch (Throwable t) {
|
||||
counter.missingValues++;
|
||||
DebugLog.error("Failed to apply theme profile entry %s", t, ownerId);
|
||||
}
|
||||
}
|
||||
if (currentId != null) {
|
||||
String selectedId = currentId.toLowerCase(java.util.Locale.ROOT);
|
||||
if (Theme.themes().stream().anyMatch(theme -> theme.getId().equals(selectedId))) {
|
||||
Theme.setTheme(selectedId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applyValues(ConfigObject owner, ConfigProfileEntry entry, ApplyCounter counter) {
|
||||
Map<String, ConfigValue<?>> byName = new HashMap<>();
|
||||
for (ConfigValue<?> value : owner.getConfigValues()) {
|
||||
if (value != null && value.getName() != null) byName.put(value.getName(), value);
|
||||
}
|
||||
for (Map.Entry<String, Object> saved : entry.values().entrySet()) {
|
||||
ConfigValue<?> value = byName.get(saved.getKey());
|
||||
if (value == null) {
|
||||
counter.missingValues++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
value.fromJson(saved.getValue());
|
||||
} catch (Throwable t) {
|
||||
counter.missingValues++;
|
||||
DebugLog.error("Failed to apply profile value %s.%s", t, entry.ownerId(), saved.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigObject resolveOwner(String ownerId) {
|
||||
if (ownerId == null) return null;
|
||||
if (ownerId.startsWith("addon:")) {
|
||||
return resolveOwner(stripAddonPrefix(ownerId));
|
||||
}
|
||||
if (ownerId.startsWith("module:")) return ModuleManager.get(ownerId.substring("module:".length()));
|
||||
if (ownerId.startsWith("hud.draggable:")) {
|
||||
return DraggableHudElementRegistry.getById(ownerId.substring("hud.draggable:".length()));
|
||||
}
|
||||
if (ownerId.startsWith("hud.static:")) {
|
||||
return StaticHudElementRegistry.getById(ownerId.substring("hud.static:".length()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String stripAddonPrefix(String ownerId) {
|
||||
String addonId = AddonManager.addonIdFromProfileOwner(ownerId);
|
||||
if (addonId == null) return "";
|
||||
String prefix = "addon:" + addonId + ":";
|
||||
if (!ownerId.startsWith(prefix)) return "";
|
||||
return ownerId.substring(prefix.length());
|
||||
}
|
||||
|
||||
private void afterOwnerApplied(ConfigObject owner) {
|
||||
if (owner instanceof Module module) {
|
||||
module.applyConfiguredEnabledState();
|
||||
module.syncSettingsAfterLoad();
|
||||
module.saveConfig();
|
||||
return;
|
||||
}
|
||||
if (owner instanceof BaseHudElement hud) {
|
||||
hud.saveConfig();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ApplyCounter {
|
||||
int appliedOwners;
|
||||
int missingOwners;
|
||||
int missingValues;
|
||||
}
|
||||
|
||||
public record ApplyResult(int appliedOwners, int missingOwners, int missingValues) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.service;
|
||||
|
||||
import dev.loki.lovisual.features.theme.Theme;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import dev.loki.lovisual.config.definition.ConfigObject;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.addon.core.AddonManager;
|
||||
import dev.loki.lovisual.features.gui.hud.base.AbstractHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
|
||||
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElementRegistry;
|
||||
import dev.loki.lovisual.features.gui.hud.nondraggable.StaticHudElementRegistry;
|
||||
import dev.loki.lovisual.features.theme.Themes;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.features.module.core.ModuleManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileBinaryCodec;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileEntry;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.service.ConfigProfileStorage;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileMeta;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileSnapshot;
|
||||
import dev.loki.lovisual.features.module.lifecycle.Modules;
|
||||
|
||||
public final class ConfigProfileCollector {
|
||||
public ConfigProfileSnapshot collect(ConfigProfileType type, String name) {
|
||||
long now = System.currentTimeMillis();
|
||||
String safeName = (name == null || name.isBlank()) ? defaultName(type) : name.trim();
|
||||
String id = ConfigProfileStorage.sanitizeFileName(safeName);
|
||||
ConfigProfileMeta meta = new ConfigProfileMeta(
|
||||
id,
|
||||
safeName,
|
||||
type,
|
||||
currentAuthorName(),
|
||||
now,
|
||||
now,
|
||||
ConfigProfileBinaryCodec.VERSION
|
||||
);
|
||||
return new ConfigProfileSnapshot(meta, collectEntries(type));
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot collectWithMeta(ConfigProfileMeta meta) {
|
||||
if (meta == null) throw new IllegalArgumentException("profile meta is null");
|
||||
return new ConfigProfileSnapshot(meta, collectEntries(meta.type()));
|
||||
}
|
||||
|
||||
public List<ConfigProfileEntry> collectEntries(ConfigProfileType type) {
|
||||
List<ConfigProfileEntry> entries = new ArrayList<>();
|
||||
if (type == ConfigProfileType.HUD) {
|
||||
for (DraggableHudElement widget : DraggableHudElementRegistry.getWidgets()) {
|
||||
String ownerId = AddonManager.draggableHudProfileOwnerId(widget.getId());
|
||||
entries.add(entry(ownerId, AddonManager.profileDisplayName(ownerId, widget.getTitle()), widget));
|
||||
}
|
||||
for (AbstractHudElement element : StaticHudElementRegistry.getAll()) {
|
||||
String ownerId = AddonManager.staticHudProfileOwnerId(element.getId());
|
||||
entries.add(entry(ownerId, AddonManager.profileDisplayName(ownerId, element.getTitle()), element));
|
||||
}
|
||||
} else if (type == ConfigProfileType.THEMES) {
|
||||
Map<String, Object> state = new LinkedHashMap<>();
|
||||
state.put("current", Theme.currentId());
|
||||
entries.add(new ConfigProfileEntry("theme-state:current", "Current Theme", state));
|
||||
for (Themes.ThemeEntry theme : Theme.customThemes()) {
|
||||
entries.add(new ConfigProfileEntry("theme:" + theme.getId(), theme.name(), Themes.toProfileValues(theme)));
|
||||
}
|
||||
} else {
|
||||
for (Module module : ModuleManager.getModules()) {
|
||||
String ownerId = AddonManager.moduleProfileOwnerId(module.name());
|
||||
entries.add(entry(ownerId, AddonManager.profileDisplayName(ownerId, module.getDisplayName()), module));
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private ConfigProfileEntry entry(String ownerId, String displayName, ConfigObject owner) {
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
if (owner != null) {
|
||||
for (ConfigValue<?> value : owner.getConfigValues()) {
|
||||
if (value != null && value.getName() != null) {
|
||||
values.put(value.getName(), value.toJson());
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ConfigProfileEntry(ownerId, displayName, values);
|
||||
}
|
||||
|
||||
private String currentAuthorName() {
|
||||
try {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc != null && mc.getUser() != null) {
|
||||
String username = mc.getUser().getName();
|
||||
if (username != null && !username.isBlank()) return username;
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
// TODO: use Discord RPC nickname/avatar when Discord integration is ready.
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
private String defaultName(ConfigProfileType type) {
|
||||
return type == ConfigProfileType.HUD ? "Hud Config" : type == ConfigProfileType.THEMES ? "Themes Config" : "Modules Config";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileBinaryCodec;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.diff.ConfigProfileDiff;
|
||||
import dev.loki.lovisual.config.profile.diff.ConfigProfileDiffEngine;
|
||||
import dev.loki.lovisual.config.profile.service.ConfigProfileApplier;
|
||||
import dev.loki.lovisual.config.profile.service.ConfigProfileCollector;
|
||||
import dev.loki.lovisual.config.profile.service.ConfigProfileStorage;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileMeta;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileSnapshot;
|
||||
|
||||
public final class ConfigProfileService {
|
||||
public static final ConfigProfileService INSTANCE = new ConfigProfileService();
|
||||
|
||||
private final ConfigProfileStorage storage = new ConfigProfileStorage();
|
||||
private final ConfigProfileCollector collector = new ConfigProfileCollector();
|
||||
private final ConfigProfileApplier applier = new ConfigProfileApplier();
|
||||
private final ConfigProfileDiffEngine diffEngine = new ConfigProfileDiffEngine();
|
||||
|
||||
private ConfigProfileService() {
|
||||
}
|
||||
|
||||
public ConfigProfileStorage storage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
public List<ConfigProfileMeta> list(ConfigProfileType type) {
|
||||
return storage.list(type);
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot saveCurrent(ConfigProfileType type, String name) throws IOException {
|
||||
ConfigProfileMeta old = find(type, name);
|
||||
ConfigProfileSnapshot snapshot = collector.collect(type, name);
|
||||
if (old != null) {
|
||||
ConfigProfileMeta meta = new ConfigProfileMeta(
|
||||
old.getId(),
|
||||
old.name(),
|
||||
old.type(),
|
||||
old.author(),
|
||||
old.createdAt(),
|
||||
System.currentTimeMillis(),
|
||||
ConfigProfileBinaryCodec.VERSION
|
||||
);
|
||||
snapshot = collector.collectWithMeta(meta);
|
||||
}
|
||||
storage.save(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot overwriteCurrent(ConfigProfileMeta target) throws IOException {
|
||||
if (target == null) throw new IllegalArgumentException("profile meta is null");
|
||||
ConfigProfileMeta meta = target.withUpdatedAt(System.currentTimeMillis());
|
||||
ConfigProfileSnapshot snapshot = collector.collectWithMeta(meta);
|
||||
storage.save(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot read(ConfigProfileType type, String idOrName) throws IOException {
|
||||
return storage.read(type, idOrName);
|
||||
}
|
||||
|
||||
public ConfigProfileApplier.ApplyResult apply(ConfigProfileType type, String idOrName) throws IOException {
|
||||
return applier.apply(storage.read(type, idOrName));
|
||||
}
|
||||
|
||||
public ConfigProfileDiff diffWithCurrent(ConfigProfileType type, String idOrName) throws IOException {
|
||||
ConfigProfileSnapshot selected = storage.read(type, idOrName);
|
||||
ConfigProfileSnapshot current = collector.collectWithMeta(new ConfigProfileMeta(
|
||||
"__current__",
|
||||
"Current",
|
||||
type,
|
||||
"Runtime",
|
||||
System.currentTimeMillis(),
|
||||
System.currentTimeMillis(),
|
||||
ConfigProfileBinaryCodec.VERSION
|
||||
));
|
||||
return diffEngine.compare(current, selected);
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot rename(ConfigProfileType type, String idOrName, String newName) throws IOException {
|
||||
return storage.rename(type, idOrName, newName);
|
||||
}
|
||||
|
||||
public boolean delete(ConfigProfileType type, String idOrName) throws IOException {
|
||||
return storage.delete(type, idOrName);
|
||||
}
|
||||
|
||||
public ConfigProfileStorage.ImportResult importProfileFile(Path source, boolean moveSource) throws IOException {
|
||||
return storage.importProfileFile(source, moveSource);
|
||||
}
|
||||
|
||||
private ConfigProfileMeta find(ConfigProfileType type, String name) {
|
||||
String id = ConfigProfileStorage.sanitizeFileName(name);
|
||||
for (ConfigProfileMeta meta : storage.list(type)) {
|
||||
if (meta.getId().equals(id)) return meta;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,222 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.service;
|
||||
|
||||
import dev.loki.lovisual.config.io.ConfigPaths;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileBinaryCodec;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileMeta;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileSnapshot;
|
||||
|
||||
public final class ConfigProfileStorage {
|
||||
public static final String EXTENSION = ".lvcfg";
|
||||
public static final String LEGACY_EXTENSION = ".cbcfg";
|
||||
|
||||
private final Path root;
|
||||
private final ConfigProfileBinaryCodec codec = new ConfigProfileBinaryCodec();
|
||||
|
||||
public ConfigProfileStorage() {
|
||||
this(ConfigPaths.profilesRoot());
|
||||
}
|
||||
|
||||
public ConfigProfileStorage(Path root) {
|
||||
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
public static String sanitizeFileName(String name) {
|
||||
if (name == null) return "config";
|
||||
String base = name.trim().toLowerCase(Locale.ROOT);
|
||||
base = stripExtension(base, EXTENSION);
|
||||
base = stripExtension(base, LEGACY_EXTENSION);
|
||||
if (base.isEmpty()) return "config";
|
||||
StringBuilder out = new StringBuilder(base.length());
|
||||
for (int i = 0; i < base.length(); i++) {
|
||||
char c = base.charAt(i);
|
||||
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') {
|
||||
out.append(c);
|
||||
} else {
|
||||
out.append('_');
|
||||
}
|
||||
}
|
||||
return out.length() == 0 ? "config" : out.toString();
|
||||
}
|
||||
|
||||
private static String stripExtension(String value, String extension) {
|
||||
if (value.endsWith(extension)) return value.substring(0, value.length() - extension.length());
|
||||
return value;
|
||||
}
|
||||
|
||||
public Path root() {
|
||||
return root;
|
||||
}
|
||||
|
||||
public Path directory(ConfigProfileType type) {
|
||||
return root.resolve(type.folderName());
|
||||
}
|
||||
|
||||
public List<ConfigProfileMeta> list(ConfigProfileType type) {
|
||||
normalizeLooseProfiles();
|
||||
List<ConfigProfileMeta> out = new ArrayList<>();
|
||||
Path dir = directory(type);
|
||||
if (!Files.isDirectory(dir)) return out;
|
||||
try (var stream = Files.list(dir)) {
|
||||
stream.filter(path -> Files.isRegularFile(path) && hasProfileExtension(path))
|
||||
.forEach(path -> {
|
||||
try {
|
||||
ConfigProfileMeta meta = codec.readMeta(Files.readAllBytes(path));
|
||||
out.add(meta);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to read profile meta %s", e, path.toAbsolutePath());
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
DebugLog.error("Failed to list profiles %s", e, dir.toAbsolutePath());
|
||||
}
|
||||
out.sort(Comparator.comparingLong(ConfigProfileMeta::updatedAt).reversed());
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean hasProfileExtension(Path path) {
|
||||
String name = path.getFileName().toString().toLowerCase(Locale.ROOT);
|
||||
return name.endsWith(EXTENSION) || name.endsWith(LEGACY_EXTENSION);
|
||||
}
|
||||
|
||||
public ImportResult importProfileFile(Path source, boolean moveSource) throws IOException {
|
||||
if (source == null) throw new IllegalArgumentException("profile path is null");
|
||||
if (!Files.isRegularFile(source)) throw new IOException("profile is not a regular file: " + source);
|
||||
if (!hasProfileExtension(source)) {
|
||||
throw new IOException("not a " + EXTENSION + " or " + LEGACY_EXTENSION + " profile: " + source);
|
||||
}
|
||||
|
||||
byte[] bytes = Files.readAllBytes(source);
|
||||
ConfigProfileMeta meta = codec.read(bytes).meta();
|
||||
Path dest = file(meta.type(), meta.getId());
|
||||
Files.createDirectories(dest.getParent());
|
||||
|
||||
Path sourceAbs = source.toAbsolutePath().normalize();
|
||||
Path destAbs = dest.toAbsolutePath().normalize();
|
||||
if (!sourceAbs.equals(destAbs)) {
|
||||
if (moveSource) {
|
||||
Files.move(source, dest, StandardCopyOption.REPLACE_EXISTING);
|
||||
} else {
|
||||
Files.write(dest, bytes);
|
||||
}
|
||||
}
|
||||
return new ImportResult(meta, dest);
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot read(ConfigProfileType type, String idOrName) throws IOException {
|
||||
Path path = resolveExisting(type, idOrName);
|
||||
return codec.read(Files.readAllBytes(path));
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot read(ConfigProfileMeta meta) throws IOException {
|
||||
if (meta == null) throw new IllegalArgumentException("profile meta is null");
|
||||
return read(meta.type(), meta.getId());
|
||||
}
|
||||
|
||||
public void save(ConfigProfileSnapshot snapshot) throws IOException {
|
||||
if (snapshot == null) throw new IllegalArgumentException("snapshot is null");
|
||||
Files.createDirectories(directory(snapshot.meta().type()));
|
||||
Path path = file(snapshot.meta().type(), snapshot.meta().getId());
|
||||
Files.write(path, codec.write(snapshot));
|
||||
DebugLog.config("Config profile saved: %s", path.toAbsolutePath());
|
||||
}
|
||||
|
||||
public boolean delete(ConfigProfileType type, String idOrName) throws IOException {
|
||||
boolean deleted = Files.deleteIfExists(file(type, idOrName));
|
||||
deleted |= Files.deleteIfExists(legacyFile(type, idOrName));
|
||||
return deleted;
|
||||
}
|
||||
|
||||
public ConfigProfileSnapshot rename(ConfigProfileType type, String idOrName, String newName) throws IOException {
|
||||
if (newName == null || newName.isBlank()) throw new IllegalArgumentException("profile name is blank");
|
||||
ConfigProfileSnapshot old = read(type, idOrName);
|
||||
ConfigProfileMeta oldMeta = old.meta();
|
||||
ConfigProfileMeta newMeta = oldMeta.withName(newName.trim(), System.currentTimeMillis());
|
||||
Path oldPath = resolveExisting(type, oldMeta.getId());
|
||||
Path newPath = file(type, newMeta.getId());
|
||||
if (!oldMeta.getId().equals(newMeta.getId()) && Files.exists(newPath)) {
|
||||
throw new IOException("profile already exists: " + newMeta.name());
|
||||
}
|
||||
ConfigProfileSnapshot renamed = new ConfigProfileSnapshot(newMeta, old.entries());
|
||||
save(renamed);
|
||||
if (!oldPath.equals(newPath)) Files.deleteIfExists(oldPath);
|
||||
return renamed;
|
||||
}
|
||||
|
||||
public boolean exists(ConfigProfileType type, String idOrName) {
|
||||
return Files.exists(file(type, idOrName)) || Files.exists(legacyFile(type, idOrName));
|
||||
}
|
||||
|
||||
/** Canonical storage path — always uses the current {@link #EXTENSION}. */
|
||||
public Path file(ConfigProfileType type, String idOrName) {
|
||||
String id = sanitizeFileName(idOrName);
|
||||
if (id.endsWith(LEGACY_EXTENSION)) {
|
||||
id = stripExtension(id, LEGACY_EXTENSION) + EXTENSION;
|
||||
} else if (!id.endsWith(EXTENSION)) {
|
||||
id += EXTENSION;
|
||||
}
|
||||
return directory(type).resolve(id);
|
||||
}
|
||||
|
||||
private Path legacyFile(ConfigProfileType type, String idOrName) {
|
||||
String id = sanitizeFileName(idOrName);
|
||||
if (!id.endsWith(LEGACY_EXTENSION)) id += LEGACY_EXTENSION;
|
||||
return directory(type).resolve(id);
|
||||
}
|
||||
|
||||
private Path resolveExisting(ConfigProfileType type, String idOrName) {
|
||||
Path canonical = file(type, idOrName);
|
||||
if (Files.exists(canonical)) return canonical;
|
||||
Path legacy = legacyFile(type, idOrName);
|
||||
return Files.exists(legacy) ? legacy : canonical;
|
||||
}
|
||||
|
||||
private void normalizeLooseProfiles() {
|
||||
if (!Files.isDirectory(root)) return;
|
||||
List<Path> candidates = new ArrayList<>();
|
||||
try (var stream = Files.walk(root)) {
|
||||
stream.filter(Files::isRegularFile)
|
||||
.filter(ConfigProfileStorage::hasProfileExtension)
|
||||
.forEach(candidates::add);
|
||||
} catch (IOException e) {
|
||||
DebugLog.error("Failed to scan loose config profiles %s", e, root.toAbsolutePath());
|
||||
return;
|
||||
}
|
||||
|
||||
for (Path candidate : candidates) {
|
||||
try {
|
||||
ConfigProfileMeta meta = codec.read(Files.readAllBytes(candidate)).meta();
|
||||
Path dest = file(meta.type(), meta.getId());
|
||||
Path candidateAbs = candidate.toAbsolutePath().normalize();
|
||||
Path destAbs = dest.toAbsolutePath().normalize();
|
||||
if (candidateAbs.equals(destAbs)) continue;
|
||||
Files.createDirectories(dest.getParent());
|
||||
Files.move(candidate, dest, StandardCopyOption.REPLACE_EXISTING);
|
||||
DebugLog.config("Moved config profile %s -> %s", candidateAbs, destAbs);
|
||||
} catch (Exception e) {
|
||||
DebugLog.error("Failed to normalize config profile %s", e, candidate.toAbsolutePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record ImportResult(ConfigProfileMeta meta, Path path) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.snapshot;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileBinaryCodec;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileType;
|
||||
import dev.loki.lovisual.config.profile.service.ConfigProfileStorage;
|
||||
|
||||
public record ConfigProfileMeta(
|
||||
String id,
|
||||
String name,
|
||||
ConfigProfileType type,
|
||||
String author,
|
||||
long createdAt,
|
||||
long updatedAt,
|
||||
int version
|
||||
) {
|
||||
public ConfigProfileMeta {
|
||||
if (id == null || id.isBlank()) id = ConfigProfileStorage.sanitizeFileName(name);
|
||||
if (name == null || name.isBlank()) name = id;
|
||||
if (type == null) type = ConfigProfileType.MODULES;
|
||||
if (author == null || author.isBlank()) author = "Unknown";
|
||||
if (version <= 0) version = ConfigProfileBinaryCodec.VERSION;
|
||||
}
|
||||
|
||||
public ConfigProfileMeta withUpdatedAt(long timestamp) {
|
||||
return new ConfigProfileMeta(id, name, type, author, createdAt, timestamp, version);
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public ConfigProfileMeta withName(String nextName, long timestamp) {
|
||||
String nextId = ConfigProfileStorage.sanitizeFileName(nextName);
|
||||
return new ConfigProfileMeta(nextId, nextName, type, author, createdAt, timestamp, version);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.profile.snapshot;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.config.profile.codec.ConfigProfileEntry;
|
||||
import dev.loki.lovisual.config.profile.snapshot.ConfigProfileMeta;
|
||||
|
||||
public record ConfigProfileSnapshot(
|
||||
ConfigProfileMeta meta,
|
||||
List<ConfigProfileEntry> entries
|
||||
) {
|
||||
public ConfigProfileSnapshot {
|
||||
if (meta == null) throw new IllegalArgumentException("profile meta is null");
|
||||
List<ConfigProfileEntry> copy = new ArrayList<>();
|
||||
if (entries != null) copy.addAll(entries);
|
||||
entries = Collections.unmodifiableList(copy);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.collection;
|
||||
|
||||
/**
|
||||
* Базовый тип для всех конфиг-значений.
|
||||
*/
|
||||
public abstract class ConfigValue<T> {
|
||||
|
||||
private final String name; // <---- ЭТО ТЕБЕ НУЖНО
|
||||
protected T value;
|
||||
|
||||
public ConfigValue(String name, T def) {
|
||||
this.name = name;
|
||||
this.value = def;
|
||||
}
|
||||
|
||||
/**
|
||||
* ключ в конфиге
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Текущее значение
|
||||
*/
|
||||
public T get() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Установить новое значение
|
||||
*/
|
||||
public void set(T v) {
|
||||
this.value = v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сериализация:
|
||||
* Возвращает примитив (Boolean, Number, String) или структуру (Map/List).
|
||||
*/
|
||||
public abstract Object toJson();
|
||||
|
||||
/**
|
||||
* Десериализация:
|
||||
* На вход прилетает то же самое, что было возвращено в toJson().
|
||||
*/
|
||||
public abstract void fromJson(Object json);
|
||||
|
||||
/**
|
||||
* Для UI
|
||||
*/
|
||||
public String toDisplay() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,328 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.collection;
|
||||
|
||||
import java.util.*;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.mode.EnumValue;
|
||||
|
||||
/**
|
||||
* Object-shaped per-item PvP cooldown rules.
|
||||
* <p>
|
||||
* JSON shape:
|
||||
* {
|
||||
* "minecraft:golden_apple": {
|
||||
* "enabled": false,
|
||||
* "seconds": 30,
|
||||
* "uses": 2,
|
||||
* "window_seconds": 10,
|
||||
* "scope": "pvp_grace",
|
||||
* "trigger": "consume_finish",
|
||||
* "block_use": false,
|
||||
* "block_mode": "none"
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
public class ItemCooldownRulesValue extends ConfigValue<Map<String, ItemCooldownRulesValue.Rule>> {
|
||||
|
||||
private final Map<String, Rule> defaults = new LinkedHashMap<>();
|
||||
|
||||
public ItemCooldownRulesValue(String name, Map<String, Rule> defaults) {
|
||||
super(name, new LinkedHashMap<>());
|
||||
if (defaults != null) {
|
||||
for (var entry : defaults.entrySet()) {
|
||||
String id = normalizeItemId(entry.getKey());
|
||||
Rule rule = entry.getValue();
|
||||
if (id != null && rule != null) {
|
||||
this.defaults.put(id, rule.normalized());
|
||||
}
|
||||
}
|
||||
}
|
||||
value.putAll(this.defaults);
|
||||
}
|
||||
|
||||
public static String normalizeItemId(String id) {
|
||||
if (id == null) return null;
|
||||
String s = id.trim().toLowerCase(Locale.ROOT);
|
||||
if (s.isEmpty()) return null;
|
||||
if (!s.contains(":")) s = "minecraft:" + s;
|
||||
return s;
|
||||
}
|
||||
|
||||
public Rule getRule(String itemId) {
|
||||
String normalized = normalizeItemId(itemId);
|
||||
if (normalized == null) return null;
|
||||
return value.get(normalized);
|
||||
}
|
||||
|
||||
public Rule getDefaultRule(String itemId) {
|
||||
String normalized = normalizeItemId(itemId);
|
||||
if (normalized != null) {
|
||||
Rule configuredDefault = defaults.get(normalized);
|
||||
if (configuredDefault != null) return configuredDefault;
|
||||
}
|
||||
return new Rule(false, 30, 1, 0, Scope.PVP_GRACE, Trigger.CONSUME_FINISH, UseBlockMode.NONE);
|
||||
}
|
||||
|
||||
public Rule ensureRule(String itemId) {
|
||||
String normalized = normalizeItemId(itemId);
|
||||
if (normalized == null) return null;
|
||||
Rule existing = value.get(normalized);
|
||||
if (existing != null) return existing;
|
||||
Rule created = getDefaultRule(normalized).normalized();
|
||||
value.put(normalized, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
public void putRule(String itemId, Rule rule) {
|
||||
String normalized = normalizeItemId(itemId);
|
||||
if (normalized == null || rule == null) return;
|
||||
value.put(normalized, rule.normalized());
|
||||
}
|
||||
|
||||
public void removeRule(String itemId) {
|
||||
String normalized = normalizeItemId(itemId);
|
||||
if (normalized == null) return;
|
||||
value.remove(normalized);
|
||||
}
|
||||
|
||||
public boolean containsRule(String itemId) {
|
||||
String normalized = normalizeItemId(itemId);
|
||||
return normalized != null && value.containsKey(normalized);
|
||||
}
|
||||
|
||||
public Map<String, Rule> getRules() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public Set<String> getItemIds() {
|
||||
return new LinkedHashSet<>(value.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (var entry : value.entrySet()) {
|
||||
if (entry.getKey() == null || entry.getValue() == null) continue;
|
||||
out.put(entry.getKey(), entry.getValue().toJson());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
value.clear();
|
||||
value.putAll(defaults);
|
||||
|
||||
if (!(json instanceof Map<?, ?> map)) return;
|
||||
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getKey() instanceof String rawKey)) continue;
|
||||
String itemId = normalizeItemId(rawKey);
|
||||
if (itemId == null) continue;
|
||||
|
||||
Rule base = value.getOrDefault(itemId, Rule.DEFAULT);
|
||||
Rule parsed = Rule.fromJson(entry.getValue(), base);
|
||||
if (parsed != null) {
|
||||
value.put(itemId, parsed.normalized());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDisplay() {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
public enum Scope implements EnumValue.IdProvider {
|
||||
ALWAYS("always"),
|
||||
PVP_ONLY("pvp_only"),
|
||||
PVP_GRACE("pvp_grace");
|
||||
|
||||
private final String id;
|
||||
|
||||
Scope(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
static Scope parse(Object value, Scope fallback) {
|
||||
if (value instanceof String s) {
|
||||
String normalized = s.trim().toLowerCase(Locale.ROOT);
|
||||
for (Scope scope : values()) {
|
||||
if (scope.id.equals(normalized) || scope.name().equalsIgnoreCase(normalized)) {
|
||||
return scope;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
public enum Trigger implements EnumValue.IdProvider {
|
||||
INTERACT_ACCEPT("interact_accept"),
|
||||
CONSUME_FINISH("consume_finish"),
|
||||
TOTEM_POP("totem_pop");
|
||||
|
||||
private final String id;
|
||||
|
||||
Trigger(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
static Trigger parse(Object value, Trigger fallback) {
|
||||
if (value instanceof String s) {
|
||||
String normalized = s.trim().toLowerCase(Locale.ROOT);
|
||||
for (Trigger trigger : values()) {
|
||||
if (trigger.id.equals(normalized) || trigger.name().equalsIgnoreCase(normalized)) {
|
||||
return trigger;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
public enum UseBlockMode implements EnumValue.IdProvider {
|
||||
NONE("none"),
|
||||
COOLDOWN("cooldown"),
|
||||
WINDOW("window"),
|
||||
ANY("any");
|
||||
|
||||
private final String id;
|
||||
|
||||
UseBlockMode(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
static UseBlockMode parse(Object value, UseBlockMode fallback) {
|
||||
if (value instanceof String s) {
|
||||
String normalized = s.trim().toLowerCase(Locale.ROOT);
|
||||
for (UseBlockMode mode : values()) {
|
||||
if (mode.id.equals(normalized) || mode.name().equalsIgnoreCase(normalized)) {
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public UseBlockMode next() {
|
||||
UseBlockMode[] modes = values();
|
||||
return modes[(ordinal() + 1) % modes.length];
|
||||
}
|
||||
}
|
||||
|
||||
public record Rule(boolean enabled,
|
||||
int seconds,
|
||||
int uses,
|
||||
int windowSeconds,
|
||||
Scope scope,
|
||||
Trigger trigger,
|
||||
UseBlockMode blockMode) {
|
||||
public static final Rule DEFAULT = new Rule(false, 0, 1, 0, Scope.PVP_GRACE, Trigger.CONSUME_FINISH, UseBlockMode.NONE);
|
||||
|
||||
public Rule(boolean enabled,
|
||||
int seconds,
|
||||
int uses,
|
||||
int windowSeconds,
|
||||
Scope scope,
|
||||
Trigger trigger,
|
||||
boolean blockUse) {
|
||||
this(enabled, seconds, uses, windowSeconds, scope, trigger, blockUse ? UseBlockMode.COOLDOWN : UseBlockMode.NONE);
|
||||
}
|
||||
|
||||
static Rule fromJson(Object json, Rule fallback) {
|
||||
Rule base = fallback != null ? fallback : DEFAULT;
|
||||
if (!(json instanceof Map<?, ?> map)) return base;
|
||||
|
||||
boolean enabled = readBoolean(map, "enabled", base.enabled);
|
||||
int seconds = readInt(map, "seconds", base.seconds);
|
||||
int uses = readInt(map, "uses", base.uses);
|
||||
int windowSeconds = readInt(map, "window_seconds", base.windowSeconds);
|
||||
Scope scope = Scope.parse(map.get("scope"), base.scope);
|
||||
Trigger trigger = Trigger.parse(map.get("trigger"), base.trigger);
|
||||
UseBlockMode blockMode = UseBlockMode.parse(map.get("block_mode"), null);
|
||||
if (blockMode == null) {
|
||||
blockMode = readBoolean(map, "block_use", base.blockUse()) ? UseBlockMode.COOLDOWN : UseBlockMode.NONE;
|
||||
}
|
||||
|
||||
return new Rule(enabled, seconds, uses, windowSeconds, scope, trigger, blockMode);
|
||||
}
|
||||
|
||||
private static boolean readBoolean(Map<?, ?> map, String key, boolean fallback) {
|
||||
Object value = map.get(key);
|
||||
if (value instanceof Boolean b) return b;
|
||||
if (value instanceof String s) return Boolean.parseBoolean(s.trim());
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private static int readInt(Map<?, ?> map, String key, int fallback) {
|
||||
Object value = map.get(key);
|
||||
if (value instanceof Number n) return n.intValue();
|
||||
if (value instanceof String s) {
|
||||
try {
|
||||
return Integer.parseInt(s.trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
public Rule normalized() {
|
||||
int safeSeconds = Math.max(0, Math.min(3600, seconds));
|
||||
int safeUses = Math.max(1, Math.min(64, uses));
|
||||
int safeWindow = Math.max(0, Math.min(3600, windowSeconds));
|
||||
return new Rule(
|
||||
enabled,
|
||||
safeSeconds,
|
||||
safeUses,
|
||||
safeWindow,
|
||||
scope != null ? scope : Scope.PVP_GRACE,
|
||||
trigger != null ? trigger : Trigger.CONSUME_FINISH,
|
||||
blockMode != null ? blockMode : UseBlockMode.NONE
|
||||
);
|
||||
}
|
||||
|
||||
public boolean hasUseWindow() {
|
||||
return uses > 1;
|
||||
}
|
||||
|
||||
public boolean blockUse() {
|
||||
return blockMode != null && blockMode != UseBlockMode.NONE;
|
||||
}
|
||||
|
||||
Map<String, Object> toJson() {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("enabled", enabled);
|
||||
out.put("seconds", seconds);
|
||||
out.put("uses", uses);
|
||||
out.put("window_seconds", windowSeconds);
|
||||
out.put("scope", scope.getId());
|
||||
out.put("trigger", trigger.getId());
|
||||
out.put("block_use", blockUse());
|
||||
out.put("block_mode", (blockMode != null ? blockMode : UseBlockMode.NONE).getId());
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.collection;
|
||||
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
/**
|
||||
* Хранит набор item-id в формате namespace:path (minecraft:xxx).
|
||||
*/
|
||||
public class ItemIdSetValue extends ConfigValue<Set<String>> {
|
||||
|
||||
public ItemIdSetValue(String name) {
|
||||
super(name, new LinkedHashSet<>());
|
||||
}
|
||||
|
||||
public ItemIdSetValue(String name, Set<String> def) {
|
||||
super(name, normalizeCopy(def));
|
||||
}
|
||||
|
||||
private static LinkedHashSet<String> normalizeCopy(Set<String> source) {
|
||||
LinkedHashSet<String> copy = new LinkedHashSet<>();
|
||||
if (source == null) return copy;
|
||||
|
||||
for (String s : source) {
|
||||
String norm = normalizeStatic(s);
|
||||
if (norm != null) copy.add(norm);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String normalizeStatic(String s) {
|
||||
if (s == null || s.isBlank()) return null;
|
||||
s = s.trim().toLowerCase();
|
||||
if (!s.contains(":")) s = "minecraft:" + s;
|
||||
return s;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(Set<String> v) {
|
||||
super.set(normalizeCopy(v));
|
||||
log("set()", value);
|
||||
}
|
||||
|
||||
private String normalize(String s) {
|
||||
return normalizeStatic(s);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
log("toJson()", value);
|
||||
return new java.util.ArrayList<>(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof List<?> list) {
|
||||
LinkedHashSet<String> copy = new LinkedHashSet<>();
|
||||
for (Object o : list) {
|
||||
if (o instanceof String s) {
|
||||
String norm = normalize(s);
|
||||
if (norm != null) copy.add(norm);
|
||||
}
|
||||
}
|
||||
value = copy;
|
||||
log("fromJson()", value);
|
||||
}
|
||||
}
|
||||
|
||||
private void log(String stage, Set<String> data) {
|
||||
DebugLog.config("[ItemIdSetValue %s] %s -> %s", getName(), stage, data);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.collection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class SetValue extends ConfigValue<Set<String>> {
|
||||
|
||||
public SetValue(String name) {
|
||||
super(name, new LinkedHashSet<>());
|
||||
}
|
||||
|
||||
public SetValue(String name, Set<String> def) {
|
||||
super(name, new LinkedHashSet<>(def));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(Set<String> v) {
|
||||
value = v == null ? new LinkedHashSet<>() : new LinkedHashSet<>(v);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return new ArrayList<>(value); // JSON array
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof List<?> list) {
|
||||
LinkedHashSet<String> copy = new LinkedHashSet<>();
|
||||
for (Object o : list) {
|
||||
if (o instanceof String s)
|
||||
copy.add(s);
|
||||
}
|
||||
value = copy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.color;
|
||||
|
||||
public interface ColorValue {
|
||||
String get();
|
||||
|
||||
void set(String value);
|
||||
|
||||
int getArgb();
|
||||
|
||||
boolean supportsAlpha();
|
||||
|
||||
boolean isRainbow();
|
||||
|
||||
String toRainbowValue();
|
||||
|
||||
String rainbowFallbackHex();
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.color;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class KeyBindValue extends ConfigValue<String> {
|
||||
|
||||
public KeyBindValue(String name, String def) {
|
||||
super(name, def == null ? "NONE" : def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof String s)
|
||||
this.value = s.toUpperCase();
|
||||
}
|
||||
|
||||
public boolean isNone() {
|
||||
return "NONE".equalsIgnoreCase(value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.color;
|
||||
|
||||
import dev.loki.lovisual.render.engine.color.ColorUtils;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.color.ColorValue;
|
||||
|
||||
/**
|
||||
* Keeps color as hex-string and provides access as ARGB int.
|
||||
* Supported formats: #RRGGBB, #AARRGGBB, 0xRRGGBB, 0xAARRGGBB.
|
||||
*/
|
||||
public class RGBAColorValue extends ConfigValue<String> implements ColorValue {
|
||||
|
||||
private static final int RAINBOW_SPEED = 18;
|
||||
|
||||
public RGBAColorValue(String name, String defHex) {
|
||||
super(name, normalize(defHex));
|
||||
}
|
||||
|
||||
public static boolean isRainbowValue(String s) {
|
||||
if (s == null) return false;
|
||||
String t = s.trim().toUpperCase();
|
||||
return t.startsWith("RNB") || t.startsWith("RAINBOW");
|
||||
}
|
||||
|
||||
public static boolean isRgbaValue(String s) {
|
||||
if (s == null) return false;
|
||||
String t = s.trim().toUpperCase();
|
||||
return t.startsWith("RGBA");
|
||||
}
|
||||
|
||||
public static String toRainbow(String hex) {
|
||||
int argb = parseToArgb(hex);
|
||||
return "RNB#" + String.format("%08X", argb);
|
||||
}
|
||||
|
||||
public static String rainbowFallbackHex(String s) {
|
||||
int argb = rainbowFallbackArgb(s);
|
||||
return String.format("#%02X%02X%02X%02X",
|
||||
(argb >>> 24) & 0xFF,
|
||||
(argb >>> 16) & 0xFF,
|
||||
(argb >>> 8) & 0xFF,
|
||||
argb & 0xFF);
|
||||
}
|
||||
|
||||
private static String normalize(String s) {
|
||||
if (s == null || s.isEmpty()) return "#FFFFFFFF"; // white
|
||||
s = s.trim();
|
||||
if (isRainbowValue(s)) return normalizeRainbow(s);
|
||||
boolean rgba = isRgbaValue(s);
|
||||
if (rgba) {
|
||||
s = stripRgbaPrefix(s);
|
||||
}
|
||||
if (s.startsWith("0x") || s.startsWith("0X")) s = s.substring(2);
|
||||
if (!s.startsWith("#")) s = "#" + s;
|
||||
s = s.toUpperCase();
|
||||
return rgba ? "RGBA" + s : s;
|
||||
}
|
||||
|
||||
private static String normalizeRainbow(String s) {
|
||||
if (s == null) return "RNB";
|
||||
String upper = s.trim().toUpperCase();
|
||||
String tail = upper.startsWith("RAINBOW") ? upper.substring(7) : upper.substring(3);
|
||||
tail = tail.trim();
|
||||
if (!tail.isEmpty() && (tail.charAt(0) == ':' || tail.charAt(0) == '=')) {
|
||||
tail = tail.substring(1).trim();
|
||||
}
|
||||
if (tail.startsWith("#")) tail = tail.substring(1);
|
||||
if (tail.startsWith("0X")) tail = tail.substring(2);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (int i = 0; i < tail.length(); i++) {
|
||||
char c = tail.charAt(i);
|
||||
boolean digit = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
|
||||
if (digit) hex.append(c);
|
||||
}
|
||||
if (hex.length() == 6) hex.insert(0, "FF");
|
||||
if (hex.length() == 8) {
|
||||
return "RNB#" + hex;
|
||||
}
|
||||
return "RNB";
|
||||
}
|
||||
|
||||
private static int rainbowFallbackArgb(String s) {
|
||||
if (s == null) return 0xFFFFFFFF;
|
||||
int hash = s.indexOf('#');
|
||||
if (hash >= 0 && hash + 1 < s.length()) {
|
||||
return parseToArgb(s.substring(hash));
|
||||
}
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
private static int parseToArgb(String hex) {
|
||||
if (hex == null || hex.isEmpty()) return 0xFFFFFFFF;
|
||||
boolean rgba = isRgbaValue(hex);
|
||||
String cleaned = rgba ? stripRgbaPrefix(hex) : hex;
|
||||
String s = cleaned.startsWith("#") ? cleaned.substring(1) : cleaned;
|
||||
if (s.startsWith("0x") || s.startsWith("0X")) s = s.substring(2);
|
||||
long v;
|
||||
try {
|
||||
v = Long.parseUnsignedLong(s, 16);
|
||||
} catch (NumberFormatException e) {
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
if (s.length() == 6) {
|
||||
return (int) (0xFF000000L | v); // add full alpha
|
||||
} else if (s.length() == 8) {
|
||||
int value = (int) v;
|
||||
if (!rgba) {
|
||||
return value; // AARRGGBB
|
||||
}
|
||||
int r = (value >>> 24) & 0xFF;
|
||||
int g = (value >>> 16) & 0xFF;
|
||||
int b = (value >>> 8) & 0xFF;
|
||||
int a = value & 0xFF;
|
||||
return (a << 24) | (r << 16) | (g << 8) | b;
|
||||
}
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
private static String stripRgbaPrefix(String s) {
|
||||
if (s == null) return "";
|
||||
String t = s.trim();
|
||||
if (t.length() >= 4 && t.substring(0, 4).equalsIgnoreCase("RGBA")) {
|
||||
t = t.substring(4).trim();
|
||||
if (!t.isEmpty()) {
|
||||
char c = t.charAt(0);
|
||||
if (c == ':' || c == '=') {
|
||||
t = t.substring(1).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof String s) value = normalize(s);
|
||||
}
|
||||
|
||||
public int getArgb() {
|
||||
if (isRainbowValue(value)) {
|
||||
int fallback = rainbowFallbackArgb(value);
|
||||
int alpha = (fallback >>> 24) & 0xFF;
|
||||
float opacity = alpha / 255.0f;
|
||||
return ColorUtils
|
||||
.rainbow(RAINBOW_SPEED, 0, 1f, 1f, opacity)
|
||||
.getRGB();
|
||||
}
|
||||
return parseToArgb(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsAlpha() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRainbow() {
|
||||
return isRainbowValue(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toRainbowValue() {
|
||||
return toRainbow(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String rainbowFallbackHex() {
|
||||
return rainbowFallbackHex(value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.color;
|
||||
|
||||
import dev.loki.lovisual.render.engine.color.ColorUtils;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.color.ColorValue;
|
||||
|
||||
/**
|
||||
* Цвет без альфы. Хранится как hex "#RRGGBB" и возвращается с полной альфой (0xFF) при запросе ARGB.
|
||||
* Допустимые входные форматы: #RRGGBB, #AARRGGBB, 0xRRGGBB, 0xAARRGGBB.
|
||||
*/
|
||||
public class RGBColorValue extends ConfigValue<String> implements ColorValue {
|
||||
|
||||
private static final int RAINBOW_SPEED = 18;
|
||||
|
||||
public RGBColorValue(String name, String defHex) {
|
||||
super(name, normalize(defHex));
|
||||
}
|
||||
|
||||
public static boolean isRainbowValue(String s) {
|
||||
if (s == null) return false;
|
||||
String t = s.trim().toUpperCase();
|
||||
return t.startsWith("RNB") || t.startsWith("RAINBOW");
|
||||
}
|
||||
|
||||
public static String toRainbow(String hex) {
|
||||
int rgb = parseRgb(hex);
|
||||
return "RNB#" + String.format("%06X", rgb & 0xFFFFFF);
|
||||
}
|
||||
|
||||
public static String rainbowFallbackHex(String s) {
|
||||
int rgb = rainbowFallbackRgb(s);
|
||||
return String.format("#%02X%02X%02X",
|
||||
(rgb >>> 16) & 0xFF,
|
||||
(rgb >>> 8) & 0xFF,
|
||||
rgb & 0xFF);
|
||||
}
|
||||
|
||||
private static String normalize(String s) {
|
||||
if (s == null || s.isEmpty()) return "#FFFFFF"; // white RGB
|
||||
s = s.trim();
|
||||
if (isRainbowValue(s)) return normalizeRainbow(s);
|
||||
if (s.startsWith("0x") || s.startsWith("0X")) s = s.substring(2);
|
||||
if (s.startsWith("#")) s = s.substring(1);
|
||||
|
||||
// s is now hex without prefix; allow 6 or 8 digits, drop alpha if present
|
||||
if (s.length() == 8) {
|
||||
s = s.substring(2); // drop AA
|
||||
}
|
||||
if (s.length() != 6) {
|
||||
return "#FFFFFF";
|
||||
}
|
||||
return ("#" + s).toUpperCase();
|
||||
}
|
||||
|
||||
private static String normalizeRainbow(String s) {
|
||||
if (s == null) return "RNB";
|
||||
String upper = s.trim().toUpperCase();
|
||||
String tail = upper.startsWith("RAINBOW") ? upper.substring(7) : upper.substring(3);
|
||||
tail = tail.trim();
|
||||
if (!tail.isEmpty() && (tail.charAt(0) == ':' || tail.charAt(0) == '=')) {
|
||||
tail = tail.substring(1).trim();
|
||||
}
|
||||
if (tail.startsWith("#")) tail = tail.substring(1);
|
||||
if (tail.startsWith("0X")) tail = tail.substring(2);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (int i = 0; i < tail.length(); i++) {
|
||||
char c = tail.charAt(i);
|
||||
boolean digit = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
|
||||
if (digit) hex.append(c);
|
||||
}
|
||||
if (hex.length() >= 6) {
|
||||
String tail6 = hex.substring(hex.length() - 6);
|
||||
return "RNB#" + tail6;
|
||||
}
|
||||
return "RNB";
|
||||
}
|
||||
|
||||
private static int rainbowFallbackRgb(String s) {
|
||||
if (s == null) return 0xFFFFFF;
|
||||
int hash = s.indexOf('#');
|
||||
if (hash >= 0 && hash + 1 < s.length()) {
|
||||
return parseRgb(s.substring(hash));
|
||||
}
|
||||
return 0xFFFFFF;
|
||||
}
|
||||
|
||||
private static int parseRgb(String hex) {
|
||||
if (hex == null || hex.isEmpty()) return 0xFFFFFF;
|
||||
String s = hex.startsWith("#") ? hex.substring(1) : hex;
|
||||
try {
|
||||
return Integer.parseUnsignedInt(s, 16);
|
||||
} catch (NumberFormatException e) {
|
||||
return 0xFFFFFF;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof String s) value = normalize(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает цвет как ARGB с полной альфой (0xFF).
|
||||
*/
|
||||
public int getArgb() {
|
||||
if (isRainbowValue(value)) {
|
||||
return ColorUtils
|
||||
.rainbow(RAINBOW_SPEED, 0, 1f, 1f, 1f)
|
||||
.getRGB();
|
||||
}
|
||||
return 0xFF000000 | parseRgb(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsAlpha() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRainbow() {
|
||||
return isRainbowValue(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toRainbowValue() {
|
||||
return toRainbow(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String rainbowFallbackHex() {
|
||||
return rainbowFallbackHex(value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.mode;
|
||||
|
||||
public enum BindMode {
|
||||
PRESS,
|
||||
HOLD
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.mode;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum EnumIds {
|
||||
;
|
||||
|
||||
public static String defaultId(Enum<?> value) {
|
||||
if (value == null) return "";
|
||||
return value.name().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,117 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.mode;
|
||||
|
||||
import java.util.*;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
import dev.loki.lovisual.config.values.mode.EnumIds;
|
||||
|
||||
public class EnumValue<E extends Enum<E>> extends ConfigValue<E> {
|
||||
|
||||
private final List<E> options;
|
||||
private final List<String> optionIds;
|
||||
private final Map<String, E> lookup;
|
||||
public EnumValue(String name, E def, Class<E> enumClass) {
|
||||
this(name, def, enumClass.getEnumConstants());
|
||||
}
|
||||
@SafeVarargs
|
||||
public EnumValue(String name, E def, E... opts) {
|
||||
super(name, def);
|
||||
this.options = List.of(opts);
|
||||
this.optionIds = new ArrayList<>(options.size());
|
||||
this.lookup = new HashMap<>();
|
||||
|
||||
for (E opt : options) {
|
||||
String id = idOf(opt);
|
||||
optionIds.add(id);
|
||||
lookup.put(normalize(id), opt);
|
||||
}
|
||||
|
||||
for (E opt : options) {
|
||||
if (!(opt instanceof AliasProvider aliasProvider)) continue;
|
||||
List<String> aliases = aliasProvider.aliases();
|
||||
if (aliases == null) continue;
|
||||
for (String alias : aliases) {
|
||||
if (alias == null || alias.isBlank()) continue;
|
||||
lookup.putIfAbsent(normalize(alias), opt);
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.contains(def) && !options.isEmpty()) {
|
||||
this.value = options.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalize(String id) {
|
||||
return id == null ? "" : id.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public List<String> getOptions() {
|
||||
return optionIds;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return idOf(value);
|
||||
}
|
||||
|
||||
public void setById(String id) {
|
||||
if (id == null) return;
|
||||
E resolved = lookup.get(normalize(id));
|
||||
if (resolved != null) {
|
||||
value = resolved;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof String s) {
|
||||
setById(s);
|
||||
}
|
||||
}
|
||||
|
||||
private String idOf(E value) {
|
||||
if (value instanceof IdProvider idProvider) {
|
||||
return idProvider.getId();
|
||||
}
|
||||
return EnumIds.defaultId(value);
|
||||
}
|
||||
|
||||
public interface IdProvider {
|
||||
default String getId() {
|
||||
return id();
|
||||
}
|
||||
|
||||
default String id() {
|
||||
try {
|
||||
var method = getClass().getMethod("getId");
|
||||
if (method.getReturnType() == String.class && method.getParameterCount() == 0) {
|
||||
return (String) method.invoke(this);
|
||||
}
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
// Fall back to the enum name below.
|
||||
}
|
||||
|
||||
if (this instanceof Enum<?> enumValue) {
|
||||
return EnumIds.defaultId(enumValue);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public interface AliasProvider {
|
||||
default List<String> aliases() {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.mode;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class ModeValue extends ConfigValue<String> {
|
||||
|
||||
private final List<String> options;
|
||||
|
||||
public ModeValue(String name, String def, String... opts) {
|
||||
super(name, def);
|
||||
this.options = new ArrayList<>(Arrays.asList(opts));
|
||||
|
||||
// если default не валидный → ставим первый вариант
|
||||
if (!options.contains(def)) {
|
||||
this.value = options.get(0);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getOptions() {
|
||||
return List.copyOf(options);
|
||||
}
|
||||
|
||||
public boolean addOption(String option) {
|
||||
String normalized = normalizeOption(option);
|
||||
if (normalized.isEmpty() || options.contains(normalized)) return false;
|
||||
options.add(normalized);
|
||||
return true;
|
||||
}
|
||||
|
||||
public int addOptions(Collection<String> values) {
|
||||
if (values == null || values.isEmpty()) return 0;
|
||||
int added = 0;
|
||||
for (String value : values) {
|
||||
if (addOption(value)) added++;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
public boolean removeOption(String option) {
|
||||
String normalized = normalizeOption(option);
|
||||
if (normalized.isEmpty()) return false;
|
||||
if (Objects.equals(value, normalized)) return false;
|
||||
return options.remove(normalized);
|
||||
}
|
||||
|
||||
public void next() {
|
||||
int i = options.indexOf(value);
|
||||
value = options.get((i + 1) % options.size());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof String s && options.contains(s)) {
|
||||
value = s;
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeOption(String option) {
|
||||
return option == null ? "" : option.trim();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.primitive;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class BooleanMapValue extends ConfigValue<Map<String, Boolean>> {
|
||||
|
||||
private final Map<String, Boolean> defaults = new LinkedHashMap<>();
|
||||
|
||||
public BooleanMapValue(String name, Map<String, Boolean> defaults) {
|
||||
super(name, new LinkedHashMap<>());
|
||||
this.defaults.putAll(defaults);
|
||||
value.putAll(defaults);
|
||||
}
|
||||
|
||||
public Map<String, Boolean> getAll() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public boolean get(String key) {
|
||||
return value.getOrDefault(key, false);
|
||||
}
|
||||
|
||||
public void set(String key, boolean val) {
|
||||
value.put(key, val);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return new LinkedHashMap<>(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
value.clear();
|
||||
// start with defaults so new keys always exist
|
||||
value.putAll(defaults);
|
||||
if (json instanceof Map<?, ?> map) {
|
||||
for (var entry : map.entrySet()) {
|
||||
if (entry.getKey() instanceof String key &&
|
||||
entry.getValue() instanceof Boolean b &&
|
||||
defaults.containsKey(key)) {
|
||||
value.put(key, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDisplay() {
|
||||
return value.toString();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.primitive;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class BooleanValue extends ConfigValue<Boolean> {
|
||||
|
||||
public BooleanValue(String name, boolean def) {
|
||||
super(name, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof Boolean b)
|
||||
value = b;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.primitive;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class NumberValue<N extends Number> extends ConfigValue<N> {
|
||||
|
||||
private final N min, max;
|
||||
|
||||
public NumberValue(String name, N def, N min, N max) {
|
||||
super(name, def);
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
clamp();
|
||||
}
|
||||
|
||||
public N getMin() {
|
||||
return min;
|
||||
}
|
||||
|
||||
public N getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
private void clamp() {
|
||||
double v = value.doubleValue();
|
||||
double lo = min.doubleValue();
|
||||
double hi = max.doubleValue();
|
||||
|
||||
if (v < lo) value = castToType(lo);
|
||||
else if (v > hi) value = castToType(hi);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public N castToType(double v) {
|
||||
if (value instanceof Integer) return (N) Integer.valueOf((int) v);
|
||||
if (value instanceof Float) return (N) Float.valueOf((float) v);
|
||||
if (value instanceof Long) return (N) Long.valueOf((long) v);
|
||||
return (N) Double.valueOf(v);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
double v = value.doubleValue();
|
||||
if (value instanceof Float || value instanceof Double) {
|
||||
v = Math.round(v * 100d) / 100d;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof Number n) {
|
||||
value = castToType(n.doubleValue());
|
||||
clamp();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDisplay() {
|
||||
if (value instanceof Float || value instanceof Double) {
|
||||
return new DecimalFormat("0.##").format(value.doubleValue());
|
||||
}
|
||||
return super.toDisplay();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.config.values.primitive;
|
||||
import dev.loki.lovisual.config.values.collection.ConfigValue;
|
||||
|
||||
public class StringValue extends ConfigValue<String> {
|
||||
|
||||
public StringValue(String name, String def) {
|
||||
super(name, def);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object toJson() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fromJson(Object json) {
|
||||
if (json instanceof String s)
|
||||
this.value = s;
|
||||
}
|
||||
}
|
||||
21
mod/src/main/java/dev/loki/lovisual/events/Event.java
Normal file
21
mod/src/main/java/dev/loki/lovisual/events/Event.java
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public class Event {
|
||||
private boolean cancelled;
|
||||
|
||||
public void cancel() {
|
||||
cancelled = true;
|
||||
}
|
||||
}
|
||||
264
mod/src/main/java/dev/loki/lovisual/events/EventBus.java
Normal file
264
mod/src/main/java/dev/loki/lovisual/events/EventBus.java
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import dev.loki.lovisual.features.module.core.Module;
|
||||
import dev.loki.lovisual.Lifecycle;
|
||||
import dev.loki.lovisual.util.logging.DebugLog;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import dev.loki.lovisual.events.meta.EventHandler;
|
||||
|
||||
public final class EventBus {
|
||||
private static final Subscriber[] EMPTY_SUBSCRIBERS = new Subscriber[0];
|
||||
private static final Comparator<Subscriber> PRIORITY =
|
||||
Comparator.comparingInt((Subscriber sub) -> sub.priority).reversed();
|
||||
|
||||
private final Object lock = new Object();
|
||||
|
||||
private final Reference2ObjectOpenHashMap<Class<?>, Subscriber[]> exactHandlers = new Reference2ObjectOpenHashMap<>();
|
||||
private final Reference2ObjectOpenHashMap<Class<?>, Subscriber[]> dispatchCache = new Reference2ObjectOpenHashMap<>();
|
||||
private final Reference2ObjectOpenHashMap<Object, Subscriber[]> ownerIndex = new Reference2ObjectOpenHashMap<>();
|
||||
|
||||
private static Subscriber[] append(Subscriber[] old, Subscriber sub) {
|
||||
Subscriber[] next = Arrays.copyOf(old, old.length + 1);
|
||||
next[old.length] = sub;
|
||||
return next;
|
||||
}
|
||||
|
||||
private static Subscriber[] remove(Subscriber[] old, Subscriber sub) {
|
||||
int index = -1;
|
||||
for (int i = 0; i < old.length; i++) {
|
||||
if (old[i] == sub) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (index < 0) return old;
|
||||
if (old.length == 1) return EMPTY_SUBSCRIBERS;
|
||||
|
||||
Subscriber[] next = new Subscriber[old.length - 1];
|
||||
System.arraycopy(old, 0, next, 0, index);
|
||||
System.arraycopy(old, index + 1, next, index, old.length - index - 1);
|
||||
return next;
|
||||
}
|
||||
|
||||
private static void sortSubscribers(Subscriber[] subscribers) {
|
||||
Arrays.sort(subscribers, PRIORITY);
|
||||
}
|
||||
|
||||
public void register(Object listener) {
|
||||
if (listener instanceof Module module) {
|
||||
registerOwned(module, listener);
|
||||
} else {
|
||||
registerOwned(null, listener);
|
||||
}
|
||||
}
|
||||
|
||||
public void registerOwned(Module gateModule, Object listener) {
|
||||
if (listener == null) return;
|
||||
|
||||
synchronized (lock) {
|
||||
if (ownerIndex.containsKey(listener)) return;
|
||||
|
||||
Subscriber[] subs = scan(listener, gateModule);
|
||||
if (subs.length == 0) return;
|
||||
|
||||
ownerIndex.put(listener, subs);
|
||||
for (Subscriber sub : subs) {
|
||||
Subscriber[] old = exactHandlers.get(sub.eventType);
|
||||
if (old == null) old = EMPTY_SUBSCRIBERS;
|
||||
Subscriber[] next = append(old, sub);
|
||||
sortSubscribers(next);
|
||||
exactHandlers.put(sub.eventType, next);
|
||||
}
|
||||
|
||||
dispatchCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void unregister(Object listener) {
|
||||
if (listener == null) return;
|
||||
|
||||
synchronized (lock) {
|
||||
Subscriber[] subs = ownerIndex.remove(listener);
|
||||
if (subs == null || subs.length == 0) return;
|
||||
|
||||
for (Subscriber sub : subs) {
|
||||
Subscriber[] old = exactHandlers.get(sub.eventType);
|
||||
if (old == null || old.length == 0) continue;
|
||||
|
||||
Subscriber[] next = remove(old, sub);
|
||||
if (next.length == 0) {
|
||||
exactHandlers.remove(sub.eventType);
|
||||
} else {
|
||||
exactHandlers.put(sub.eventType, next);
|
||||
}
|
||||
}
|
||||
|
||||
dispatchCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasListeners(Class<? extends Event> eventType) {
|
||||
return subscribersFor(eventType).length != 0;
|
||||
}
|
||||
|
||||
public <T extends Event> T post(T event) {
|
||||
if (event == null) return null;
|
||||
if (!Lifecycle.isActive()) return event;
|
||||
|
||||
Subscriber[] subscribers = subscribersFor(event.getClass());
|
||||
for (Subscriber sub : subscribers) {
|
||||
Module gate = sub.gateModule;
|
||||
if (gate != null && !gate.isEnabled()) continue;
|
||||
|
||||
try {
|
||||
sub.invoker.invoke(event);
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("Event handler failed: %s", t, sub.describe());
|
||||
}
|
||||
}
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
synchronized (lock) {
|
||||
exactHandlers.clear();
|
||||
dispatchCache.clear();
|
||||
ownerIndex.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public int listenerCount() {
|
||||
synchronized (lock) {
|
||||
return ownerIndex.size();
|
||||
}
|
||||
}
|
||||
|
||||
private Subscriber[] scan(Object listener, Module gateModule) {
|
||||
List<Subscriber> out = new ArrayList<>();
|
||||
Class<?> cls = listener.getClass();
|
||||
|
||||
for (Method method : cls.getDeclaredMethods()) {
|
||||
if (!method.isAnnotationPresent(EventHandler.class)) continue;
|
||||
|
||||
Class<?>[] params = method.getParameterTypes();
|
||||
if (params.length != 1) continue;
|
||||
if (!Event.class.isAssignableFrom(params[0])) continue;
|
||||
|
||||
EventHandler meta = method.getAnnotation(EventHandler.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Class<? extends Event> eventType = (Class<? extends Event>) params[0];
|
||||
|
||||
EventInvoker invoker = createInvoker(listener, method);
|
||||
out.add(new Subscriber(listener, gateModule, method, invoker, eventType, meta.priority()));
|
||||
}
|
||||
|
||||
return out.toArray(Subscriber[]::new);
|
||||
}
|
||||
|
||||
private EventInvoker createInvoker(Object listener, Method method) {
|
||||
method.setAccessible(true);
|
||||
try {
|
||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||
MethodHandle handle = lookup.unreflect(method).bindTo(listener);
|
||||
return handle::invoke;
|
||||
} catch (Throwable t) {
|
||||
DebugLog.error("Failed to create MethodHandle event invoker, falling back to reflection: %s", t,
|
||||
listener.getClass().getName() + "#" + method.getName());
|
||||
return event -> method.invoke(listener, event);
|
||||
}
|
||||
}
|
||||
|
||||
private Subscriber[] subscribersFor(Class<?> eventType) {
|
||||
if (eventType == null) return EMPTY_SUBSCRIBERS;
|
||||
|
||||
synchronized (lock) {
|
||||
Subscriber[] cached = dispatchCache.get(eventType);
|
||||
if (cached != null) return cached;
|
||||
|
||||
Subscriber[] built = buildFlattenedSubscribers(eventType);
|
||||
dispatchCache.put(eventType, built);
|
||||
return built;
|
||||
}
|
||||
}
|
||||
|
||||
private Subscriber[] buildFlattenedSubscribers(Class<?> eventType) {
|
||||
int total = 0;
|
||||
|
||||
Class<?> type = eventType;
|
||||
while (type != null && Event.class.isAssignableFrom(type)) {
|
||||
Subscriber[] exact = exactHandlers.get(type);
|
||||
if (exact != null) total += exact.length;
|
||||
type = type.getSuperclass();
|
||||
}
|
||||
|
||||
if (total == 0) return EMPTY_SUBSCRIBERS;
|
||||
|
||||
Subscriber[] out = new Subscriber[total];
|
||||
int offset = 0;
|
||||
|
||||
type = eventType;
|
||||
while (type != null && Event.class.isAssignableFrom(type)) {
|
||||
Subscriber[] exact = exactHandlers.get(type);
|
||||
if (exact != null && exact.length > 0) {
|
||||
System.arraycopy(exact, 0, out, offset, exact.length);
|
||||
offset += exact.length;
|
||||
}
|
||||
type = type.getSuperclass();
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface EventInvoker {
|
||||
void invoke(Event event) throws Throwable;
|
||||
}
|
||||
|
||||
private static final class Subscriber {
|
||||
final Object owner;
|
||||
final Module gateModule;
|
||||
final Method method;
|
||||
final EventInvoker invoker;
|
||||
final Class<? extends Event> eventType;
|
||||
final int priority;
|
||||
final String description;
|
||||
|
||||
Subscriber(Object owner,
|
||||
Module gateModule,
|
||||
Method method,
|
||||
EventInvoker invoker,
|
||||
Class<? extends Event> eventType,
|
||||
int priority) {
|
||||
this.owner = owner;
|
||||
this.gateModule = gateModule;
|
||||
this.method = method;
|
||||
this.invoker = invoker;
|
||||
this.eventType = eventType;
|
||||
this.priority = priority;
|
||||
this.description = owner.getClass().getName() + "#" + method.getName();
|
||||
}
|
||||
|
||||
String describe() {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
}
|
||||
14
mod/src/main/java/dev/loki/lovisual/events/Events.java
Normal file
14
mod/src/main/java/dev/loki/lovisual/events/Events.java
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events;
|
||||
|
||||
public enum Events {
|
||||
;
|
||||
public static final EventBus BUS = new EventBus();
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events.impl.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import dev.loki.lovisual.events.Event;
|
||||
|
||||
@Getter
|
||||
public final class AttackEntityEvent extends Event {
|
||||
private final Player player;
|
||||
private final Entity target;
|
||||
|
||||
public AttackEntityEvent(Player player, Entity target) {
|
||||
this.player = player;
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events.impl.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import dev.loki.lovisual.events.Event;
|
||||
|
||||
@Getter
|
||||
public final class CrosshairTargetUpdateEvent extends Event {
|
||||
private final float tickDelta;
|
||||
@Setter
|
||||
private HitResult hitResult;
|
||||
@Setter
|
||||
private Entity targetedEntity;
|
||||
|
||||
public CrosshairTargetUpdateEvent(float tickDelta, HitResult hitResult, Entity targetedEntity) {
|
||||
this.tickDelta = tickDelta;
|
||||
this.hitResult = hitResult;
|
||||
this.targetedEntity = targetedEntity;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events.impl.entity;
|
||||
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import dev.loki.lovisual.events.Event;
|
||||
import dev.loki.lovisual.util.target.TargetManager;
|
||||
|
||||
/**
|
||||
* Fired when the centralized target changes.
|
||||
*/
|
||||
public class EventTargetChanged extends Event {
|
||||
public final LivingEntity previous;
|
||||
public final TargetManager.Source previousSource;
|
||||
public final LivingEntity current;
|
||||
public final TargetManager.Source currentSource;
|
||||
|
||||
public EventTargetChanged(LivingEntity previous,
|
||||
TargetManager.Source previousSource,
|
||||
LivingEntity current,
|
||||
TargetManager.Source currentSource) {
|
||||
this.previous = previous;
|
||||
this.previousSource = previousSource;
|
||||
this.current = current;
|
||||
this.currentSource = currentSource;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.events.impl.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import dev.loki.lovisual.events.Event;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public final class FireworkEvent extends Event {
|
||||
private Vec3 vector;
|
||||
|
||||
public FireworkEvent(Vec3 vector) {
|
||||
this.vector = vector;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue