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:
loki5512344 2026-09-23 22:38:08 +02:00
parent ec10395511
commit 9d08fa910a
2239 changed files with 35265 additions and 28110 deletions

View 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.features.command.impl;
import dev.loki.lovisual.features.command.ClientCommand;
import dev.loki.lovisual.features.command.CommandContext;
import dev.loki.lovisual.features.command.CommandInfo;
import dev.loki.lovisual.features.command.CommandOutput;
import dev.loki.lovisual.render.engine.profiler.FrameStutterProfiler;
import dev.loki.lovisual.render.engine.profiler.JfrProfiler;
import dev.loki.lovisual.render.engine.profiler.ProfilerSettings;
import dev.loki.lovisual.render.engine.profiler.TracyProfiler;
import dev.loki.lovisual.Lifecycle;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@CommandInfo(
id = "profiler",
aliases = "prof",
usage = "@profiler [2d|3d|all|sample|stutter|tracy|jfr] ...",
descriptionKey = "command.profiler.description"
)
public final class ProfilerCommand implements ClientCommand {
@Override
public boolean isAvailable() {
return Lifecycle.isActive();
}
@Override
public boolean execute(CommandContext ctx) {
if (!Lifecycle.isActive()) {
CommandOutput.send("Profiler: disabled until client is active.");
return true;
}
String target = ctx.arg(0);
if (target == null
|| !(target.equalsIgnoreCase("2d")
|| target.equalsIgnoreCase("3d")
|| target.equalsIgnoreCase("all")
|| target.equalsIgnoreCase("sample")
|| target.equalsIgnoreCase("stutter")
|| target.equalsIgnoreCase("tracy")
|| target.equalsIgnoreCase("jfr"))) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
String mode = ctx.arg(1);
String targetArg = ctx.arg(2);
String detailArg = ctx.arg(3);
if (target.equalsIgnoreCase("jfr")) {
return executeJfr(mode, targetArg);
}
if (target.equalsIgnoreCase("stutter")) {
return executeStutter(mode, targetArg, detailArg);
}
if (target.equalsIgnoreCase("tracy")) {
boolean enable = mode == null || mode.equalsIgnoreCase("on");
if (mode != null && !mode.equalsIgnoreCase("on") && !mode.equalsIgnoreCase("off")) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
boolean active = TracyProfiler.setEnabled(enable);
if (!enable) {
CommandOutput.send("Profiler tracy: off");
} else if (active) {
CommandOutput.send("Profiler tracy: on (streams to external Tracy viewer, not latest.log)");
} else {
CommandOutput.send("Profiler tracy: unavailable");
}
return true;
}
if (mode == null) {
mode = "chat";
}
ProfilerSettings.OutputMode modeOutput = ProfilerSettings.parseOutput(mode);
ProfilerSettings.SampleTarget modeTarget = ProfilerSettings.parseTarget(mode);
ProfilerSettings.SampleTarget targetTarget = ProfilerSettings.parseTarget(targetArg);
ProfilerSettings.OutputMode targetOutput = ProfilerSettings.parseOutput(targetArg);
Boolean detailMode = parseDetailMode(detailArg);
boolean modeIsOutput = modeOutput != null;
boolean modeIsTarget = modeTarget != null;
if (!modeIsOutput && !modeIsTarget) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
String t = target.toLowerCase();
if (!t.equals("sample") && !modeIsOutput) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
if (t.equals("2d")) {
ProfilerSettings.setOutput2d(modeOutput);
} else if (t.equals("3d")) {
ProfilerSettings.setOutput3d(modeOutput);
} else if (t.equals("sample")) {
if (modeIsTarget) {
ProfilerSettings.setSampleTarget(modeTarget);
if (targetOutput != null) {
ProfilerSettings.setSampleOutput(targetOutput);
modeOutput = targetOutput;
} else {
ProfilerSettings.setSampleOutput(ProfilerSettings.OutputMode.CHAT);
modeOutput = ProfilerSettings.OutputMode.CHAT;
}
} else {
ProfilerSettings.setSampleOutput(modeOutput);
}
if (targetTarget != null) {
ProfilerSettings.setSampleTarget(targetTarget);
}
if (detailMode != null) {
ProfilerSettings.setSampleDetailedStacks(detailMode);
}
} else {
ProfilerSettings.setOutput2d(modeOutput);
ProfilerSettings.setOutput3d(modeOutput);
}
if (t.equals("sample")) {
CommandOutput.send("Profiler sample output: " + modeOutput.name().toLowerCase()
+ " (target " + ProfilerSettings.formatTarget(ProfilerSettings.getSampleTarget())
+ ", stacks " + (ProfilerSettings.isSampleDetailedStacks() ? "on" : "off") + ")");
} else {
CommandOutput.send("Profiler " + t + " output: " + modeOutput.name().toLowerCase());
}
return true;
}
@Override
public List<String> suggest(CommandContext ctx, int argIndex, String token) {
if (argIndex == 1) {
return matchToken(token, List.of("2d", "3d", "all", "sample", "stutter", "tracy", "jfr"));
}
if (argIndex == 2) {
String t = ctx.arg(0);
if (t != null && (t.equalsIgnoreCase("sample") || t.equalsIgnoreCase("stutter"))) {
return matchToken(token, List.of("off", "log", "chat", "2d", "3d", "all"));
}
if (t != null && t.equalsIgnoreCase("tracy")) {
return matchToken(token, List.of("on", "off"));
}
if (t != null && t.equalsIgnoreCase("jfr")) {
return matchToken(token, List.of("start", "stop", "dump", "status"));
}
return matchToken(token, List.of("off", "log", "chat"));
}
if (argIndex == 3) {
String t = ctx.arg(0);
if (t != null && t.equalsIgnoreCase("sample")) {
return matchToken(token, List.of("2d", "3d", "all"));
}
if (t != null && t.equalsIgnoreCase("jfr")) {
String action = ctx.arg(1);
if (action == null || action.equalsIgnoreCase("start")) {
return matchToken(token, List.of("gc", "alloc", "full"));
}
}
}
if (argIndex == 4) {
String t = ctx.arg(0);
if (t != null && t.equalsIgnoreCase("sample")) {
return matchToken(token, List.of("stacks", "nostacks"));
}
}
return List.of();
}
private boolean executeStutter(String mode, String thresholdArg, String sampleArg) {
if (mode == null || mode.equalsIgnoreCase("status")) {
CommandOutput.send(FrameStutterProfiler.statusLine());
return true;
}
ProfilerSettings.OutputMode output = ProfilerSettings.parseOutput(mode);
if (output == null) {
CommandOutput.send("Profiler stutter usage: @profiler stutter [off|log|chat|status] [thresholdMs] [sampleMs]");
return true;
}
double thresholdMs = parseDouble(thresholdArg, 35.0);
double sampleMs = parseDouble(sampleArg, 2.0);
FrameStutterProfiler.configure(output, thresholdMs, sampleMs);
CommandOutput.send(FrameStutterProfiler.statusLine());
return true;
}
private boolean executeJfr(String action, String presetArg) {
if (action == null || action.equalsIgnoreCase("status")) {
CommandOutput.send(JfrProfiler.statusLine());
return true;
}
if (action.equalsIgnoreCase("start")) {
JfrProfiler.Preset preset = JfrProfiler.Preset.parse(presetArg);
if (preset == null) {
CommandOutput.send("Profiler JFR usage: @profiler jfr start [gc|alloc|full]");
return true;
}
JfrProfiler.StartResult result = JfrProfiler.start(preset);
if (result.started()) {
CommandOutput.send("Profiler JFR: started " + preset.getId() + " -> " + absolute(result.path()));
return true;
}
if (result.alreadyRunning()) {
CommandOutput.send("Profiler JFR: already running ("
+ result.preset().getId() + ", file " + absolute(result.path()) + ")");
return true;
}
CommandOutput.send("Profiler JFR: unavailable"
+ (result.error() == null ? "" : " (" + result.error() + ")"));
return true;
}
if (action.equalsIgnoreCase("dump")) {
JfrProfiler.DumpResult result = JfrProfiler.dumpSnapshot();
if (result.dumped()) {
CommandOutput.send("Profiler JFR: snapshot -> " + absolute(result.path()));
return true;
}
if (result.notRunning()) {
CommandOutput.send("Profiler JFR: not running");
return true;
}
CommandOutput.send("Profiler JFR: snapshot failed"
+ (result.error() == null ? "" : " (" + result.error() + ")"));
return true;
}
if (action.equalsIgnoreCase("stop")) {
JfrProfiler.StopResult result = JfrProfiler.stop();
if (result.stopped()) {
long seconds = result.startedAt() == null
? 0L
: Math.max(0L, Duration.between(result.startedAt(), Instant.now()).toSeconds());
CommandOutput.send("Profiler JFR: saved " + result.preset().getId()
+ " (" + formatDuration(seconds) + ") -> " + absolute(result.path()));
return true;
}
if (result.notRunning()) {
CommandOutput.send("Profiler JFR: not running");
return true;
}
CommandOutput.send("Profiler JFR: stop failed"
+ (result.error() == null ? "" : " (" + result.error() + ")"));
return true;
}
CommandOutput.send("Profiler JFR usage: @profiler jfr [start|stop|dump|status] [gc|alloc|full]");
return true;
}
private Boolean parseDetailMode(String raw) {
if (raw == null) return null;
return switch (raw.toLowerCase()) {
case "stacks", "stack", "detail", "detailed" -> Boolean.TRUE;
case "nostacks", "nostack", "basic", "light" -> Boolean.FALSE;
default -> null;
};
}
private double parseDouble(String raw, double fallback) {
if (raw == null || raw.isBlank()) return fallback;
try {
double value = Double.parseDouble(raw.trim());
return Double.isFinite(value) ? value : fallback;
} catch (NumberFormatException ignored) {
return fallback;
}
}
private List<String> matchToken(String token, List<String> options) {
String lower = token == null ? "" : token.toLowerCase();
List<String> out = new java.util.ArrayList<>();
for (String opt : options) {
if (lower.isEmpty() || opt.startsWith(lower)) {
out.add(opt);
}
}
return out;
}
private String absolute(Path path) {
return path == null ? "<unknown>" : path.toAbsolutePath().toString();
}
private String formatDuration(long totalSeconds) {
long minutes = totalSeconds / 60L;
long seconds = totalSeconds % 60L;
if (minutes <= 0L) {
return seconds + "s";
}
return minutes + "m " + seconds + "s";
}
}

View file

@ -0,0 +1,25 @@
package dev.loki.lovisual.mixins;
import net.minecraft.util.profiling.InactiveProfiler;
import net.minecraft.util.profiling.Profiler;
import net.minecraft.util.profiling.ProfilerFiller;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import dev.loki.lovisual.render.engine.profiler.DevTracyProfiler;
@Mixin(Profiler.class)
public abstract class ProfilersMixin {
@Inject(method = "getDefaultFiller", at = @At("HEAD"), cancellable = true)
private static void lovisual$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
if (!DevTracyProfiler.isEnabled()) {
return;
}
if (DevTracyProfiler.shouldTraceCurrentThread()) {
return;
}
cir.setReturnValue(InactiveProfiler.INSTANCE);
}
}

View file

@ -0,0 +1,494 @@
package dev.loki.lovisual.render.engine.profiler;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;
import dev.loki.lovisual.util.screen.ClientScreen;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.openmbean.CompositeData;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.*;
public enum DevFrameStutterProfiler {
;
private static final long DEFAULT_THRESHOLD_NS = 35_000_000L;
private static final long DEFAULT_SAMPLE_INTERVAL_NS = 2_000_000L;
private static final long GC_CORRELATION_WINDOW_NS = 75_000_000L;
private static final int MAX_STACK_FRAMES = 6;
private static final int MAX_SAMPLES = 2048;
private static final int MAX_GC_EVENTS = 64;
private static final int TOP_STACKS = 8;
private static final Object LOCK = new Object();
private static final Sample[] SAMPLES = new Sample[MAX_SAMPLES];
private static final GcEvent[] GC_EVENTS = new GcEvent[MAX_GC_EVENTS];
private static volatile ProfilerSettings.OutputMode output = ProfilerSettings.OutputMode.OFF;
private static volatile long thresholdNs = DEFAULT_THRESHOLD_NS;
private static volatile long sampleIntervalNs = DEFAULT_SAMPLE_INTERVAL_NS;
private static volatile Thread renderThread;
private static volatile Thread samplerThread;
private static volatile boolean running;
private static volatile boolean gcListenerInstalled;
private static int sampleCursor;
private static int sampleCount;
private static int gcCursor;
private static int gcCount;
private static long lastPresentedNs;
private static long lastLoggedNs;
public static void configure(ProfilerSettings.OutputMode mode, double thresholdMs, double sampleMs) {
output = mode == null ? ProfilerSettings.OutputMode.OFF : mode;
thresholdNs = clampMs(thresholdMs, 1.0, 5000.0, DEFAULT_THRESHOLD_NS);
sampleIntervalNs = clampMs(sampleMs, 1.0, 100.0, DEFAULT_SAMPLE_INTERVAL_NS);
if (output == ProfilerSettings.OutputMode.OFF) {
stopSampler();
synchronized (LOCK) {
sampleCursor = 0;
sampleCount = 0;
lastPresentedNs = 0L;
lastLoggedNs = 0L;
}
return;
}
installGcListener();
ensureSampler();
}
public static String statusLine() {
if (output == ProfilerSettings.OutputMode.OFF) {
return "Profiler stutter: off";
}
return String.format(Locale.ROOT,
"Profiler stutter: %s (threshold %.1f ms, sample %.1f ms)",
output.name().toLowerCase(Locale.ROOT),
thresholdNs / 1_000_000.0,
sampleIntervalNs / 1_000_000.0);
}
public static boolean isEnabled() {
return output != ProfilerSettings.OutputMode.OFF;
}
public static void onFramePresented(RhiStatsSnapshot rhi,
UniformAllocatorStatsSnapshot uniforms,
RenderResourceStatsSnapshot resources) {
try {
if (!isEnabled()) return;
renderThread = Thread.currentThread();
ensureSampler();
long now = System.nanoTime();
long previous;
synchronized (LOCK) {
previous = lastPresentedNs;
lastPresentedNs = now;
}
if (previous == 0L) return;
long elapsedNs = now - previous;
if (elapsedNs < thresholdNs) return;
if (now - lastLoggedNs < thresholdNs) return;
lastLoggedNs = now;
List<String> lines = buildReport(previous, now, elapsedNs, rhi, uniforms, resources);
emit(lines);
} catch (Throwable t) {
ProfilerLog.warn("[FrameStutter] disabled after profiler failure: %s",
t.getClass().getSimpleName() + ": " + t.getMessage());
configure(ProfilerSettings.OutputMode.OFF, 0.0, 0.0);
}
}
private static List<String> buildReport(long frameStartNs,
long frameEndNs,
long elapsedNs,
RhiStatsSnapshot rhi,
UniformAllocatorStatsSnapshot uniforms,
RenderResourceStatsSnapshot resources) {
List<Sample> samples = samplesInWindow(frameStartNs, frameEndNs);
List<GcEvent> gcEvents = gcNearWindow(frameStartNs, frameEndNs);
Minecraft mc = Minecraft.getInstance();
String screen = mc == null || ClientScreen.current() == null ? "none" : ClientScreen.current().getClass().getSimpleName();
String world = mc == null || mc.level == null ? "none" : mc.level.dimension().identifier().toString();
List<String> lines = new ArrayList<>();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] frame %.2f ms over %.2f ms, samples %d, screen=%s, world=%s",
elapsedNs / 1_000_000.0,
thresholdNs / 1_000_000.0,
samples.size(),
screen,
world));
if (rhi != null) {
long uploaded = rhi.uploadedVertexBytes() + rhi.uploadedIndexBytes();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] rhi draw=%d fs=%d meshUpload=%d/%s copies=%d/%d ringWrap=%d stall=%d fallback=%d backlog=%d",
rhi.drawCalls(),
rhi.fullscreenPasses(),
rhi.meshUploads(),
formatBytes(uploaded),
rhi.textureFastCopies(),
rhi.textureShaderCopies(),
rhi.ringWraps(),
rhi.ringStalls(),
rhi.immediateFallbackUploads(),
rhi.dynamicArenaBacklogEvents()));
}
if (uniforms != null || resources != null) {
long uniformWrites = uniforms == null ? 0L : uniforms.writes();
long uniformBytes = uniforms == null ? 0L : uniforms.uploadedBytes();
int retireBacklog = resources == null ? 0 : resources.retirementBacklog();
int leaks = resources == null ? 0 : resources.leakedResources();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] uniforms writes=%d/%s resourceBacklog=%d leaks=%d",
uniformWrites,
formatBytes(uniformBytes),
retireBacklog,
leaks));
}
if (gcEvents.isEmpty()) {
lines.add("[FrameStutter] gc nearby: none");
} else {
for (GcEvent gc : gcEvents) {
double relativeEndMs = (gc.endNs - frameStartNs) / 1_000_000.0;
lines.add(String.format(Locale.ROOT,
"[FrameStutter] gc nearby: %s %s %.2f ms at %+,.2f ms, freed %s",
gc.name,
gc.cause,
(double) gc.durationMs,
relativeEndMs,
formatBytes(gc.freedBytes)));
}
}
appendSampleSummary(lines, samples);
return lines;
}
private static void appendSampleSummary(List<String> lines, List<Sample> samples) {
if (samples.isEmpty()) {
lines.add("[FrameStutter] sample top: none");
return;
}
Map<String, Integer> counts = new HashMap<>();
int glWait = 0;
int glUpload = 0;
int glDraw = 0;
int glState = 0;
for (Sample sample : samples) {
counts.merge(sample.stack, 1, Integer::sum);
if (sample.stack.startsWith("GL WAIT:")) {
glWait++;
} else if (sample.stack.startsWith("GL UPLOAD:")) {
glUpload++;
} else if (sample.stack.startsWith("GL DRAW:")) {
glDraw++;
} else if (sample.stack.startsWith("GL STATE:")) {
glState++;
}
}
lines.add(String.format(Locale.ROOT,
"[FrameStutter] gl samples wait/upload/draw/state=%d/%d/%d/%d",
glWait,
glUpload,
glDraw,
glState));
List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
lines.add("[FrameStutter] sample top:");
int top = Math.min(TOP_STACKS, entries.size());
for (int i = 0; i < top; i++) {
Map.Entry<String, Integer> entry = entries.get(i);
double pct = entry.getValue() * 100.0 / samples.size();
lines.add(String.format(Locale.ROOT,
"[FrameStutter] %d) %s (%d, %.1f%%)",
i + 1,
entry.getKey(),
entry.getValue(),
pct));
}
}
private static List<Sample> samplesInWindow(long startNs, long endNs) {
List<Sample> out = new ArrayList<>();
synchronized (LOCK) {
for (int i = 0; i < sampleCount; i++) {
Sample sample = SAMPLES[i];
if (sample != null && sample.timeNs >= startNs && sample.timeNs <= endNs) {
out.add(sample);
}
}
}
out.sort((a, b) -> Long.compare(a.timeNs, b.timeNs));
return out;
}
private static List<GcEvent> gcNearWindow(long startNs, long endNs) {
long from = startNs - GC_CORRELATION_WINDOW_NS;
long to = endNs + GC_CORRELATION_WINDOW_NS;
List<GcEvent> out = new ArrayList<>();
synchronized (LOCK) {
for (int i = 0; i < gcCount; i++) {
GcEvent event = GC_EVENTS[i];
if (event != null && event.endNs >= from && event.endNs <= to) {
out.add(event);
}
}
}
out.sort((a, b) -> Long.compare(a.endNs, b.endNs));
return out;
}
private static void ensureSampler() {
if (running || output == ProfilerSettings.OutputMode.OFF) return;
running = true;
samplerThread = new Thread(DevFrameStutterProfiler::sampleLoop, "LoVisual-DevFrameStutterProfiler");
samplerThread.setDaemon(true);
samplerThread.start();
}
private static void stopSampler() {
running = false;
Thread thread = samplerThread;
samplerThread = null;
if (thread != null) {
thread.interrupt();
}
renderThread = null;
}
private static void sampleLoop() {
long lastSampleNs = 0L;
while (running) {
if (output == ProfilerSettings.OutputMode.OFF) {
sleepMs(20L);
continue;
}
Thread target = renderThread;
if (target == null) {
sleepMs(10L);
continue;
}
long now = System.nanoTime();
if (now - lastSampleNs >= sampleIntervalNs) {
recordSample(now, target);
lastSampleNs = now;
}
sleepMs(1L);
}
}
private static void recordSample(long now, Thread target) {
StackTraceElement[] stack = target.getStackTrace();
if (stack == null || stack.length == 0) return;
String key = buildKey(stack);
if (key == null || key.isBlank()) return;
synchronized (LOCK) {
SAMPLES[sampleCursor] = new Sample(now, key);
sampleCursor = (sampleCursor + 1) % MAX_SAMPLES;
if (sampleCount < MAX_SAMPLES) {
sampleCount++;
}
}
}
private static String buildKey(StackTraceElement[] stack) {
StringBuilder sb = new StringBuilder(320);
String glCat = glCategory(stack);
if (glCat != null) {
sb.append("GL ").append(glCat).append(": ");
}
int added = 0;
for (StackTraceElement e : stack) {
if (added >= MAX_STACK_FRAMES) break;
if (isNoise(e)) continue;
if (added > 0) sb.append(" <= ");
sb.append(formatElement(e));
added++;
}
return added == 0 ? null : sb.toString();
}
private static String glCategory(StackTraceElement[] stack) {
for (StackTraceElement e : stack) {
String cls = e.getClassName();
String method = e.getMethodName();
if (!isGlFrame(cls)) continue;
if (method == null) continue;
if (method.equals("glfwSwapBuffers")
|| method.equals("glClientWaitSync")
|| method.equals("nglClientWaitSync")
|| method.equals("glWaitSync")
|| method.equals("glFinish")) {
return "WAIT";
}
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
return "DRAW";
}
if (method.contains("BufferSubData")
|| method.contains("BufferData")
|| method.contains("TexImage")
|| method.contains("TexSubImage")
|| method.contains("FlushMapped")
|| method.contains("MapBuffer")
|| method.contains("MapBufferRange")
|| method.contains("UnmapBuffer")) {
return "UPLOAD";
}
if (method.startsWith("glUseProgram")
|| method.startsWith("glBind")
|| method.startsWith("glTexParameter")
|| method.startsWith("glBlend")
|| method.startsWith("glEnable")
|| method.startsWith("glDisable")
|| method.startsWith("glDepth")
|| method.startsWith("glColorMask")
|| method.startsWith("glViewport")
|| method.startsWith("glScissor")
|| method.startsWith("glActiveTexture")
|| method.startsWith("glUniform")
|| method.startsWith("glVertexAttrib")) {
return "STATE";
}
}
return null;
}
private static boolean isGlFrame(String cls) {
return cls != null
&& (cls.startsWith("org.lwjgl.opengl.")
|| cls.startsWith("org.lwjgl.glfw.")
|| cls.startsWith("com.mojang.blaze3d.platform.")
|| cls.startsWith("com.mojang.blaze3d.systems."));
}
private static boolean isNoise(StackTraceElement e) {
String cls = e.getClassName();
return cls.startsWith("java.lang.Thread")
|| cls.startsWith("jdk.internal")
|| cls.startsWith("sun.")
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevFrameStutterProfiler");
}
private static String formatElement(StackTraceElement e) {
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + e.getLineNumber() + ")";
}
private static void installGcListener() {
if (gcListenerInstalled) return;
synchronized (LOCK) {
if (gcListenerInstalled) return;
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (bean instanceof NotificationEmitter emitter) {
emitter.addNotificationListener(DevFrameStutterProfiler::onGcNotification, null, null);
}
}
gcListenerInstalled = true;
}
}
private static void onGcNotification(Notification notification, Object handback) {
if (output == ProfilerSettings.OutputMode.OFF) return;
if (!GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) return;
Object data = notification.getUserData();
if (!(data instanceof CompositeData compositeData)) return;
try {
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(compositeData);
GcInfo gcInfo = info.getGcInfo();
long freed = usedBefore(gcInfo) - usedAfter(gcInfo);
GcEvent event = new GcEvent(
System.nanoTime(),
info.getGcName(),
info.getGcCause(),
Math.max(0L, gcInfo.getDuration()),
Math.max(0L, freed));
synchronized (LOCK) {
GC_EVENTS[gcCursor] = event;
gcCursor = (gcCursor + 1) % MAX_GC_EVENTS;
if (gcCount < MAX_GC_EVENTS) {
gcCount++;
}
}
} catch (Throwable ignored) {
}
}
private static long usedBefore(GcInfo info) {
return used(info == null ? null : info.getMemoryUsageBeforeGc());
}
private static long usedAfter(GcInfo info) {
return used(info == null ? null : info.getMemoryUsageAfterGc());
}
private static long used(Map<String, MemoryUsage> usage) {
if (usage == null || usage.isEmpty()) return 0L;
long total = 0L;
for (MemoryUsage value : usage.values()) {
if (value != null && value.getUsed() > 0L) {
total += value.getUsed();
}
}
return total;
}
private static void emit(List<String> lines) {
ProfilerSettings.OutputMode mode = output;
if (mode == ProfilerSettings.OutputMode.OFF || lines == null || lines.isEmpty()) return;
if (mode == ProfilerSettings.OutputMode.LOG) {
for (String line : lines) {
ProfilerLog.info("%s", line);
}
return;
}
if (mode == ProfilerSettings.OutputMode.CHAT) {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal(line));
}
}
}
private static long clampMs(double valueMs, double minMs, double maxMs, long fallbackNs) {
if (!Double.isFinite(valueMs) || valueMs <= 0.0) return fallbackNs;
double clamped = Math.max(minMs, Math.min(maxMs, valueMs));
return (long) (clamped * 1_000_000.0);
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
private static void sleepMs(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {
}
}
private record Sample(long timeNs, String stack) {
}
private record GcEvent(long endNs, String name, String cause, long durationMs, long freedBytes) {
}
}

View file

@ -0,0 +1,340 @@
package dev.loki.lovisual.render.engine.profiler;
import java.util.*;
public enum DevGlSyncTracker {
;
private static final int MAX_FENCES = 512;
private static final int TOP_PHASES = 4;
private static final int TOP_STACKS = 3;
private static final int MAX_STACK_FRAMES = 8;
private static final int MAX_SLOW_WAITS = 3;
private static final long SLOW_WAIT_THRESHOLD_NS = 1_000_000L;
private static final Object LOCK = new Object();
private static final LinkedHashMap<Long, FenceInfo> FENCE_INFOS = new LinkedHashMap<>();
private static final Map<String, Integer> WAIT_BY_FENCE_PHASE = new HashMap<>();
private static final Map<String, Integer> WAIT_BY_WAIT_PHASE = new HashMap<>();
private static final Map<String, Long> WAIT_TIME_BY_FENCE_PHASE = new HashMap<>();
private static final Map<String, Long> WAIT_TIME_BY_WAIT_PHASE = new HashMap<>();
private static final Map<String, StackAggregate> WAIT_BY_CREATE_STACK = new HashMap<>();
private static final List<SlowWait> SLOW_WAITS = new ArrayList<>();
private static final ThreadLocal<WaitState> WAIT_STATE =
ThreadLocal.withInitial(WaitState::new);
private static int waitTotal;
private static long waitTimeTotalNs;
private static int tracyWaitCallsFrame;
private static long tracyWaitTimeFrameNs;
public static void onFence(long sync) {
if (!shouldTrackWaits()) return;
if (sync == 0L) return;
String phase = DevProfilerPhase.current();
String createStack = shouldCaptureStacks() ? captureStackTrace() : null;
synchronized (LOCK) {
FENCE_INFOS.put(sync, new FenceInfo(phase, createStack));
trimFences();
}
}
public static void onWaitStart(long sync) {
if (!shouldTrackWaits()) return;
WaitState state = WAIT_STATE.get();
state.startNs = System.nanoTime();
state.waitPhase = DevProfilerPhase.current();
state.waitStack = null;
FenceInfo fenceInfo;
synchronized (LOCK) {
fenceInfo = FENCE_INFOS.remove(sync);
}
state.fencePhase = fenceInfo == null || fenceInfo.phase == null ? "unknown" : fenceInfo.phase;
state.createStack = fenceInfo == null ? null : fenceInfo.createStack;
state.active = true;
}
public static void onWaitEnd() {
WaitState state = WAIT_STATE.get();
if (state == null || !state.active) return;
state.active = false;
long durationNs = System.nanoTime() - state.startNs;
if (durationNs < 0L) durationNs = 0L;
if (!shouldTrackWaits()) return;
String fencePhase = state.fencePhase == null ? "unknown" : state.fencePhase;
String waitPhase = state.waitPhase == null ? "unknown" : state.waitPhase;
boolean captureStacks = shouldCaptureStacks();
String createStack = captureStacks ? normalizeStack(state.createStack) : null;
String waitStack = captureStacks && durationNs >= SLOW_WAIT_THRESHOLD_NS ? captureStackTrace() : null;
synchronized (LOCK) {
WAIT_BY_FENCE_PHASE.merge(fencePhase, 1, Integer::sum);
WAIT_BY_WAIT_PHASE.merge(waitPhase, 1, Integer::sum);
WAIT_TIME_BY_FENCE_PHASE.merge(fencePhase, durationNs, Long::sum);
WAIT_TIME_BY_WAIT_PHASE.merge(waitPhase, durationNs, Long::sum);
if (captureStacks) {
StackAggregate aggregate = WAIT_BY_CREATE_STACK.computeIfAbsent(
createStack,
key -> new StackAggregate(fencePhase, key)
);
aggregate.count += 1;
aggregate.timeNs += durationNs;
}
if (durationNs >= SLOW_WAIT_THRESHOLD_NS) {
recordSlowWait(new SlowWait(
durationNs,
fencePhase,
waitPhase,
createStack,
captureStacks ? normalizeStack(waitStack) : null
));
}
waitTotal += 1;
waitTimeTotalNs += durationNs;
tracyWaitCallsFrame += 1;
tracyWaitTimeFrameNs += durationNs;
}
}
public static void emitTracyFrame() {
if (!DevTracyProfiler.isEnabled()) return;
int calls;
long totalNs;
synchronized (LOCK) {
calls = tracyWaitCallsFrame;
totalNs = tracyWaitTimeFrameNs;
tracyWaitCallsFrame = 0;
tracyWaitTimeFrameNs = 0L;
}
DevTracyProfiler.plotGlWait(totalNs / 1_000_000.0, calls);
}
public static List<String> drainLines() {
if (!DevSamplingProfiler.isActive()) return List.of();
List<String> lines = new ArrayList<>();
Map<String, Integer> byFence;
Map<String, Integer> byWait;
Map<String, Long> timeByFence;
Map<String, Long> timeByWait;
List<StackAggregate> createStacks;
List<SlowWait> slowWaits;
int total;
long totalNs;
synchronized (LOCK) {
if (waitTotal == 0) return List.of();
total = waitTotal;
totalNs = waitTimeTotalNs;
byFence = new HashMap<>(WAIT_BY_FENCE_PHASE);
byWait = new HashMap<>(WAIT_BY_WAIT_PHASE);
timeByFence = new HashMap<>(WAIT_TIME_BY_FENCE_PHASE);
timeByWait = new HashMap<>(WAIT_TIME_BY_WAIT_PHASE);
createStacks = new ArrayList<>(WAIT_BY_CREATE_STACK.values());
slowWaits = new ArrayList<>(SLOW_WAITS);
WAIT_BY_FENCE_PHASE.clear();
WAIT_BY_WAIT_PHASE.clear();
WAIT_TIME_BY_FENCE_PHASE.clear();
WAIT_TIME_BY_WAIT_PHASE.clear();
WAIT_BY_CREATE_STACK.clear();
SLOW_WAITS.clear();
waitTotal = 0;
waitTimeTotalNs = 0L;
}
lines.add(String.format("gl wait calls: %d", total));
lines.add("gl wait phase (fence): " + formatTop(byFence, total));
lines.add("gl wait phase (wait): " + formatTop(byWait, total));
if (totalNs > 0L) {
lines.add(String.format("gl wait time total: %s", formatDuration(totalNs)));
lines.add("gl wait time (fence): " + formatTopTime(timeByFence, totalNs));
lines.add("gl wait time (wait): " + formatTopTime(timeByWait, totalNs));
}
String createStackSummary = formatTopCreateStacks(createStacks, totalNs);
if (createStackSummary != null) {
lines.add("gl wait source (create): " + createStackSummary);
}
if (!slowWaits.isEmpty()) {
lines.add("gl wait slow traces:");
for (int i = 0; i < slowWaits.size(); i++) {
SlowWait slow = slowWaits.get(i);
lines.add(String.format(
" %d) %s fence=%s wait=%s",
i + 1,
formatDuration(slow.durationNs),
slow.fencePhase,
slow.waitPhase
));
if (slow.createStack != null) {
lines.add(" create: " + slow.createStack);
}
if (slow.waitStack != null) {
lines.add(" wait: " + slow.waitStack);
}
}
}
return lines;
}
private static String formatTop(Map<String, Integer> src, int total) {
if (src.isEmpty()) return "n/a";
List<Map.Entry<String, Integer>> list = new ArrayList<>(src.entrySet());
list.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
int top = Math.min(TOP_PHASES, list.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
Map.Entry<String, Integer> e = list.get(i);
double pct = total == 0 ? 0.0 : (e.getValue() * 100.0) / total;
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey()).append('=').append(e.getValue())
.append(String.format(" (%.1f%%)", pct));
}
return sb.toString();
}
private static String formatTopTime(Map<String, Long> src, long totalNs) {
if (src.isEmpty()) return "n/a";
List<Map.Entry<String, Long>> list = new ArrayList<>(src.entrySet());
list.sort((a, b) -> Long.compare(b.getValue(), a.getValue()));
int top = Math.min(TOP_PHASES, list.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
Map.Entry<String, Long> e = list.get(i);
double pct = totalNs == 0L ? 0.0 : (e.getValue() * 100.0) / totalNs;
if (sb.length() > 0) sb.append(", ");
sb.append(e.getKey()).append('=').append(formatDuration(e.getValue()))
.append(String.format(" (%.1f%%)", pct));
}
return sb.toString();
}
private static String formatDuration(long ns) {
double ms = ns / 1_000_000.0;
return String.format("%.2fms", ms);
}
private static void trimFences() {
if (FENCE_INFOS.size() <= MAX_FENCES) return;
int toRemove = FENCE_INFOS.size() - MAX_FENCES;
var it = FENCE_INFOS.keySet().iterator();
while (toRemove > 0 && it.hasNext()) {
it.next();
it.remove();
toRemove--;
}
}
private static String formatTopCreateStacks(List<StackAggregate> stacks, long totalNs) {
if (stacks == null || stacks.isEmpty()) return null;
stacks.sort((a, b) -> Long.compare(b.timeNs, a.timeNs));
int top = Math.min(TOP_STACKS, stacks.size());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < top; i++) {
StackAggregate aggregate = stacks.get(i);
double pct = totalNs == 0L ? 0.0 : (aggregate.timeNs * 100.0) / totalNs;
if (sb.length() > 0) sb.append(" | ");
sb.append(aggregate.fencePhase)
.append('=')
.append(formatDuration(aggregate.timeNs))
.append(" x")
.append(aggregate.count)
.append(String.format(" (%.1f%%)", pct))
.append(" :: ")
.append(aggregate.createStack);
}
return sb.toString();
}
private static void recordSlowWait(SlowWait slowWait) {
SLOW_WAITS.add(slowWait);
SLOW_WAITS.sort((a, b) -> Long.compare(b.durationNs, a.durationNs));
while (SLOW_WAITS.size() > MAX_SLOW_WAITS) {
SLOW_WAITS.remove(SLOW_WAITS.size() - 1);
}
}
private static String captureStackTrace() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StringBuilder sb = new StringBuilder(256);
int added = 0;
for (StackTraceElement e : stack) {
if (added >= MAX_STACK_FRAMES) break;
if (isStackNoise(e)) continue;
if (added > 0) sb.append(" <= ");
sb.append(formatElement(e));
added++;
}
return added == 0 ? "unknown" : sb.toString();
}
private static String normalizeStack(String stack) {
return stack == null || stack.isBlank() ? "unknown" : stack;
}
private static boolean shouldCaptureStacks() {
return ProfilerSettings.isSampleDetailedStacks();
}
private static boolean shouldTrackWaits() {
return DevSamplingProfiler.isActive() || DevTracyProfiler.isEnabled();
}
private static boolean isStackNoise(StackTraceElement e) {
String cls = e.getClassName();
String method = e.getMethodName();
return cls.equals(Thread.class.getName())
|| cls.startsWith("java.lang.Thread")
|| cls.startsWith("jdk.internal")
|| cls.startsWith("sun.")
|| cls.startsWith("org.lwjgl.opengl.GL")
|| cls.startsWith("org.lwjgl.system.JNI")
|| cls.equals(DevGlSyncTracker.class.getName())
|| cls.equals("dev.loki.lovisual.mixins.GlStateManagerMixin")
|| (cls.equals("com.mojang.blaze3d.opengl.GlStateManager")
&& ("_glFenceSync".equals(method) || "_glClientWaitSync".equals(method)));
}
private static String formatElement(StackTraceElement e) {
String cls = e.getClassName();
int idx = cls.lastIndexOf('.');
String simple = idx >= 0 ? cls.substring(idx + 1) : cls;
return simple + "." + e.getMethodName() + "(" + e.getFileName() + ":" + e.getLineNumber() + ")";
}
public static void reset() {
synchronized (LOCK) {
FENCE_INFOS.clear();
WAIT_BY_FENCE_PHASE.clear();
WAIT_BY_WAIT_PHASE.clear();
WAIT_TIME_BY_FENCE_PHASE.clear();
WAIT_TIME_BY_WAIT_PHASE.clear();
WAIT_BY_CREATE_STACK.clear();
SLOW_WAITS.clear();
waitTotal = 0;
waitTimeTotalNs = 0L;
}
}
private record FenceInfo(String phase, String createStack) {
}
private static final class StackAggregate {
final String fencePhase;
final String createStack;
int count;
long timeNs;
StackAggregate(String fencePhase, String createStack) {
this.fencePhase = fencePhase;
this.createStack = createStack;
}
}
private record SlowWait(long durationNs, String fencePhase, String waitPhase, String createStack,
String waitStack) {
}
private static final class WaitState {
long startNs;
String fencePhase;
String waitPhase;
String createStack;
String waitStack;
boolean active;
}
}

View file

@ -0,0 +1,253 @@
package dev.loki.lovisual.render.engine.profiler;
import jdk.jfr.EventSettings;
import jdk.jfr.Recording;
import net.minecraft.client.Minecraft;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public enum DevJfrProfiler {
;
private static final DateTimeFormatter FILE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
private static Recording recording;
private static Preset activePreset;
private static Instant startedAt;
private static Path outputPath;
public static synchronized StartResult start(Preset preset) {
if (recording != null) {
return StartResult.alreadyRunning(activePreset, outputPath, startedAt);
}
try {
Path dir = ensureOutputDirectory();
Path file = dir.resolve(defaultFileName(preset, false));
Recording next = new Recording();
next.setName("LoVisual " + preset.getId());
next.setToDisk(true);
next.setDumpOnExit(false);
configure(next, preset);
next.start();
recording = next;
activePreset = preset;
startedAt = Instant.now();
outputPath = file;
ProfilerLog.info("JFR started (%s) -> %s", preset.getId(), file.toAbsolutePath());
return StartResult.started(preset, file, startedAt);
} catch (Throwable t) {
ProfilerLog.warn("JFR unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
return StartResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
public static synchronized DumpResult dumpSnapshot() {
if (recording == null) {
return DumpResult.notRunningResult();
}
try {
Path dir = ensureOutputDirectory();
Path snapshot = dir.resolve(defaultFileName(activePreset, true));
recording.dump(snapshot);
ProfilerLog.info("JFR snapshot dumped -> %s", snapshot.toAbsolutePath());
return DumpResult.dumped(snapshot);
} catch (Throwable t) {
ProfilerLog.warn("JFR snapshot failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
return DumpResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
public static synchronized StopResult stop() {
if (recording == null) {
return StopResult.notRunningResult();
}
Recording current = recording;
Preset preset = activePreset;
Instant started = startedAt;
Path destination = outputPath;
recording = null;
activePreset = null;
startedAt = null;
outputPath = null;
try {
current.stop();
Files.createDirectories(destination.getParent());
current.dump(destination);
current.close();
ProfilerLog.info("JFR stopped (%s) -> %s", preset.getId(), destination.toAbsolutePath());
return StopResult.stopped(preset, destination, started);
} catch (Throwable t) {
try {
current.close();
} catch (Throwable ignored) {
}
ProfilerLog.warn("JFR stop failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
return StopResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
public static synchronized String statusLine() {
if (recording == null) {
return "Profiler JFR: off";
}
long seconds = Math.max(0L, Duration.between(startedAt, Instant.now()).toSeconds());
return "Profiler JFR: on (" + activePreset.getId()
+ ", " + formatDuration(seconds)
+ ", file " + outputPath.toAbsolutePath() + ")";
}
private static void configure(Recording recording, Preset preset) {
enable(recording, "jdk.GarbageCollection", true, null, null);
enable(recording, "jdk.GCHeapSummary", false, null, null);
enable(recording, "jdk.MetaspaceSummary", false, null, null);
enable(recording, "jdk.CPULoad", false, Duration.ofSeconds(1), null);
enable(recording, "jdk.JavaThreadStatistics", false, Duration.ofSeconds(1), null);
if (preset.capturesAllocations()) {
enable(recording, "jdk.ObjectAllocationSample", true, null, null);
}
if (preset == Preset.FULL) {
enable(recording, "jdk.ExecutionSample", true, Duration.ofMillis(20), null);
enable(recording, "jdk.NativeMethodSample", true, Duration.ofMillis(20), null);
enable(recording, "jdk.ThreadPark", true, null, Duration.ofMillis(1));
enable(recording, "jdk.JavaMonitorEnter", true, null, Duration.ofMillis(1));
}
}
private static void enable(
Recording recording,
String eventName,
boolean stackTrace,
Duration period,
Duration threshold
) {
try {
EventSettings settings = recording.enable(eventName);
settings = stackTrace ? settings.withStackTrace() : settings.withoutStackTrace();
if (period != null) {
settings = settings.withPeriod(period);
}
if (threshold != null) {
settings = settings.withThreshold(threshold);
}
} catch (IllegalArgumentException ignored) {
// Some runtimes ship a slightly different event set.
}
}
private static Path ensureOutputDirectory() throws Exception {
Minecraft mc = Minecraft.getInstance();
Path dir;
if (mc != null && mc.gameDirectory != null) {
dir = mc.gameDirectory.toPath().resolve("profile").resolve("jfr");
} else {
dir = Path.of("profile", "jfr");
}
Files.createDirectories(dir);
return dir;
}
private static String defaultFileName(Preset preset, boolean snapshot) {
String timestamp = FILE_TIME.format(LocalDateTime.now(ZoneId.systemDefault()));
String suffix = snapshot ? "-snapshot" : "";
return "lovisual-" + preset.getId() + suffix + "-" + timestamp + ".jfr";
}
private static String formatDuration(long totalSeconds) {
long minutes = totalSeconds / 60L;
long seconds = totalSeconds % 60L;
if (minutes <= 0L) {
return seconds + "s";
}
return minutes + "m " + seconds + "s";
}
public enum Preset {
GC("gc"),
ALLOC("alloc"),
FULL("full");
private final String id;
Preset(String id) {
this.id = id;
}
public static Preset parse(String raw) {
if (raw == null || raw.isBlank()) {
return FULL;
}
return switch (raw.toLowerCase()) {
case "gc" -> GC;
case "alloc", "allocation", "allocs" -> ALLOC;
case "full", "all", "profile" -> FULL;
default -> null;
};
}
public String id() {
return id;
}
public String getId() {
return id;
}
public boolean capturesAllocations() {
return this == ALLOC || this == FULL;
}
}
public record StartResult(boolean started, boolean alreadyRunning, Preset preset, Path path, Instant startedAt,
String error) {
private static StartResult started(Preset preset, Path path, Instant startedAt) {
return new StartResult(true, false, preset, path, startedAt, null);
}
private static StartResult alreadyRunning(Preset preset, Path path, Instant startedAt) {
return new StartResult(false, true, preset, path, startedAt, null);
}
private static StartResult failed(String error) {
return new StartResult(false, false, null, null, null, error);
}
}
public record DumpResult(boolean dumped, boolean notRunning, Path path, String error) {
private static DumpResult dumped(Path path) {
return new DumpResult(true, false, path, null);
}
private static DumpResult notRunningResult() {
return new DumpResult(false, true, null, null);
}
private static DumpResult failed(String error) {
return new DumpResult(false, false, null, error);
}
}
public record StopResult(boolean stopped, boolean notRunning, Preset preset, Path path, Instant startedAt,
String error) {
private static StopResult stopped(Preset preset, Path path, Instant startedAt) {
return new StopResult(true, false, preset, path, startedAt, null);
}
private static StopResult notRunningResult() {
return new StopResult(false, true, null, null, null, null);
}
private static StopResult failed(String error) {
return new StopResult(false, false, null, null, null, error);
}
}
}

View file

@ -0,0 +1,67 @@
package dev.loki.lovisual.render.engine.profiler;
import java.util.ArrayDeque;
public enum DevProfilerPhase {
;
private static final ThreadLocal<ArrayDeque<String>> STACK =
ThreadLocal.withInitial(ArrayDeque::new);
public static Scope scope(String label) {
if (label == null || label.isBlank()) return Scope.NOOP;
begin(label);
return new Scope(true);
}
public static void begin(String label) {
if (label == null || label.isBlank()) return;
if (!DevSamplingProfiler.isActive()) return;
STACK.get().push(label);
}
public static void end(String label) {
if (label == null || label.isBlank()) return;
ArrayDeque<String> stack = STACK.get();
if (stack == null || stack.isEmpty()) return;
String top = stack.peek();
if (label.equals(top)) {
pop();
}
}
public static String current() {
ArrayDeque<String> stack = STACK.get();
if (stack == null || stack.isEmpty()) return "unknown";
String v = stack.peek();
return v == null || v.isBlank() ? "unknown" : v;
}
public static void clearCurrent() {
ArrayDeque<String> stack = STACK.get();
if (stack != null) {
stack.clear();
}
}
private static void pop() {
ArrayDeque<String> stack = STACK.get();
if (stack == null || stack.isEmpty()) return;
stack.pop();
}
public static final class Scope implements AutoCloseable {
private static final Scope NOOP = new Scope(false);
private final boolean active;
private Scope(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active) return;
pop();
}
}
}

View file

@ -0,0 +1,457 @@
package dev.loki.lovisual.render.engine.profiler;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import java.util.*;
/**
* Low-overhead owner/effect profiler for the new RHI path.
*
* <p>The existing DevRenderProfiler2D/3D tree answers "which Java section is hot".
* This profiler answers the practical render question: which phase/widget/node/effect/pass
* consumed CPU time and caused RHI work (draws, uploads, fullscreen passes, copies, uniforms).</p>
*/
public enum DevRenderCostProfiler {
;
private static final int MAX_BUCKETS = 768;
private static final long NS_IN_MS = 1_000_000L;
private static final int DEFAULT_LOG_INTERVAL_FRAMES = 120;
private static final int DEFAULT_LOG_TOP = 20;
private static final double DEFAULT_LOG_MIN_MS = 0.02;
private static final String PROP_ENABLED = "lovisual.profiler.renderCost";
private static final String PROP_LOG = "lovisual.profiler.renderCost.log";
private static final String PROP_INTERVAL = "lovisual.profiler.renderCost.interval";
private static final String PROP_TOP = "lovisual.profiler.renderCost.top";
private static final String PROP_MIN_MS = "lovisual.profiler.renderCost.minMs";
private static final LinkedHashMap<String, Bucket> buckets = new LinkedHashMap<>();
private static final HashMap<String, String> labelCache = new HashMap<>(256);
private static final ThreadLocal<Deque<Scope>> scopeStack = ThreadLocal.withInitial(ArrayDeque::new);
private static long frameId = Long.MIN_VALUE;
private static long lastLoggedFrameId = Long.MIN_VALUE;
private static boolean active;
private static Snapshot snapshot = Snapshot.EMPTY;
public static void beginFrame(long newFrameId) {
if (frameId == newFrameId) return;
frameId = newFrameId;
active = isProfilerEnabled();
if (!active) {
snapshot = Snapshot.EMPTY;
return;
}
buckets.clear();
scopeStack.get().clear();
}
public static void endFrame() {
if (!active) return;
snapshot = Snapshot.from(frameId, buckets);
emitLogIfDue(snapshot);
active = false;
}
public static Snapshot snapshot() {
return snapshot;
}
public static boolean isEnabled() {
return active;
}
public static boolean isConfigured() {
return Boolean.getBoolean(PROP_ENABLED);
}
public static Scope scope(String domain, String name) {
if (!active) return Scope.NOOP;
String d = clean(domain, "unknown");
String n = clean(name, "unnamed");
String owner = clean(DevProfilerPhase.current(), "unknown");
Bucket bucket = bucket(d, owner, n);
if (bucket == null) return Scope.NOOP;
Scope scope = new Scope(bucket, System.nanoTime(), Counters.capture(), true);
scopeStack.get().push(scope);
return scope;
}
public static Scope phase(String label) {
return scope("phase", label);
}
public static Scope uiNode(Object label) {
return scope("ui.node", String.valueOf(label));
}
public static Scope uiRuntime(String label) {
return scope("ui.runtime", label);
}
public static Scope uiEffect(String label) {
return scope("ui.effect", label);
}
public static Scope postPass(String label) {
return scope("post.pass", label);
}
public static Scope rhiDraw(String label) {
return scope("rhi.draw", label);
}
public static Scope itemRender(String label) {
return scope("item.render", label);
}
public static Scope worldEffect(String label) {
return scope("world.effect", label);
}
public static List<String> debugLines(String title, String domainPrefix, int limit, double minMs) {
Snapshot snap = snapshot;
if (snap == null || snap.entries.isEmpty()) return List.of();
String prefix = domainPrefix == null ? "" : domainPrefix;
List<Entry> filtered = new ArrayList<>();
for (Entry entry : snap.entries) {
if (prefix.isEmpty() || entry.domain.startsWith(prefix)) {
filtered.add(entry);
}
}
if (filtered.isEmpty()) return List.of();
filtered.sort(Comparator
.comparingLong((Entry e) -> e.totalNs).reversed()
.thenComparingLong((Entry e) -> e.uploadedBytes).reversed()
.thenComparingLong((Entry e) -> e.drawCalls).reversed());
List<String> lines = new ArrayList<>();
lines.add(title + ":");
int count = 0;
for (Entry e : filtered) {
double ms = e.totalNs / (double) NS_IN_MS;
if (ms < minMs) continue;
lines.add(String.format(Locale.ROOT,
" %d) [%s] %s:%s %.2f ms max %.2f calls %d | draw %d upload %d/%s fs %d copy %d/%d uni %d/%s",
count + 1,
shorten(e.owner, 42),
e.domain,
shorten(e.name, 56),
ms,
e.maxNs / (double) NS_IN_MS,
e.calls,
e.drawCalls,
e.meshUploads,
formatBytes(e.uploadedBytes),
e.fullscreenPasses,
e.fastCopies,
e.shaderCopies,
e.uniformWrites,
formatBytes(e.uniformBytes)));
count++;
if (count >= limit) break;
}
if (count == 0) return List.of();
return lines;
}
private static boolean isProfilerEnabled() {
return Boolean.getBoolean(PROP_ENABLED);
}
private static boolean shouldLogToLatest() {
if (!Boolean.getBoolean(PROP_ENABLED)) return false;
return Boolean.parseBoolean(System.getProperty(PROP_LOG, "true"));
}
private static void emitLogIfDue(Snapshot snap) {
if (!shouldLogToLatest()) return;
if (snap == null || snap.entries.isEmpty()) return;
int interval = intProperty(PROP_INTERVAL, DEFAULT_LOG_INTERVAL_FRAMES, 1, 60_000);
if (lastLoggedFrameId != Long.MIN_VALUE && snap.frameId - lastLoggedFrameId < interval) return;
lastLoggedFrameId = snap.frameId;
int top = intProperty(PROP_TOP, DEFAULT_LOG_TOP, 1, 200);
double minMs = doubleProperty(PROP_MIN_MS, DEFAULT_LOG_MIN_MS, 0.0, 1_000.0);
ProfilerLog.info("[RenderCost] frame=%d buckets=%d interval=%d top=%d minMs=%.3f", snap.frameId, snap.entries.size(), interval, top, minMs);
emitDomainToLog("phases", "phase", top, minMs);
emitDomainToLog("ui runtime", "ui.runtime", top, minMs);
emitDomainToLog("ui nodes", "ui.node", top, minMs);
emitDomainToLog("ui effects", "ui.effect", top, minMs);
emitDomainToLog("item render", "item.render", top, minMs);
emitDomainToLog("world effects", "world.effect", top, minMs);
emitDomainToLog("post passes", "post.pass", top, minMs);
emitDomainToLog("rhi draws", "rhi.draw", top, minMs);
}
private static void emitDomainToLog(String title, String prefix, int top, double minMs) {
List<String> lines = debugLines("[RenderCost] " + title, prefix, top, minMs);
for (String line : lines) {
ProfilerLog.info("%s", line);
}
}
private static int intProperty(String key, int fallback, int min, int max) {
String raw = System.getProperty(key);
if (raw == null || raw.isBlank()) return fallback;
try {
int value = Integer.parseInt(raw.trim());
return Math.max(min, Math.min(max, value));
} catch (NumberFormatException ignored) {
return fallback;
}
}
private static double doubleProperty(String key, double fallback, double min, double max) {
String raw = System.getProperty(key);
if (raw == null || raw.isBlank()) return fallback;
try {
double value = Double.parseDouble(raw.trim());
if (!Double.isFinite(value)) return fallback;
return Math.max(min, Math.min(max, value));
} catch (NumberFormatException ignored) {
return fallback;
}
}
private static Bucket bucket(String domain, String owner, String name) {
String key = domain + '\u001F' + owner + '\u001F' + name;
Bucket existing = buckets.get(key);
if (existing != null) return existing;
if (buckets.size() >= MAX_BUCKETS) {
key = "overflow\u001F" + owner + "\u001Fother";
existing = buckets.get(key);
if (existing != null) return existing;
if (buckets.size() >= MAX_BUCKETS + 1) return null;
Bucket overflow = new Bucket("overflow", owner, "other");
buckets.put(key, overflow);
return overflow;
}
Bucket created = new Bucket(domain, owner, name);
buckets.put(key, created);
return created;
}
private static String clean(String raw, String fallback) {
if (raw == null || raw.isBlank()) return fallback;
String s = raw.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').trim();
return s.isEmpty() ? fallback : s;
}
private static String shorten(String s, int max) {
if (s == null) return "";
if (s.length() <= max) return s;
if (max <= 3) return s.substring(0, max);
return s.substring(0, max - 3) + "...";
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
public static final class Scope implements AutoCloseable {
private static final Scope NOOP = new Scope(null, 0L, Counters.ZERO, false);
private final Bucket bucket;
private final long startNs;
private final Counters begin;
private final boolean enabled;
private boolean closed;
private long childNs;
private Counters childCounters = Counters.ZERO;
private Scope(Bucket bucket, long startNs, Counters begin, boolean enabled) {
this.bucket = bucket;
this.startNs = startNs;
this.begin = begin;
this.enabled = enabled;
}
@Override
public void close() {
if (!enabled || closed || bucket == null) return;
closed = true;
long elapsed = Math.max(0L, System.nanoTime() - startNs);
Counters rawDelta = begin.deltaTo(Counters.capture());
Deque<Scope> stack = scopeStack.get();
if (!stack.isEmpty() && stack.peek() == this) {
stack.pop();
} else {
stack.remove(this);
}
if (!stack.isEmpty()) {
Scope parent = stack.peek();
parent.childNs += elapsed;
parent.childCounters = parent.childCounters.plus(rawDelta);
}
long bucketNs = elapsed;
Counters bucketCounters = rawDelta;
if ("ui.node".equals(bucket.domain)) {
bucketNs = Math.max(0L, elapsed - childNs);
bucketCounters = rawDelta.minus(childCounters);
}
bucket.add(bucketNs, bucketCounters);
}
}
private static final class Bucket {
final String domain;
final String owner;
final String name;
long calls;
long totalNs;
long maxNs;
long drawCalls;
long meshUploads;
long fullscreenPasses;
long fastCopies;
long shaderCopies;
long uploadedBytes;
long uniformWrites;
long uniformBytes;
private Bucket(String domain, String owner, String name) {
this.domain = domain;
this.owner = owner;
this.name = name;
}
void add(long ns, Counters d) {
calls++;
totalNs += ns;
maxNs = Math.max(maxNs, ns);
if (d == null) return;
drawCalls += d.drawCalls;
meshUploads += d.meshUploads;
fullscreenPasses += d.fullscreenPasses;
fastCopies += d.fastCopies;
shaderCopies += d.shaderCopies;
uploadedBytes += d.uploadedBytes;
uniformWrites += d.uniformWrites;
uniformBytes += d.uniformBytes;
}
}
private record Counters(long drawCalls,
long meshUploads,
long fullscreenPasses,
long fastCopies,
long shaderCopies,
long uploadedBytes,
long uniformWrites,
long uniformBytes) {
static final Counters ZERO = new Counters(0, 0, 0, 0, 0, 0, 0, 0);
static Counters capture() {
try {
long uploaded = LoVisualRenderSystem.rhi().stats().uploadedVertexBytes()
+ LoVisualRenderSystem.rhi().stats().uploadedIndexBytes();
return new Counters(
LoVisualRenderSystem.rhi().stats().drawCalls(),
LoVisualRenderSystem.rhi().stats().meshUploads(),
LoVisualRenderSystem.rhi().stats().fullscreenPasses(),
LoVisualRenderSystem.rhi().stats().textureFastCopies(),
LoVisualRenderSystem.rhi().stats().textureShaderCopies(),
uploaded,
LoVisualRenderSystem.uniforms().stats().writes(),
LoVisualRenderSystem.uniforms().stats().uploadedBytes()
);
} catch (Throwable ignored) {
return ZERO;
}
}
Counters deltaTo(Counters end) {
if (end == null) return ZERO;
return new Counters(
Math.max(0L, end.drawCalls - drawCalls),
Math.max(0L, end.meshUploads - meshUploads),
Math.max(0L, end.fullscreenPasses - fullscreenPasses),
Math.max(0L, end.fastCopies - fastCopies),
Math.max(0L, end.shaderCopies - shaderCopies),
Math.max(0L, end.uploadedBytes - uploadedBytes),
Math.max(0L, end.uniformWrites - uniformWrites),
Math.max(0L, end.uniformBytes - uniformBytes)
);
}
Counters plus(Counters other) {
if (other == null) return this;
return new Counters(
drawCalls + other.drawCalls,
meshUploads + other.meshUploads,
fullscreenPasses + other.fullscreenPasses,
fastCopies + other.fastCopies,
shaderCopies + other.shaderCopies,
uploadedBytes + other.uploadedBytes,
uniformWrites + other.uniformWrites,
uniformBytes + other.uniformBytes
);
}
Counters minus(Counters other) {
if (other == null) return this;
return new Counters(
Math.max(0L, drawCalls - other.drawCalls),
Math.max(0L, meshUploads - other.meshUploads),
Math.max(0L, fullscreenPasses - other.fullscreenPasses),
Math.max(0L, fastCopies - other.fastCopies),
Math.max(0L, shaderCopies - other.shaderCopies),
Math.max(0L, uploadedBytes - other.uploadedBytes),
Math.max(0L, uniformWrites - other.uniformWrites),
Math.max(0L, uniformBytes - other.uniformBytes)
);
}
}
public record Snapshot(long frameId, List<Entry> entries) {
static final Snapshot EMPTY = new Snapshot(Long.MIN_VALUE, List.of());
static Snapshot from(long frameId, Map<String, Bucket> buckets) {
if (buckets == null || buckets.isEmpty()) return EMPTY;
List<Entry> out = new ArrayList<>(buckets.size());
for (Bucket b : buckets.values()) {
out.add(new Entry(
b.domain,
b.owner,
b.name,
b.calls,
b.totalNs,
b.maxNs,
b.drawCalls,
b.meshUploads,
b.fullscreenPasses,
b.fastCopies,
b.shaderCopies,
b.uploadedBytes,
b.uniformWrites,
b.uniformBytes
));
}
return new Snapshot(frameId, List.copyOf(out));
}
}
public record Entry(String domain,
String owner,
String name,
long calls,
long totalNs,
long maxNs,
long drawCalls,
long meshUploads,
long fullscreenPasses,
long fastCopies,
long shaderCopies,
long uploadedBytes,
long uniformWrites,
long uniformBytes) {
}
}

View file

@ -0,0 +1,135 @@
package dev.loki.lovisual.render.engine.profiler;
import dev.loki.lovisual.render.engine.core.RenderPhase;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
/**
* Single profiler bridge for the RHI/FrameGraph lifecycle.
* Existing DevRenderProfiler2D/3D trees are preserved, but phase ownership moves here.
*/
public enum DevRenderFrameProfiler {
;
private static boolean worldFrameOpen;
private static boolean uiFrameOpen;
public static void beginFrame(long frameId) {
// The sampling profiler is still driven by 2D/3D beginFrame calls below.
DevRenderCostProfiler.beginFrame(frameId);
}
public static PhaseScope phase(RenderPhase phase, String label) {
RenderPhase actualPhase = phase == null ? RenderPhase.NONE : phase;
String actualLabel = label == null || label.isBlank() ? defaultLabel(actualPhase) : label;
DevProfilerPhase.Scope cpu = DevProfilerPhase.scope(actualLabel);
DevRenderCostProfiler.Scope cost = DevRenderCostProfiler.phase(actualLabel);
DevTracyGpuProfiler.Scope gpu = DevTracyGpuProfiler.beginZone(actualLabel);
AutoCloseable tree = beginTreeSection(actualPhase, actualLabel);
return new PhaseScope(cpu, cost, gpu, tree);
}
public static void endFrame(RhiStatsSnapshot rhi, UniformAllocatorStatsSnapshot uniforms) {
DevRenderCostProfiler.endFrame();
if (worldFrameOpen) {
DevRenderProfiler3D.endFrame();
worldFrameOpen = false;
}
if (uiFrameOpen) {
DevRenderProfiler2D.endFrame();
uiFrameOpen = false;
}
DevGlSyncTracker.emitTracyFrame();
DevTracyProfiler.markFrame();
}
private static AutoCloseable beginTreeSection(RenderPhase phase, String label) {
if (isWorld(phase)) {
if (!worldFrameOpen) {
DevRenderProfiler3D.beginFrame("world");
worldFrameOpen = true;
}
return DevRenderProfiler3D.section(stripDomain(label));
}
if (isUi(phase)) {
if (!uiFrameOpen) {
DevRenderProfiler2D.beginFrame("ui");
uiFrameOpen = true;
}
return DevRenderProfiler2D.section(stripDomain(label));
}
return () -> {
};
}
private static boolean isWorld(RenderPhase phase) {
return phase == RenderPhase.WORLD_BEFORE_ENTITIES
|| phase == RenderPhase.WORLD_AFTER_ENTITIES
|| phase == RenderPhase.WORLD_BEFORE_TRANSLUCENT
|| phase == RenderPhase.WORLD_AFTER_TRANSLUCENT
|| phase == RenderPhase.WORLD_POST_PRE_HAND
|| phase == RenderPhase.WORLD_POST_HAND;
}
private static boolean isUi(RenderPhase phase) {
return phase == RenderPhase.HUD_CAPTURE
|| phase == RenderPhase.HUD_MAIN
|| phase == RenderPhase.HUD_EFFECTS
|| phase == RenderPhase.SCREEN_TOP
|| phase == RenderPhase.SCREEN;
}
private static String defaultLabel(RenderPhase phase) {
return switch (phase) {
case WORLD_BEFORE_ENTITIES -> "3d:world_before_entities";
case WORLD_AFTER_ENTITIES -> "3d:world_after_entities";
case WORLD_BEFORE_TRANSLUCENT -> "3d:world_before_translucent";
case WORLD_AFTER_TRANSLUCENT -> "3d:world_after_translucent";
case WORLD_POST_PRE_HAND -> "3d:post_pre_hand";
case WORLD_POST_HAND -> "3d:post_hand";
case HUD_CAPTURE -> "2d:hud_capture";
case HUD_MAIN -> "2d:hud_main";
case HUD_EFFECTS -> "2d:hud_effects";
case SCREEN_TOP -> "2d:screen_top";
case SCREEN -> "2d:screen";
case LEGACY_SHADOW_TERRAIN -> "3d:shadow_terrain_legacy";
default -> "render:none";
};
}
private static String stripDomain(String label) {
int idx = label.indexOf(':');
if (idx >= 0 && idx + 1 < label.length()) {
return label.substring(idx + 1);
}
return label;
}
public static final class PhaseScope implements AutoCloseable {
private final DevProfilerPhase.Scope cpu;
private final DevRenderCostProfiler.Scope cost;
private final DevTracyGpuProfiler.Scope gpu;
private final AutoCloseable tree;
private boolean closed;
private PhaseScope(DevProfilerPhase.Scope cpu, DevRenderCostProfiler.Scope cost, DevTracyGpuProfiler.Scope gpu, AutoCloseable tree) {
this.cpu = cpu;
this.cost = cost;
this.gpu = gpu;
this.tree = tree;
}
@Override
public void close() {
if (closed) return;
closed = true;
try {
if (tree != null) tree.close();
} catch (Exception ignored) {
}
if (gpu != null) gpu.close();
if (cost != null) cost.close();
if (cpu != null) cpu.close();
}
}
}

View file

@ -0,0 +1,498 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.command.UiStatsSnapshot;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.ui.runtime.script.CachedUiScriptRuntime;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import dev.loki.lovisual.render.engine.text.TextCommandStatsSnapshot;
import dev.loki.lovisual.render.engine.text.TextRenderSystem;
import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
import java.util.*;
public enum DevRenderProfiler2D {
;
private static final long NS_IN_MS = 1_000_000L;
private static final int DEFAULT_TOP_LIMIT = 6;
private static final int DEFAULT_TREE_DEPTH = 32;
private static final double DEFAULT_MIN_MS = 0.0;
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
private static boolean active;
private static Node root;
private static Node snapshot;
private static long lastEmitNs;
public static boolean isEnabled() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
public static void beginFrame(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
if (!isEnabled()) return;
CachedUiScriptRuntime.resetFrameStats();
MeshBuilder.resetFrameStats();
active = true;
root = new Node(name, null);
stack.clear();
stack.push(root);
root.startNs = System.nanoTime();
}
public static boolean beginFrameIfNeeded(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
if (!isEnabled() || active) return false;
beginFrame(name);
return true;
}
public static void endFrame() {
if (!isEnabled() || !active) return;
long now = System.nanoTime();
while (stack.size() > 1) {
endSection();
}
Node r = stack.peek();
if (r != null) {
r.calls = Math.max(1, r.calls);
r.totalNs += now - r.startNs;
r.startNs = 0L;
snapshot = r;
DevTracyProfiler.plotUiFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
}
active = false;
emitIfDue(now);
}
public static Section section(String name) {
if (!isEnabled() || !active) return Section.NOOP;
beginSection(name);
return new Section(true);
}
private static void beginSection(String name) {
Node parent = stack.peek();
if (parent == null) return;
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
child.calls += 1;
child.startNs = System.nanoTime();
stack.push(child);
}
private static void endSection() {
Node node = stack.poll();
if (node == null) return;
long now = System.nanoTime();
node.totalNs += now - node.startNs;
node.startNs = 0L;
}
public static List<String> getDebugLines() {
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
}
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
if (!isEnabled()) return List.of();
Node snap = snapshot;
if (snap == null) return List.of();
List<String> lines = new ArrayList<>();
double totalMs = snap.totalNs / (double) NS_IN_MS;
lines.add(String.format("ui prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
appendRuntimeCounters(lines);
List<Node> flat = new ArrayList<>();
collectFlat(snap, flat);
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
int top = Math.min(topLimit, flat.size());
if (top > 0) {
lines.add("ui prof top:");
for (int i = 0; i < top; i++) {
Node n = flat.get(i);
double ms = n.totalNs / (double) NS_IN_MS;
if (ms < minMs) break;
double selfMs = selfNs(n) / (double) NS_IN_MS;
Node hot = hottestChild(n);
if (hot != null) {
double hotMs = hot.totalNs / (double) NS_IN_MS;
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
hot.name,
hotMs,
n.calls
));
} else {
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
n.calls
));
}
}
}
lines.add("ui prof tree:");
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
return lines;
}
private static void appendRuntimeCounters(List<String> lines) {
CachedUiScriptRuntime.FrameStatsSnapshot ui = CachedUiScriptRuntime.frameStatsSnapshot();
if (ui.bakeCalls() > 0 || ui.jsRenders() > 0 || ui.layoutPasses() > 0 || ui.propPatches() > 0 || ui.boundsPatches() > 0) {
lines.add(String.format(
"ui runtime: bake %d, js %d, layout %d, propPatch %d/%d, boundsPatch %d/%d, blocked %d, fail %d",
ui.bakeCalls(),
ui.jsRenders(),
ui.layoutPasses(),
ui.propPatchPasses(),
ui.propPatches(),
ui.boundsPatchPasses(),
ui.boundsPatches(),
ui.blockedCalls(),
ui.failedRenders()
));
}
TextCommandStatsSnapshot textStats = LoVisualRenderSystem.textStatsSnapshot();
if (textStats.recorded() > 0 || textStats.meshUploads() > 0 || textStats.glyphs() > 0) {
lines.add(String.format(
"text: rec/sub %d/%d, backend vanilla/bitmap/msdf/world %d/%d/%d/%d, effect/clip %d/%d, glyphs %d, meshUploads %d, router hit/miss/fallback %d/%d/%d, adjacent %d, uploaded v/i %s/%s",
textStats.recorded(),
textStats.submitted(),
textStats.vanilla(),
textStats.bitmap(),
textStats.msdf(),
textStats.world(),
textStats.effect(),
textStats.clipped(),
textStats.glyphs(),
textStats.meshUploads(),
textStats.routerCacheHits(),
textStats.routerCacheMisses(),
textStats.routerFallbackMisses(),
textStats.adjacentBatchedCommands(),
formatBytes(textStats.uploadedVertexBytes()),
formatBytes(textStats.uploadedIndexBytes())
));
}
var glyphStats = TextRenderSystem.glyphAtlases().stats();
if (glyphStats.pageCount() > 0 || glyphStats.dirtyUploads() > 0) {
lines.add(String.format(
"glyph atlas: pages %d, glyphs %d, dirtyUploads %d, uploaded %s",
glyphStats.pageCount(),
glyphStats.glyphCount(),
glyphStats.dirtyUploads(),
formatBytes(glyphStats.uploadedBytes())
));
}
UiStatsSnapshot uiDraw = Renderer2D.getUiStatsSnapshot();
if (uiDraw.recordedCommands() > 0 || uiDraw.compiledBatches() > 0) {
lines.add(String.format(
"ui commands: total %d, shape/path/tex/text/item/effect %d/%d/%d/%d/%d/%d, compiled %d, backend %d",
uiDraw.recordedCommands(),
uiDraw.shapeCommands(),
uiDraw.pathCommands(),
uiDraw.textureCommands(),
uiDraw.textCommands(),
uiDraw.itemCommands(),
uiDraw.effectCommands(),
uiDraw.compiledBatches(),
uiDraw.backendCommands()
));
}
Renderer2D.BatchStats batch = Renderer2D.getBatchStats();
int frameBatches = batch.getFrameBatches();
int frameDraws = batch.getFrameDraws();
int frameVertices = batch.getFrameVertices();
int frameIndices = batch.getFrameIndices();
Map<Renderer2D.FlushReason, Integer> flushReasons = batch.getFrameFlushReasons();
if (frameBatches > 0 || frameDraws > 0 || frameVertices > 0 || frameIndices > 0 || !flushReasons.isEmpty()) {
lines.add(String.format(
"ui batch: batches %d, draws %d, vertices %d, indices %d, pool %d, last %d/%d/%d, flush %s %s",
frameBatches,
frameDraws,
frameVertices,
frameIndices,
batch.getPoolTotal(),
batch.getLastOrder(),
batch.getLastDraws(),
batch.getLastVertices(),
batch.getLastFlushReason(),
formatFlushReasons(flushReasons)
));
}
if (!batch.getLastError().isEmpty()) {
lines.add("ui batch error: " + batch.getLastError());
}
MeshBuilder.FrameStatsSnapshot mesh = MeshBuilder.frameStatsSnapshot();
if (mesh.initialAllocations() > 0 || mesh.vertexReallocs() > 0 || mesh.indexReallocs() > 0) {
lines.add(String.format(
"ui mesh: alloc %d, realloc v/i %d/%d, bytes %s, max v/i %s/%s",
mesh.initialAllocations(),
mesh.vertexReallocs(),
mesh.indexReallocs(),
formatBytes(mesh.allocatedBytes()),
formatBytes(mesh.maxVertexBytes()),
formatBytes(mesh.maxIndexBytes())
));
}
appendRhiCounters(lines);
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
appendCostCounters(lines);
}
private static String formatFlushReasons(Map<Renderer2D.FlushReason, Integer> reasons) {
if (reasons == null || reasons.isEmpty()) return "{}";
List<String> parts = new ArrayList<>();
for (Map.Entry<Renderer2D.FlushReason, Integer> entry : reasons.entrySet()) {
if (entry.getValue() != null && entry.getValue() > 0) {
parts.add(entry.getKey().name().toLowerCase(Locale.ROOT) + "=" + entry.getValue());
}
}
return parts.isEmpty() ? "{}" : "{" + String.join(",", parts) + "}";
}
private static void appendCostCounters(List<String> lines) {
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
if (!phase.isEmpty()) lines.addAll(phase);
List<String> runtime = DevRenderCostProfiler.debugLines("ui cost runtime", "ui.runtime", 8, 0.02);
if (!runtime.isEmpty()) lines.addAll(runtime);
List<String> nodes = DevRenderCostProfiler.debugLines("ui cost nodes", "ui.node", 10, 0.02);
if (!nodes.isEmpty()) lines.addAll(nodes);
List<String> effects = DevRenderCostProfiler.debugLines("ui cost effects", "ui.effect", 8, 0.02);
if (!effects.isEmpty()) lines.addAll(effects);
List<String> items = DevRenderCostProfiler.debugLines("ui cost item render", "item.render", 8, 0.02);
if (!items.isEmpty()) lines.addAll(items);
List<String> rhi = DevRenderCostProfiler.debugLines("ui cost rhi draws", "rhi.draw", 8, 0.02);
if (!rhi.isEmpty()) lines.addAll(rhi);
}
private static void appendRhiCounters(List<String> lines) {
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
lines.add(String.format(
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
rhi.drawCalls(),
rhi.renderPasses(),
rhi.renderPassAttachmentSwitches(),
rhi.meshUploads(),
rhi.fullscreenPasses(),
rhi.textureFastCopies(),
rhi.textureShaderCopies(),
formatBytes(rhi.uploadedVertexBytes()),
formatBytes(rhi.uploadedIndexBytes())
));
}
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
lines.add(String.format(
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
rhi.ringWraps(),
rhi.ringStalls(),
rhi.immediateFallbackUploads(),
rhi.dynamicArenaReuses(),
rhi.dynamicArenaRetires()
));
}
if (rhi.legacyPathUses() > 0) {
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
}
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
lines.add(String.format(
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
uniforms.writes(),
formatBytes(uniforms.uploadedBytes()),
uniforms.activeStreams(),
uniforms.ringRotations(),
uniforms.ringGrows(),
uniforms.staleReadMisses()
));
}
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
lines.add(String.format(
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
resources.persistentFramebuffers(),
resources.temporaryFramebuffers(),
resources.framebufferCreates(),
resources.framebufferResizes(),
resources.framebufferBorrows(),
resources.framebufferReleases(),
resources.retirementBacklog(),
resources.leakedResources()
));
}
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
private static void collectFlat(Node node, List<Node> out) {
for (Node child : node.children.values()) {
out.add(child);
collectFlat(child, out);
}
}
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
if (node == null) return;
double ms = node.totalNs / (double) NS_IN_MS;
if (depth > 0 && ms < minMs) return;
double selfMs = selfNs(node) / (double) NS_IN_MS;
String line = depth == 0
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
out.add(line);
if (depth >= maxDepth) return;
List<Node> children = new ArrayList<>(node.children.values());
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
String childIndent = indent + "| ";
for (Node child : children) {
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
}
}
private static void emitIfDue(long nowNs) {
ProfilerSettings.OutputMode mode = getOutputMode();
if (mode == ProfilerSettings.OutputMode.OFF) return;
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
lastEmitNs = nowNs;
if (mode == ProfilerSettings.OutputMode.LOG) {
emitToLog();
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
emitToChat();
}
}
private static ProfilerSettings.OutputMode getOutputMode() {
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
return getOutputModeRaw();
}
private static ProfilerSettings.OutputMode getOutputModeRaw() {
return ProfilerSettings.getOutput2d();
}
private static void emitToLog() {
List<String> lines = getDebugLines();
if (lines.isEmpty()) return;
for (String line : lines) {
ProfilerLog.info("[UIProfiler] %s", line);
}
}
private static void emitToChat() {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
List<String> lines = getDebugLines(4, 2, 0.05);
if (lines.isEmpty()) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[UIProfiler] " + line));
}
}
private static long selfNs(Node node) {
if (node == null) return 0L;
long childrenNs = 0L;
for (Node child : node.children.values()) {
childrenNs += child.totalNs;
}
long self = node.totalNs - childrenNs;
return Math.max(0L, self);
}
private static Node hottestChild(Node node) {
if (node == null || node.children.isEmpty()) return null;
Node best = null;
long bestNs = 0L;
for (Node child : node.children.values()) {
if (best == null || child.totalNs > bestNs) {
best = child;
bestNs = child.totalNs;
}
}
return best;
}
private static String nodePath(Node node) {
if (node == null) return "";
List<String> parts = new ArrayList<>();
Node cur = node;
while (cur != null) {
parts.add(cur.name);
cur = cur.parent;
}
StringBuilder sb = new StringBuilder();
for (int i = parts.size() - 1; i >= 0; i--) {
if (sb.length() > 0) sb.append(" > ");
sb.append(parts.get(i));
}
return sb.toString();
}
public static final class Section implements AutoCloseable {
private static final Section NOOP = new Section(false);
private final boolean active;
private Section(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active) return;
endSection();
}
}
private static final class Node {
final String name;
final Node parent;
final Map<String, Node> children = new HashMap<>();
long totalNs;
long startNs;
int calls;
private Node(String name, Node parent) {
this.name = name;
this.parent = parent;
}
int countNodes() {
int count = 1;
for (Node child : children.values()) {
count += child.countNodes();
}
return count;
}
}
}

View file

@ -0,0 +1,420 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
import dev.loki.lovisual.render.engine.world.WorldRenderStatsSnapshot;
import dev.loki.lovisual.render.iris.IrisRuntimeSnapshot;
import dev.loki.lovisual.render.sodium.SodiumTerrainInteropStatsSnapshot;
import dev.loki.lovisual.render.sodium.SodiumVisibilityStatsSnapshot;
import java.util.*;
public enum DevRenderProfiler3D {
;
private static final long NS_IN_MS = 1_000_000L;
private static final int DEFAULT_TOP_LIMIT = 6;
private static final int DEFAULT_TREE_DEPTH = 32;
private static final double DEFAULT_MIN_MS = 0.0;
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
private static boolean active;
private static Node root;
private static Node snapshot;
private static long lastEmitNs;
public static boolean isEnabled() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
public static void beginFrame(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
if (!isEnabled()) return;
active = true;
root = new Node(name, null);
stack.clear();
stack.push(root);
root.startNs = System.nanoTime();
}
public static boolean beginFrameIfNeeded(String name) {
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
if (!isEnabled() || active) return false;
beginFrame(name);
return true;
}
public static void endFrame() {
if (!isEnabled() || !active) return;
long now = System.nanoTime();
while (stack.size() > 1) {
endSection();
}
Node r = stack.peek();
if (r != null) {
r.calls = Math.max(1, r.calls);
r.totalNs += now - r.startNs;
r.startNs = 0L;
snapshot = r;
DevTracyProfiler.plotWorldFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
}
active = false;
emitIfDue(now);
}
public static Section section(String name) {
if (!isEnabled() || !active) return Section.NOOP;
beginSection(name);
return new Section(true);
}
private static void beginSection(String name) {
Node parent = stack.peek();
if (parent == null) return;
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
child.calls += 1;
child.startNs = System.nanoTime();
stack.push(child);
}
private static void endSection() {
Node node = stack.poll();
if (node == null) return;
long now = System.nanoTime();
node.totalNs += now - node.startNs;
node.startNs = 0L;
}
public static List<String> getDebugLines() {
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
}
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
if (!isEnabled()) return List.of();
Node snap = snapshot;
if (snap == null) return List.of();
List<String> lines = new ArrayList<>();
double totalMs = snap.totalNs / (double) NS_IN_MS;
lines.add(String.format("world prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
appendRhiCounters(lines);
appendCostCounters(lines);
List<Node> flat = new ArrayList<>();
collectFlat(snap, flat);
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
int top = Math.min(topLimit, flat.size());
if (top > 0) {
lines.add("world prof top:");
for (int i = 0; i < top; i++) {
Node n = flat.get(i);
double ms = n.totalNs / (double) NS_IN_MS;
if (ms < minMs) break;
double selfMs = selfNs(n) / (double) NS_IN_MS;
Node hot = hottestChild(n);
if (hot != null) {
double hotMs = hot.totalNs / (double) NS_IN_MS;
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
hot.name,
hotMs,
n.calls
));
} else {
lines.add(String.format(
" %d) %s %.2f ms (self %.2f, %d)",
i + 1,
nodePath(n),
ms,
selfMs,
n.calls
));
}
}
}
lines.add("world prof tree:");
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
return lines;
}
private static void appendCostCounters(List<String> lines) {
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
if (!phase.isEmpty()) lines.addAll(phase);
List<String> post = DevRenderCostProfiler.debugLines("world cost post", "post.pass", 8, 0.02);
if (!post.isEmpty()) lines.addAll(post);
List<String> effects = DevRenderCostProfiler.debugLines("world cost effects", "world.effect", 8, 0.02);
if (!effects.isEmpty()) lines.addAll(effects);
List<String> rhi = DevRenderCostProfiler.debugLines("world cost rhi draws", "rhi.draw", 8, 0.02);
if (!rhi.isEmpty()) lines.addAll(rhi);
}
private static void appendRhiCounters(List<String> lines) {
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
lines.add(String.format(
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
rhi.drawCalls(),
rhi.renderPasses(),
rhi.renderPassAttachmentSwitches(),
rhi.meshUploads(),
rhi.fullscreenPasses(),
rhi.textureFastCopies(),
rhi.textureShaderCopies(),
formatBytes(rhi.uploadedVertexBytes()),
formatBytes(rhi.uploadedIndexBytes())
));
}
WorldRenderStatsSnapshot world = LoVisualRenderSystem.worldRenderStatsSnapshot();
if (world.recordedCommands() > 0 || world.submittedCommands() > 0 || world.skippedEmptyCommands() > 0) {
lines.add(String.format(
"world3d: commands rec/sub/skip %d/%d/%d, vertices/indices %d/%d, fog %d, depth pre/main/none %d/%d/%d",
world.recordedCommands(),
world.submittedCommands(),
world.skippedEmptyCommands(),
world.submittedVertices(),
world.submittedIndices(),
world.fogBindings(),
world.depthPrePassBindings(),
world.depthMainBindings(),
world.depthDisabledBindings()
));
}
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
lines.add(String.format(
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
rhi.ringWraps(),
rhi.ringStalls(),
rhi.immediateFallbackUploads(),
rhi.dynamicArenaReuses(),
rhi.dynamicArenaRetires()
));
}
if (rhi.legacyPathUses() > 0) {
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
}
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
lines.add(String.format(
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
uniforms.writes(),
formatBytes(uniforms.uploadedBytes()),
uniforms.activeStreams(),
uniforms.ringRotations(),
uniforms.ringGrows(),
uniforms.staleReadMisses()
));
}
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
lines.add(String.format(
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
resources.persistentFramebuffers(),
resources.temporaryFramebuffers(),
resources.framebufferCreates(),
resources.framebufferResizes(),
resources.framebufferBorrows(),
resources.framebufferReleases(),
resources.retirementBacklog(),
resources.leakedResources()
));
}
IrisRuntimeSnapshot iris = LoVisualRenderSystem.irisSnapshot();
if (iris.modLoaded() || iris.shaderpackInUse()) {
lines.add(iris.shortLine());
}
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
SodiumVisibilityStatsSnapshot sodiumVisibility = LoVisualRenderSystem.sodiumVisibilityStatsSnapshot();
if (sodiumVisibility.queries() > 0 || sodiumVisibility.errors() > 0) {
lines.add(String.format(
"sodium vis: queries %d, accepts/rejects %d/%d, bypass %d (unavail %d, optout %d), errors %d",
sodiumVisibility.queries(),
sodiumVisibility.accepts(),
sodiumVisibility.rejects(),
sodiumVisibility.bypasses(),
sodiumVisibility.unavailableBypasses(),
sodiumVisibility.optOutBypasses(),
sodiumVisibility.errors()
));
}
SodiumTerrainInteropStatsSnapshot sodiumTerrain = LoVisualRenderSystem.sodiumTerrainStatsSnapshot();
if (sodiumTerrain.terrainUpdatesScheduled() > 0
|| sodiumTerrain.rebuildsScheduled() > 0
|| sodiumTerrain.interopErrors() > 0) {
lines.add(String.format(
"sodium terrain: updates %d, rebuilds %d, errors %d",
sodiumTerrain.terrainUpdatesScheduled(),
sodiumTerrain.rebuildsScheduled(),
sodiumTerrain.interopErrors()
));
}
}
private static String formatBytes(long bytes) {
if (bytes < 1024L) return bytes + " B";
double kb = bytes / 1024.0;
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
}
private static void collectFlat(Node node, List<Node> out) {
for (Node child : node.children.values()) {
out.add(child);
collectFlat(child, out);
}
}
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
if (node == null) return;
double ms = node.totalNs / (double) NS_IN_MS;
if (depth > 0 && ms < minMs) return;
double selfMs = selfNs(node) / (double) NS_IN_MS;
String line = depth == 0
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
out.add(line);
if (depth >= maxDepth) return;
List<Node> children = new ArrayList<>(node.children.values());
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
String childIndent = indent + "| ";
for (Node child : children) {
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
}
}
private static void emitIfDue(long nowNs) {
ProfilerSettings.OutputMode mode = getOutputMode();
if (mode == ProfilerSettings.OutputMode.OFF) return;
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
lastEmitNs = nowNs;
if (mode == ProfilerSettings.OutputMode.LOG) {
emitToLog();
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
emitToChat();
}
}
private static ProfilerSettings.OutputMode getOutputMode() {
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
return getOutputModeRaw();
}
private static ProfilerSettings.OutputMode getOutputModeRaw() {
return ProfilerSettings.getOutput3d();
}
private static void emitToLog() {
List<String> lines = getDebugLines();
if (lines.isEmpty()) return;
for (String line : lines) {
ProfilerLog.info("[WorldProfiler] %s", line);
}
}
private static void emitToChat() {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
List<String> lines = getDebugLines(4, 2, 0.05);
if (lines.isEmpty()) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[WorldProfiler] " + line));
}
}
private static long selfNs(Node node) {
if (node == null) return 0L;
long childrenNs = 0L;
for (Node child : node.children.values()) {
childrenNs += child.totalNs;
}
long self = node.totalNs - childrenNs;
return Math.max(0L, self);
}
private static Node hottestChild(Node node) {
if (node == null || node.children.isEmpty()) return null;
Node best = null;
long bestNs = 0L;
for (Node child : node.children.values()) {
if (best == null || child.totalNs > bestNs) {
best = child;
bestNs = child.totalNs;
}
}
return best;
}
private static String nodePath(Node node) {
if (node == null) return "";
List<String> parts = new ArrayList<>();
Node cur = node;
while (cur != null) {
parts.add(cur.name);
cur = cur.parent;
}
StringBuilder sb = new StringBuilder();
for (int i = parts.size() - 1; i >= 0; i--) {
if (sb.length() > 0) sb.append(" > ");
sb.append(parts.get(i));
}
return sb.toString();
}
public static final class Section implements AutoCloseable {
private static final Section NOOP = new Section(false);
private final boolean active;
private Section(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active) return;
endSection();
}
}
private static final class Node {
final String name;
final Node parent;
final Map<String, Node> children = new HashMap<>();
long totalNs;
long startNs;
int calls;
private Node(String name, Node parent) {
this.name = name;
this.parent = parent;
}
int countNodes() {
int count = 1;
for (Node child : children.values()) {
count += child.countNodes();
}
return count;
}
}
}

View file

@ -0,0 +1,442 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public enum DevSamplingProfiler {
;
private static final long SAMPLE_INTERVAL_NS = 10_000_000L; // 10 ms
private static final long EMIT_INTERVAL_NS = 1_000_000_000L; // 1 s
private static final int TOP_LIMIT = 8;
private static final int TOP_LIMIT_NON_GL = 4;
private static final int TOP_LIMIT_GL_WAIT = 3;
private static final int MAX_STACK_FRAMES = 4;
private static final int MAX_ENTRIES = 256;
private static final Object LOCK = new Object();
private static final Map<String, Integer> COUNTS = new HashMap<>();
private static int idleSamples;
private static volatile Thread targetThread;
private static volatile Thread samplerThread;
private static volatile boolean running;
private static volatile long lastEmitNs;
private static volatile List<String> pendingChatLines;
private static volatile Target lastSource = Target.WORLD;
public static void onClientFrame(Target source) {
if (!isEnabled()) {
DevProfilerPhase.clearCurrent();
stopIfRunning();
return;
}
lastSource = source;
flushPendingChat();
if (!matchesTarget(source)) return;
targetThread = Thread.currentThread();
ensureRunning();
}
private static boolean isEnabled() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
public static boolean isActive() {
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
}
private static void ensureRunning() {
if (running) return;
running = true;
samplerThread = new Thread(DevSamplingProfiler::runLoop, "LoVisual-DevSamplingProfiler");
samplerThread.setDaemon(true);
samplerThread.start();
}
private static void stopIfRunning() {
if (!running) return;
running = false;
Thread t = samplerThread;
samplerThread = null;
if (t != null) t.interrupt();
synchronized (LOCK) {
COUNTS.clear();
idleSamples = 0;
}
DevGlSyncTracker.reset();
pendingChatLines = null;
}
private static void runLoop() {
long lastSampleNs = 0L;
while (running) {
if (!isEnabled()) {
running = false;
synchronized (LOCK) {
COUNTS.clear();
idleSamples = 0;
}
DevGlSyncTracker.reset();
pendingChatLines = null;
break;
}
Thread t = targetThread;
if (t == null) {
sleepMs(10);
continue;
}
long now = System.nanoTime();
if (now - lastSampleNs >= SAMPLE_INTERVAL_NS) {
if (matchesTarget(lastSource)) {
sample(t);
}
lastSampleNs = now;
}
if (now - lastEmitNs >= EMIT_INTERVAL_NS) {
emit(now);
}
sleepMs(2);
}
}
private static void sample(Thread t) {
StackTraceElement[] stack = t.getStackTrace();
if (stack == null || stack.length == 0) return;
if (isIdleStack(stack)) {
synchronized (LOCK) {
idleSamples += 1;
}
return;
}
String key = buildKey(stack);
if (key == null || key.isEmpty()) return;
synchronized (LOCK) {
COUNTS.merge(key, 1, Integer::sum);
if (COUNTS.size() > MAX_ENTRIES) {
trimToLimit();
}
}
}
private static void emit(long now) {
ProfilerSettings.OutputMode mode = getOutputModeRaw();
if (mode == ProfilerSettings.OutputMode.OFF) return;
List<String> lines = buildOutputLines();
if (lines.isEmpty()) return;
lastEmitNs = now;
if (mode == ProfilerSettings.OutputMode.LOG) {
for (String line : lines) {
ProfilerLog.info("[SampleProfiler] %s", line);
}
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
pendingChatLines = lines;
}
synchronized (LOCK) {
COUNTS.clear();
idleSamples = 0;
}
}
private static List<String> buildOutputLines() {
List<Map.Entry<String, Integer>> entries;
int total;
int idle;
synchronized (LOCK) {
if (COUNTS.isEmpty() && idleSamples == 0) return List.of();
entries = new ArrayList<>(COUNTS.entrySet());
int sum = 0;
for (Integer count : COUNTS.values()) {
if (count != null) {
sum += count;
}
}
total = sum;
idle = idleSamples;
}
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
List<String> lines = new ArrayList<>();
int all = total + idle;
double idlePct = all == 0 ? 0.0 : (idle * 100.0) / all;
lines.add(String.format("sample prof: %d samples, idle %d (%.1f%%), entries %d", all, idle, idlePct, entries.size()));
int glWait = 0;
int glUpload = 0;
int glDraw = 0;
int glState = 0;
int glWaitClient = 0;
int glWaitSwap = 0;
int glWaitFinish = 0;
int glWaitSync = 0;
int glWaitOther = 0;
List<Map.Entry<String, Integer>> nonGl = new ArrayList<>();
List<Map.Entry<String, Integer>> glWaitList = new ArrayList<>();
for (Map.Entry<String, Integer> e : entries) {
String k = e.getKey();
int c = e.getValue();
if (k.startsWith("GL WAIT:")) {
glWait += c;
glWaitList.add(e);
if (containsAny(k, "glClientWaitSync", "nglClientWaitSync")) {
glWaitClient += c;
} else if (containsAny(k, "glfwSwapBuffers")) {
glWaitSwap += c;
} else if (containsAny(k, "glFinish", "nglFinish")) {
glWaitFinish += c;
} else if (containsAny(k, "glWaitSync", "nglWaitSync")) {
glWaitSync += c;
} else {
glWaitOther += c;
}
} else if (k.startsWith("GL UPLOAD:")) {
glUpload += c;
} else if (k.startsWith("GL DRAW:")) {
glDraw += c;
} else if (k.startsWith("GL STATE:")) {
glState += c;
} else {
nonGl.add(e);
}
}
int glTotal = glWait + glUpload + glDraw + glState;
if (glTotal > 0) {
double waitPct = all == 0 ? 0.0 : (glWait * 100.0) / all;
double uploadPct = all == 0 ? 0.0 : (glUpload * 100.0) / all;
double drawPct = all == 0 ? 0.0 : (glDraw * 100.0) / all;
double statePct = all == 0 ? 0.0 : (glState * 100.0) / all;
lines.add(String.format(
"gl samples: wait %d (%.1f%%), upload %d (%.1f%%), draw %d (%.1f%%), state %d (%.1f%%)",
glWait, waitPct, glUpload, uploadPct, glDraw, drawPct, glState, statePct
));
if (glWait > 0) {
lines.add(String.format(
"gl wait breakdown: client %d, swap %d, finish %d, waitsync %d, other %d",
glWaitClient, glWaitSwap, glWaitFinish, glWaitSync, glWaitOther
));
}
}
List<String> waitPhaseLines = DevGlSyncTracker.drainLines();
if (!waitPhaseLines.isEmpty()) {
lines.addAll(waitPhaseLines);
}
lines.add("sample prof top:");
int top = Math.min(TOP_LIMIT, entries.size());
for (int i = 0; i < top; i++) {
Map.Entry<String, Integer> e = entries.get(i);
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
}
if (!nonGl.isEmpty()) {
int topNon = Math.min(TOP_LIMIT_NON_GL, nonGl.size());
lines.add("sample prof top non-gl:");
for (int i = 0; i < topNon; i++) {
Map.Entry<String, Integer> e = nonGl.get(i);
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
}
}
if (!glWaitList.isEmpty()) {
int topWait = Math.min(TOP_LIMIT_GL_WAIT, glWaitList.size());
lines.add("sample prof top gl wait:");
for (int i = 0; i < topWait; i++) {
Map.Entry<String, Integer> e = glWaitList.get(i);
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
}
}
return lines;
}
private static void flushPendingChat() {
List<String> lines = pendingChatLines;
if (lines == null || lines.isEmpty()) return;
pendingChatLines = null;
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null) return;
for (String line : lines) {
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[SampleProfiler] " + line));
}
}
private static String buildKey(StackTraceElement[] stack) {
StringBuilder sb = new StringBuilder();
String glCat = glCategory(stack);
boolean hasPrefix = false;
if (glCat != null) {
sb.append("GL ").append(glCat).append(": ");
hasPrefix = true;
}
int added = 0;
for (StackTraceElement e : stack) {
if (added >= MAX_STACK_FRAMES) break;
if (isNoise(e)) continue;
if (added > 0 || (sb.length() > 0 && !hasPrefix)) sb.append(" <= ");
sb.append(formatElement(e));
added++;
}
return added == 0 ? null : sb.toString();
}
private static boolean isNoise(StackTraceElement e) {
String cls = e.getClassName();
return cls.startsWith("java.lang.Thread")
|| cls.startsWith("java.util.concurrent")
|| cls.startsWith("jdk.internal")
|| cls.startsWith("sun.")
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevSamplingProfiler");
}
private static String glCategory(StackTraceElement[] stack) {
for (StackTraceElement e : stack) {
String cls = e.getClassName();
String method = e.getMethodName();
if (!isGlFrame(cls)) continue;
String cat = glCategoryForMethod(method);
if (cat != null) return cat;
}
return null;
}
private static boolean isGlFrame(String cls) {
if (cls == null) return false;
return cls.startsWith("org.lwjgl.opengl.")
|| cls.startsWith("org.lwjgl.glfw.")
|| cls.startsWith("com.mojang.blaze3d.platform.")
|| cls.startsWith("com.mojang.blaze3d.systems.");
}
private static String glCategoryForMethod(String method) {
if (method == null) return null;
if (method.equals("glfwSwapBuffers")
|| method.equals("glClientWaitSync")
|| method.equals("glWaitSync")
|| method.equals("glFinish")) {
return "WAIT";
}
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
return "DRAW";
}
if (method.contains("BufferSubData")
|| method.contains("BufferData")
|| method.contains("TexImage")
|| method.contains("TexSubImage")
|| method.contains("CompressedTex")
|| method.contains("FlushMapped")
|| method.contains("MapBuffer")
|| method.contains("MapBufferRange")
|| method.contains("UnmapBuffer")) {
return "UPLOAD";
}
if (method.startsWith("glUseProgram")
|| method.startsWith("glBind")
|| method.startsWith("glTexParameter")
|| method.startsWith("glBlendFunc")
|| method.startsWith("glBlendEquation")
|| method.startsWith("glEnable")
|| method.startsWith("glDisable")
|| method.startsWith("glDepthFunc")
|| method.startsWith("glDepthMask")
|| method.startsWith("glColorMask")
|| method.startsWith("glCullFace")
|| method.startsWith("glFrontFace")
|| method.startsWith("glViewport")
|| method.startsWith("glScissor")
|| method.startsWith("glPolygonMode")
|| method.startsWith("glActiveTexture")
|| method.startsWith("glUniform")
|| method.startsWith("glVertexAttrib")) {
return "STATE";
}
return null;
}
private static boolean containsAny(String text, String... needles) {
if (text == null) return false;
for (String n : needles) {
if (n != null && !n.isEmpty() && text.contains(n)) return true;
}
return false;
}
private static boolean isIdleStack(StackTraceElement[] stack) {
boolean hasWait = false;
boolean hasLimit = false;
for (StackTraceElement e : stack) {
String cls = e.getClassName();
String method = e.getMethodName();
if ("org.lwjgl.glfw.GLFW".equals(cls) && "glfwWaitEventsTimeout".equals(method)) {
hasWait = true;
}
if ("com.mojang.blaze3d.systems.RenderSystem".equals(cls) && "limitDisplayFPS".equals(method)) {
hasLimit = true;
}
if (hasWait || hasLimit) {
return true;
}
}
return false;
}
private static String formatElement(StackTraceElement e) {
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
int line = e.getLineNumber();
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + line + ")";
}
private static boolean matchesTarget(Target source) {
if (source == null) return true;
Target target = getTargetRaw();
return target == Target.ALL || target == source;
}
private static Target getTargetRaw() {
ProfilerSettings.SampleTarget target = ProfilerSettings.getSampleTarget();
if (target == null) return Target.ALL;
return switch (target) {
case D2 -> Target.UI;
case D3 -> Target.WORLD;
case ALL -> Target.ALL;
};
}
private static void trimToLimit() {
if (COUNTS.size() <= MAX_ENTRIES) return;
List<Map.Entry<String, Integer>> entries = new ArrayList<>(COUNTS.entrySet());
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
for (int i = MAX_ENTRIES; i < entries.size(); i++) {
COUNTS.remove(entries.get(i).getKey());
}
}
private static ProfilerSettings.OutputMode getOutputModeRaw() {
return ProfilerSettings.getSampleOutput();
}
private static void sleepMs(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {
// ignore
}
}
public enum Target {
ALL,
UI,
WORLD
}
}

View file

@ -0,0 +1,150 @@
package dev.loki.lovisual.render.engine.profiler;
import com.mojang.jtracy.GpuApi;
import com.mojang.jtracy.GpuContext;
import com.mojang.jtracy.TracyClient;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL15C;
import org.lwjgl.opengl.GL33C;
import org.lwjgl.opengl.GLCapabilities;
import dev.loki.lovisual.render.engine.guard.LegacyRenderPath;
import dev.loki.lovisual.render.engine.guard.RenderBoundaryExempt;
import java.util.ArrayDeque;
@RenderBoundaryExempt(value = LegacyRenderPath.DIRECT_GL_OUTSIDE_BACKEND, reason = "Profiler-only timer query path; not part of renderer submission architecture")
public enum DevTracyGpuProfiler {
;
private static final Scope NOOP_SCOPE = new Scope(false);
private static final Object LOCK = new Object();
private static final ArrayDeque<QueryEvent> PENDING = new ArrayDeque<>();
private static final ArrayDeque<Integer> FREE_GL_QUERIES = new ArrayDeque<>();
private static volatile boolean initAttempted;
private static volatile boolean available;
private static volatile GpuContext context;
private static int nextQueryId = 1;
public static boolean isEnabled() {
return DevTracyProfiler.isEnabled() && isAvailable();
}
public static Scope beginZone(String name) {
if (!isEnabled() || name == null || name.isBlank()) {
return NOOP_SCOPE;
}
int beginId = allocateQueryId();
int beginQuery = allocateGlQuery();
context.beginZone(beginId, name, "", "", 0);
GL33C.glQueryCounter(beginQuery, GL33C.GL_TIMESTAMP);
enqueue(beginId, beginQuery);
return new Scope(true);
}
public static void onFrameEnd() {
if (!isEnabled()) {
return;
}
pump();
}
private static boolean isAvailable() {
ensureContext();
return available;
}
private static void ensureContext() {
if (initAttempted) {
return;
}
synchronized (LOCK) {
if (initAttempted) {
return;
}
initAttempted = true;
try {
GLCapabilities caps = GL.getCapabilities();
boolean timerQuery = caps.OpenGL33 || caps.GL_ARB_timer_query;
if (!timerQuery) {
available = false;
ProfilerLog.warn("Tracy GPU unavailable: timer queries are not supported by this OpenGL context");
return;
}
long gpuTimestamp = GL33C.glGetInteger64(GL33C.GL_TIMESTAMP);
context = TracyClient.createGpuContext(GpuApi.OPENGL, gpuTimestamp, 1.0f);
context.setName("main");
available = true;
ProfilerLog.info("Tracy GPU context initialized");
} catch (Throwable t) {
available = false;
ProfilerLog.warn("Tracy GPU unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
}
private static void pump() {
synchronized (LOCK) {
while (!PENDING.isEmpty()) {
QueryEvent event = PENDING.peekFirst();
if (GL15C.glGetQueryObjecti(event.glQuery, GL15C.GL_QUERY_RESULT_AVAILABLE) == 0) {
break;
}
long timestamp = GL33C.glGetQueryObjecti64(event.glQuery, GL15C.GL_QUERY_RESULT);
context.submitQueryTimestamp(event.queryId, timestamp);
PENDING.removeFirst();
FREE_GL_QUERIES.addLast(event.glQuery);
}
}
}
private static void enqueue(int queryId, int glQuery) {
synchronized (LOCK) {
PENDING.addLast(new QueryEvent(queryId, glQuery));
}
}
private static int allocateQueryId() {
synchronized (LOCK) {
int id = nextQueryId++;
if (id <= 0) {
nextQueryId = 1;
id = nextQueryId++;
}
return id;
}
}
private static int allocateGlQuery() {
synchronized (LOCK) {
Integer existing = FREE_GL_QUERIES.pollFirst();
if (existing != null) {
return existing;
}
}
return GL15C.glGenQueries();
}
private record QueryEvent(int queryId, int glQuery) {
}
public static final class Scope implements AutoCloseable {
private final boolean active;
private Scope(boolean active) {
this.active = active;
}
@Override
public void close() {
if (!active || !isEnabled()) {
return;
}
int endId = allocateQueryId();
int endQuery = allocateGlQuery();
context.endZone(endId);
GL33C.glQueryCounter(endQuery, GL33C.GL_TIMESTAMP);
enqueue(endId, endQuery);
}
}
}

View file

@ -0,0 +1,230 @@
package dev.loki.lovisual.render.engine.profiler;
import com.mojang.jtracy.Plot;
import com.mojang.jtracy.TracyClient;
import com.mojang.jtracy.Zone;
public enum DevTracyProfiler {
;
private static final Scope NOOP_SCOPE = new Scope(null);
private static final ThreadLocal<Boolean> THREAD_NAMED =
ThreadLocal.withInitial(() -> Boolean.FALSE);
private static volatile boolean loadAttempted;
private static volatile boolean available;
private static volatile Plot uiFrameMsPlot;
private static volatile Plot uiNodeCountPlot;
private static volatile Plot worldFrameMsPlot;
private static volatile Plot worldNodeCountPlot;
private static volatile Plot glWaitMsPlot;
private static volatile Plot glWaitCallsPlot;
private static volatile Plot uiBatchDrawsPlot;
private static volatile Plot uiBatchVerticesPlot;
public static boolean isEnabled() {
return ProfilerSettings.isTracyEnabled() && isAvailable();
}
public static boolean isAvailable() {
ensureLoaded();
return available;
}
public static synchronized boolean setEnabled(boolean enabled) {
ProfilerSettings.setTracyEnabled(enabled);
if (!enabled) {
ProfilerLog.info("Tracy disabled");
return false;
}
boolean active = isAvailable();
if (active) {
ProfilerLog.info("Tracy enabled; data is streamed to the external Tracy viewer, not latest.log");
TracyClient.message("LoVisual Tracy enabled");
}
return active;
}
public static Scope beginZone(String name) {
if (!isEnabled() || name == null || name.isBlank()) {
return NOOP_SCOPE;
}
ensureThreadNamed();
return new Scope(TracyClient.beginZone(name, false));
}
public static void markFrame() {
if (!isEnabled()) return;
ensureThreadNamed();
TracyClient.markFrame();
}
public static boolean shouldTraceCurrentThread() {
String threadName = Thread.currentThread().getName();
if (threadName == null || threadName.isBlank()) {
return false;
}
return "Render thread".equals(threadName)
|| threadName.startsWith("Render thread")
|| "main".equals(threadName)
|| "Main thread".equals(threadName);
}
public static void plotUiFrame(double ms, int nodes) {
if (!isEnabled()) return;
plotUiFrameMs().setValue(ms);
plotUiNodeCount().setValue(nodes);
}
public static void plotWorldFrame(double ms, int nodes) {
if (!isEnabled()) return;
plotWorldFrameMs().setValue(ms);
plotWorldNodeCount().setValue(nodes);
}
public static void plotGlWait(double ms, int calls) {
if (!isEnabled()) return;
plotGlWaitMs().setValue(ms);
plotGlWaitCalls().setValue(calls);
}
public static void plotUiBatch(int draws, int vertices) {
if (!isEnabled()) return;
plotUiBatchDraws().setValue(draws);
plotUiBatchVertices().setValue(vertices);
}
private static void ensureLoaded() {
if (loadAttempted) {
return;
}
synchronized (DevTracyProfiler.class) {
if (loadAttempted) {
return;
}
loadAttempted = true;
try {
TracyClient.load();
TracyClient.reportAppInfo("LoVisual render profiler");
available = TracyClient.isAvailable();
if (available) {
ProfilerLog.info("Tracy client loaded");
}
} catch (Throwable t) {
available = false;
ProfilerLog.warn("Tracy unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
}
}
}
private static void ensureThreadNamed() {
if (Boolean.TRUE.equals(THREAD_NAMED.get())) {
return;
}
TracyClient.setThreadName(Thread.currentThread().getName(), 0);
THREAD_NAMED.set(Boolean.TRUE);
}
private static Plot plotUiFrameMs() {
Plot plot = uiFrameMsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiFrameMsPlot == null) {
uiFrameMsPlot = TracyClient.createPlot("render.ui.ms");
}
return uiFrameMsPlot;
}
}
private static Plot plotUiNodeCount() {
Plot plot = uiNodeCountPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiNodeCountPlot == null) {
uiNodeCountPlot = TracyClient.createPlot("render.ui.nodes");
}
return uiNodeCountPlot;
}
}
private static Plot plotWorldFrameMs() {
Plot plot = worldFrameMsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (worldFrameMsPlot == null) {
worldFrameMsPlot = TracyClient.createPlot("render.world.ms");
}
return worldFrameMsPlot;
}
}
private static Plot plotWorldNodeCount() {
Plot plot = worldNodeCountPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (worldNodeCountPlot == null) {
worldNodeCountPlot = TracyClient.createPlot("render.world.nodes");
}
return worldNodeCountPlot;
}
}
private static Plot plotGlWaitMs() {
Plot plot = glWaitMsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (glWaitMsPlot == null) {
glWaitMsPlot = TracyClient.createPlot("render.gl_wait.ms");
}
return glWaitMsPlot;
}
}
private static Plot plotGlWaitCalls() {
Plot plot = glWaitCallsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (glWaitCallsPlot == null) {
glWaitCallsPlot = TracyClient.createPlot("render.gl_wait.calls");
}
return glWaitCallsPlot;
}
}
private static Plot plotUiBatchDraws() {
Plot plot = uiBatchDrawsPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiBatchDrawsPlot == null) {
uiBatchDrawsPlot = TracyClient.createPlot("render.ui_batch.draws");
}
return uiBatchDrawsPlot;
}
}
private static Plot plotUiBatchVertices() {
Plot plot = uiBatchVerticesPlot;
if (plot != null) return plot;
synchronized (DevTracyProfiler.class) {
if (uiBatchVerticesPlot == null) {
uiBatchVerticesPlot = TracyClient.createPlot("render.ui_batch.vertices");
}
return uiBatchVerticesPlot;
}
}
public static final class Scope implements AutoCloseable {
private final Zone zone;
private Scope(Zone zone) {
this.zone = zone;
}
@Override
public void close() {
if (zone != null) {
zone.close();
}
}
}
}

View file

@ -0,0 +1,16 @@
{
"required": true,
"plugin": "dev.loki.lovisual.mixins.LoVisualMixinPlugin",
"minVersion": "0.8",
"package": "dev.loki.lovisual.mixins",
"compatibilityLevel": "JAVA_21",
"client": [
"ProfilersMixin"
],
"injectors": {
"defaultRequire": 1
},
"overwrites": {
"requireAnnotations": true
}
}

View 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();
}
}

View 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");
}
}

View file

@ -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);
}
}
}

View file

@ -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();
}
}

View file

@ -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
);
}
}

View file

@ -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);
}
}

View file

@ -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
) {
}

View 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.addon.core;
public record AddonIssue(
String addonId,
Severity severity,
String message,
String detail
) {
public enum Severity {
INFO,
WARNING,
ERROR
}
}

View 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);
}
}

View file

@ -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));
}
}

View file

@ -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();
}
}
}

View file

@ -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) {
}
}

View file

@ -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;
}
}
}

View file

@ -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
) {
}

View file

@ -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<>();
}
}

View file

@ -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
}

View file

@ -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) {
}
}

View file

@ -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);
}

View file

@ -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();
}

View file

@ -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());
}
}

View file

@ -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
) {
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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) {
}
}

View file

@ -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);
}

View file

@ -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());
}
}

View file

@ -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
}

View file

@ -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);
}
}

View file

@ -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);
}

View file

@ -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();
}
}

View file

@ -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);
}

View file

@ -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();
}
}

View file

@ -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();
}
}

View file

@ -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());
}
}

View file

@ -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) {
}
}

View file

@ -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;
}
}

View file

@ -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) {
}
}

View file

@ -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());
}
}

View file

@ -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();
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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";
}
}

View file

@ -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();
}
}

View file

@ -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);
}
}
}

View file

@ -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;
}
}

View file

@ -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";
}
}

View file

@ -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";
}
}

View file

@ -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";
}
}

View file

@ -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";
}
}

View file

@ -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";
}
}

View file

@ -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";
}
}

View file

@ -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;
}
}

View file

@ -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();
}

View file

@ -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();
}

View file

@ -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
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View 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.config.i18n;
import java.util.List;
public interface ConfigValueAliasProvider {
List<String> getLegacyValueNames(String currentValueName);
}

View file

@ -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;
}

View 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;
}
}

View file

@ -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'});
}
}

View file

@ -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) {
}
}

View file

@ -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 {
}

View file

@ -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();
}

View file

@ -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) {
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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();
}
}

View file

@ -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;
}
}
}

View file

@ -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;
}
}

View file

@ -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) {
}
}

View file

@ -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";
}
}

View file

@ -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;
}
}

View file

@ -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) {
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}
}

View file

@ -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();
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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
}

Some files were not shown because too many files have changed in this diff Show more