This commit is contained in:
loki5512344 2026-07-30 11:12:56 +02:00
commit 8084ac50b3
1629 changed files with 238620 additions and 0 deletions

View file

@ -0,0 +1,301 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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.runtime.RuntimeGate;
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 RuntimeGate.canRunClientLogic();
}
@Override
public boolean execute(CommandContext ctx) {
if (!RuntimeGate.canRunClientLogic()) {
CommandOutput.send("Profiler: disabled in Panic mode.");
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 combatant$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
if (!DevTracyProfiler.isEnabled()) {
return;
}
if (DevTracyProfiler.shouldTraceCurrentThread()) {
return;
}
cir.setReturnValue(InactiveProfiler.INSTANCE);
}
}

View file

@ -0,0 +1,495 @@
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 dev.loki.lovisual.runtime.RuntimeGate;
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;
if (RuntimeGate.isPanic()) 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, "Combatant-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 || RuntimeGate.isPanic()) {
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("Combatant " + 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 "combatant-" + 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.CombatantRenderSystem;
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 = "combatant.profiler.renderCost";
private static final String PROP_LOG = "combatant.profiler.renderCost.log";
private static final String PROP_INTERVAL = "combatant.profiler.renderCost.interval";
private static final String PROP_TOP = "combatant.profiler.renderCost.top";
private static final String PROP_MIN_MS = "combatant.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 = CombatantRenderSystem.rhi().stats().uploadedVertexBytes()
+ CombatantRenderSystem.rhi().stats().uploadedIndexBytes();
return new Counters(
CombatantRenderSystem.rhi().stats().drawCalls(),
CombatantRenderSystem.rhi().stats().meshUploads(),
CombatantRenderSystem.rhi().stats().fullscreenPasses(),
CombatantRenderSystem.rhi().stats().textureFastCopies(),
CombatantRenderSystem.rhi().stats().textureShaderCopies(),
uploaded,
CombatantRenderSystem.uniforms().stats().writes(),
CombatantRenderSystem.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,499 @@
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.CombatantRenderSystem;
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 dev.loki.lovisual.runtime.RuntimeGate;
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 = CombatantRenderSystem.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 = CombatantRenderSystem.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 = CombatantRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = CombatantRenderSystem.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 = CombatantRenderSystem.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 (RuntimeGate.isPanic()) 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,421 @@
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.CombatantRenderSystem;
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 dev.loki.lovisual.runtime.RuntimeGate;
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 = CombatantRenderSystem.rhiStatsSnapshot();
UniformAllocatorStatsSnapshot uniforms = CombatantRenderSystem.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 = CombatantRenderSystem.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 = CombatantRenderSystem.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 = CombatantRenderSystem.irisSnapshot();
if (iris.modLoaded() || iris.shaderpackInUse()) {
lines.add(iris.shortLine());
}
var immediatelyFast = CombatantRenderSystem.immediatelyFastSnapshot();
if (immediatelyFast.modLoaded()) {
lines.add(immediatelyFast.shortLine());
}
SodiumVisibilityStatsSnapshot sodiumVisibility = CombatantRenderSystem.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 = CombatantRenderSystem.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 (RuntimeGate.isPanic()) 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,447 @@
package dev.loki.lovisual.render.engine.profiler;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.runtime.RuntimeGate;
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;
}
if (RuntimeGate.isPanic()) 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, "Combatant-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;
}
if (RuntimeGate.isPanic()) {
sleepMs(20);
continue;
}
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("Combatant 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("Combatant 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,525 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual;
import dev.loki.lovisual.events.impl.GameTickEvent;
import dev.loki.lovisual.runtime.*;
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.AddonManager;
import dev.loki.lovisual.addon.AddonRenderPipelineManager;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import dev.loki.lovisual.config.MainConfig;
import dev.loki.lovisual.events.Events;
import dev.loki.lovisual.features.account.AccountConfig;
import dev.loki.lovisual.features.command.CommandManager;
import dev.loki.lovisual.features.command.VanillaChatRuntimeCleanup;
import dev.loki.lovisual.features.gui.clickgui.ClickGuiRenderer;
import dev.loki.lovisual.features.gui.clickgui.settings.I18nPreflightContributors;
import dev.loki.lovisual.features.gui.hud.HudElements;
import dev.loki.lovisual.features.gui.hud.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.SwapTooltip;
import dev.loki.lovisual.features.module.HudPhase;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.mixininterface.IGuiGraphics;
import dev.loki.lovisual.render.effects.NetherPortalRiftPass;
import dev.loki.lovisual.render.effects.SleepOverlayPass;
import dev.loki.lovisual.render.engine.CombatantRenderEngineBootstrap;
import dev.loki.lovisual.render.engine.core.CombatantRenderSystem;
import dev.loki.lovisual.render.engine.core.RenderPhase;
import dev.loki.lovisual.render.engine.core.RenderPhaseScope;
import dev.loki.lovisual.render.engine.core.ViewportContext;
import dev.loki.lovisual.render.engine.postprocess.PostProcessManager;
import dev.loki.lovisual.render.engine.profiler.ProfilerPhase;
import dev.loki.lovisual.render.engine.profiler.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.TextRenderer;
import dev.loki.lovisual.render.helpers.SystemCursor;
import dev.loki.lovisual.render.helpers.TickDelta;
import dev.loki.lovisual.util.aiming.RotationManager;
import dev.loki.lovisual.util.block.bed.SelfBedTracker;
import dev.loki.lovisual.util.click.AttackPressing;
import dev.loki.lovisual.util.combat.AntiBotTracker;
import dev.loki.lovisual.util.combat.protocol.CombatProtocolHeuristics;
import dev.loki.lovisual.util.combat.SprintController;
import dev.loki.lovisual.util.combat.VulcanReachController;
import dev.loki.lovisual.util.entity.simulation.BoatSimulationCache;
import dev.loki.lovisual.util.media.MediaSessionService;
import dev.loki.lovisual.util.network.BacktrackController;
import dev.loki.lovisual.util.network.BlinkManager;
import dev.loki.lovisual.util.proxy.ProxyBackend;
import dev.loki.lovisual.util.network.FakeLagController;
import dev.loki.lovisual.util.player.inventory.InventorySwap;
import dev.loki.lovisual.util.player.simulation.PlayerSimulationCache;
import dev.loki.lovisual.util.pvp.PvpTargetTracker;
import dev.loki.lovisual.util.pvp.PvpTracker;
import dev.loki.lovisual.util.target.TargetManager;
import dev.loki.lovisual.util.time.TimerController;
public class LoVisual implements ClientModInitializer {
private static void registerRuntimeLifecycle() {
AddonManager.registerRuntimeLifecycle();
ClientRuntime.setCallbackCounter(Events.BUS::listenerCount);
ClientRuntime.setModuleCounter(ModuleManager::registeredCount);
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "modules";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
ModuleManager.shutdownForRuntime(context);
}
});
ClientRuntime.registerResumeParticipant(new RuntimeResumeParticipant() {
@Override
public String id() {
return "modules";
}
@Override
public void resume(String reason) {
ModuleManager.restoreAfterSoftPanic(reason);
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "clickgui";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
ClickGuiRenderer.shutdownForRuntime();
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "vanilla_chat";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
VanillaChatRuntimeCleanup.clearVanillaChatCache();
context.increment("vanillaChatCleared", 1);
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "hud";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
if (context.jarReplacement()) {
DraggableHudElementRegistry.clearRuntimeReferences();
StaticHudElementRegistry.clearRuntimeReferences();
}
}
});
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "render";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
if (context.jarReplacement()) {
PostProcessManager.shutdownForRuntime();
CombatantRenderSystem.shutdown();
}
}
});
}
private static void renderWorldPhase(WorldPhase phase,
com.mojang.blaze3d.vertex.PoseStack matrices,
net.minecraft.client.renderer.SubmitNodeCollector consumers) {
if (!RuntimeGate.canRunRender()) return;
ModuleManager.renderWorld(
phase,
matrices,
consumers,
TickDelta.tickProgress(false)
);
}
private static void refreshHudFrameTiming(DeltaTracker tickCounter) {
CombatantRenderSystem.updateFrameTiming(
TickDelta.tickProgress(tickCounter, false),
TickDelta.frameDeltaTicks(tickCounter),
TickDelta.fixedDeltaTicks(tickCounter)
);
}
private static void renderHudPhase(HudPhase phase, GuiGraphicsExtractor ctx, DeltaTracker tickCounter) {
if (!RuntimeGate.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 = CombatantRenderSystem.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 (!RuntimeGate.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 = CombatantRenderSystem.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.combatant$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() {
CombatantRenderEngineBootstrap.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(InventorySwap.INSTANCE);
Events.BUS.register(SprintController.INSTANCE);
Events.BUS.register(AntiBotTracker.INSTANCE);
Events.BUS.register(VulcanReachController.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 (!RuntimeGate.canRunClientLogic()) return;
Events.BUS.post(new GameTickEvent());
});
ClientTickEvents.END_CLIENT_TICK.register(client -> {
ModuleManager.tickRuntimeControllers();
if (!RuntimeGate.canRunClientLogic()) 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)
);
registerRuntimeLifecycle();
ClientRuntime.markActive("client initialized");
RenderPrewarmManager.prewarm("client initialized");
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import java.util.List;
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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
public record AddonIssue(
String addonId,
Severity severity,
String message,
String detail
) {
public enum Severity {
INFO,
WARNING,
ERROR
}
}

View file

@ -0,0 +1,540 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualAddon;
import dev.loki.lovisual.features.gui.hud.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.Module;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.runtime.ClientRuntime;
import dev.loki.lovisual.runtime.RuntimeResumeParticipant;
import dev.loki.lovisual.runtime.RuntimeShutdownContext;
import dev.loki.lovisual.runtime.RuntimeShutdownParticipant;
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;
public enum AddonManager {
;
public static final String ADDON_METADATA_KEY = "combatant: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 void registerRuntimeLifecycle() {
ClientRuntime.setAddonCounter(AddonManager::activeCount);
ClientRuntime.registerParticipant(new RuntimeShutdownParticipant() {
@Override
public String id() {
return "addons";
}
@Override
public void shutdown(RuntimeShutdownContext context) {
suspendForRuntime(context);
}
});
ClientRuntime.registerResumeParticipant(new RuntimeResumeParticipant() {
@Override
public String id() {
return "addons";
}
@Override
public void resume(String reason) {
resumeAfterRuntime(reason);
}
});
}
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("combatant", 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 suspendForRuntime(RuntimeShutdownContext context) {
int suspended = 0;
for (AddonRegistration registration : ADDONS.values()) {
if (registration.addon == null || registration.status != AddonStatus.ACTIVE) continue;
try {
if (context.jarReplacement()) {
shutdownAddon(registration, context.reason());
registration.status = AddonStatus.SHUTDOWN;
} else {
registration.addon.onRuntimeSuspended(
new LoVisualAddonRuntimeContextImpl(registration.descriptor.id())
);
registration.status = AddonStatus.SUSPENDED;
}
suspended++;
} 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());
}
}
context.increment("addons_suspended", suspended);
}
private static void resumeAfterRuntime(String reason) {
for (AddonRegistration registration : ADDONS.values()) {
if (registration.addon == null || registration.status != AddonStatus.SUSPENDED || !registration.enabled) {
continue;
}
resumeAddon(registration, reason);
if (registration.status != AddonStatus.ERROR) {
registration.status = AddonStatus.ACTIVE;
}
}
}
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();
}
static void noteModuleOwner(String addonId, String moduleId) {
if (moduleId != null && !moduleId.isBlank()) {
MODULE_OWNERS.put(normalizeId(moduleId), normalizeId(addonId));
}
}
static void noteDraggableHudOwner(String addonId, String elementId) {
if (elementId != null && !elementId.isBlank()) {
DRAGGABLE_HUD_OWNERS.put(normalizeId(elementId), normalizeId(addonId));
}
}
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,79 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
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;
final class AddonRegistration {
final AddonDescriptor descriptor;
final EntrypointContainer<LoVisualAddon> entrypoint;
final List<String> modules = new ArrayList<>();
final List<String> disabledBuiltInModules = new ArrayList<>();
final List<String> draggableHudElements = new ArrayList<>();
final List<String> staticHudElements = new ArrayList<>();
final List<String> commands = new ArrayList<>();
final List<String> clickGuiSections = new ArrayList<>();
final List<String> moduleExtensions = new ArrayList<>();
final List<String> irisPatchManifests = new ArrayList<>();
final List<String> renderCallbacks = new ArrayList<>();
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;
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)
);
}
void issue(AddonIssue.Severity severity, String message, String detail) {
issues.add(new AddonIssue(descriptor.id(), severity, message, detail));
}
}

View file

@ -0,0 +1,193 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import com.mojang.blaze3d.textures.GpuTextureView;
import com.mojang.blaze3d.vertex.PoseStack;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessCallback;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessContext;
import dev.loki.lovisual.api.v0.render.LoVisualRenderCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderContext;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import dev.loki.lovisual.features.module.HudPhase;
import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.render.engine.postprocess.PostProcessManager;
import dev.loki.lovisual.render.engine.postprocess.PostProcessPass;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.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;
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,32 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import java.util.List;
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,63 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
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;
final class AddonStateStore {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private AddonStateStore() {
}
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<>();
}
}
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("combatant")
.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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
public enum AddonStatus {
DISCOVERED,
DISABLED,
ACTIVE,
SUSPENDED,
ERROR,
SHUTDOWN
}

View file

@ -0,0 +1,144 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiRenderContext;
import dev.loki.lovisual.features.gui.clickgui.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;
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,206 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
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.LoVisualPostProcessCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.features.command.ClientCommand;
import dev.loki.lovisual.features.command.CommandManager;
import dev.loki.lovisual.features.gui.hud.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.Module;
import dev.loki.lovisual.render.engine.pipeline.CombatantRenderPipelines;
import dev.loki.lovisual.render.engine.postprocess.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;
final class LoVisualAddonContextImpl implements LoVisualAddonContext {
private final AddonRegistration registration;
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 = CombatantRenderPipelines.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.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.CommandContext ctx, int argIndex, String token) {
return delegate.suggest(ctx, argIndex, token);
}
@Override
public boolean execute(dev.loki.lovisual.features.command.CommandContext ctx) {
return isAvailable() && delegate.execute(ctx);
}
}
}

View file

@ -0,0 +1,29 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualAddonRuntimeContext;
import dev.loki.lovisual.api.v0.client.LoVisualClientApi;
final class LoVisualAddonRuntimeContextImpl implements LoVisualAddonRuntimeContext {
private final String addonId;
LoVisualAddonRuntimeContextImpl(String addonId) {
this.addonId = addonId;
}
@Override
public String addonId() {
return addonId;
}
@Override
public LoVisualClientApi client() {
return LoVisualClientApi.get();
}
}

View file

@ -0,0 +1,68 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.addon.LoVisualModuleLoadContext;
import dev.loki.lovisual.features.module.ModuleAutoLoader;
import java.util.ArrayList;
import java.util.List;
final class LoVisualModuleLoadContextImpl implements LoVisualModuleLoadContext {
private final AddonRegistration registration;
private final List<String> pendingExclusions = new ArrayList<>();
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;
}
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,55 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.module.ModuleExtensionContext;
import dev.loki.lovisual.config.SettingDef;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.config.values.ModeValue;
import dev.loki.lovisual.features.module.Module;
final class ModuleExtensionContextImpl implements ModuleExtensionContext {
private final String addonId;
private final Module module;
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,171 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.addon;
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.ModuleManager;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.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;
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,45 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
/**
* Fabric entrypoint contract for Combatant addons.
*
* <p>Declare it in fabric.mod.json under the {@value #ENTRYPOINT_KEY} entrypoint.
*/
public interface LoVisualAddon {
String ENTRYPOINT_KEY = "combatant: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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
import dev.loki.lovisual.events.UsedImplicitly;
import dev.loki.lovisual.features.command.ClientCommand;
import dev.loki.lovisual.api.v0.clickgui.LoVisualClickGuiSection;
import dev.loki.lovisual.features.gui.hud.AbstractHudElement;
import dev.loki.lovisual.features.gui.hud.draggable.DraggableHudElement;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.api.v0.module.LoVisualModuleExtension;
import dev.loki.lovisual.api.v0.render.LoVisualPostProcessCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderCallback;
import dev.loki.lovisual.api.v0.render.LoVisualRenderStage;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import dev.loki.lovisual.render.engine.postprocess.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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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,43 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.addon;
import dev.loki.lovisual.events.UsedImplicitly;
import dev.loki.lovisual.features.module.Module;
/**
* Early addon context used before Combatant'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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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.TextRenderer;
public record LoVisualClickGuiRenderContext(
Renderer2D renderer,
TextRenderer regularFont,
TextRenderer mediumFont
) {
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.client;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.features.module.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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.module;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.module;
import dev.loki.lovisual.config.SettingDef;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.features.module.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,13 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
@FunctionalInterface
public interface LoVisualPostProcessCallback {
boolean render(LoVisualPostProcessContext context);
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.textures.GpuTextureView;
import dev.loki.lovisual.render.engine.postprocess.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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
@FunctionalInterface
public interface LoVisualRenderCallback {
void render(LoVisualRenderContext context);
}

View file

@ -0,0 +1,36 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.api.v0.render;
import com.mojang.blaze3d.vertex.PoseStack;
import dev.loki.lovisual.features.module.HudPhase;
import dev.loki.lovisual.features.module.WorldPhase;
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
import dev.loki.lovisual.render.engine.renderer.Renderer3D;
import dev.loki.lovisual.render.engine.text.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,109 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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.CombatantRenderPipelines;
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 CombatantRenderPipelines.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 CombatantRenderPipelines.registerAddonPipeline(build());
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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.CombatantRenderSystem;
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 CombatantRenderSystem.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 CombatantRenderSystem.uniforms().writeCached(
name,
std140Size,
expectedWritesPerFrame,
updateEveryFrames,
force,
writer::write
);
}
public static GpuBufferSlice current(String name) {
if (name == null || name.isBlank()) return null;
return CombatantRenderSystem.uniforms().current(name);
}
public static void invalidate(String name) {
if (name == null || name.isBlank()) return;
CombatantRenderSystem.uniforms().invalidate(name);
}
@FunctionalInterface
public interface UniformWriter {
void write(ByteBuffer buffer);
}
}

View file

@ -0,0 +1,75 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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.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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.compat.xaero;
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 = "combatant";
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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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.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,31 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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;
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 Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* 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 = "combatant";
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,21 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class Event {
private boolean cancelled;
public void cancel() {
cancelled = true;
}
}

View file

@ -0,0 +1,263 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import dev.loki.lovisual.features.module.Module;
import dev.loki.lovisual.runtime.RuntimeGate;
import dev.loki.lovisual.util.logging.DebugLog;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public final class EventBus {
private static final Subscriber[] EMPTY_SUBSCRIBERS = new Subscriber[0];
private static final Comparator<Subscriber> PRIORITY =
Comparator.comparingInt((Subscriber sub) -> sub.priority).reversed();
private final Object lock = new Object();
private final Reference2ObjectOpenHashMap<Class<?>, Subscriber[]> exactHandlers = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<Class<?>, Subscriber[]> dispatchCache = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<Object, Subscriber[]> ownerIndex = new Reference2ObjectOpenHashMap<>();
private static Subscriber[] append(Subscriber[] old, Subscriber sub) {
Subscriber[] next = Arrays.copyOf(old, old.length + 1);
next[old.length] = sub;
return next;
}
private static Subscriber[] remove(Subscriber[] old, Subscriber sub) {
int index = -1;
for (int i = 0; i < old.length; i++) {
if (old[i] == sub) {
index = i;
break;
}
}
if (index < 0) return old;
if (old.length == 1) return EMPTY_SUBSCRIBERS;
Subscriber[] next = new Subscriber[old.length - 1];
System.arraycopy(old, 0, next, 0, index);
System.arraycopy(old, index + 1, next, index, old.length - index - 1);
return next;
}
private static void sortSubscribers(Subscriber[] subscribers) {
Arrays.sort(subscribers, PRIORITY);
}
public void register(Object listener) {
if (listener instanceof Module module) {
registerOwned(module, listener);
} else {
registerOwned(null, listener);
}
}
public void registerOwned(Module gateModule, Object listener) {
if (listener == null) return;
synchronized (lock) {
if (ownerIndex.containsKey(listener)) return;
Subscriber[] subs = scan(listener, gateModule);
if (subs.length == 0) return;
ownerIndex.put(listener, subs);
for (Subscriber sub : subs) {
Subscriber[] old = exactHandlers.get(sub.eventType);
if (old == null) old = EMPTY_SUBSCRIBERS;
Subscriber[] next = append(old, sub);
sortSubscribers(next);
exactHandlers.put(sub.eventType, next);
}
dispatchCache.clear();
}
}
public void unregister(Object listener) {
if (listener == null) return;
synchronized (lock) {
Subscriber[] subs = ownerIndex.remove(listener);
if (subs == null || subs.length == 0) return;
for (Subscriber sub : subs) {
Subscriber[] old = exactHandlers.get(sub.eventType);
if (old == null || old.length == 0) continue;
Subscriber[] next = remove(old, sub);
if (next.length == 0) {
exactHandlers.remove(sub.eventType);
} else {
exactHandlers.put(sub.eventType, next);
}
}
dispatchCache.clear();
}
}
public boolean hasListeners(Class<? extends Event> eventType) {
return subscribersFor(eventType).length != 0;
}
public <T extends Event> T post(T event) {
if (event == null) return null;
if (!RuntimeGate.canRunClientLogic()) return event;
Subscriber[] subscribers = subscribersFor(event.getClass());
for (Subscriber sub : subscribers) {
Module gate = sub.gateModule;
if (gate != null && !gate.isEnabled()) continue;
try {
sub.invoker.invoke(event);
} catch (Throwable t) {
DebugLog.error("Event handler failed: %s", t, sub.describe());
}
}
return event;
}
public void clear() {
synchronized (lock) {
exactHandlers.clear();
dispatchCache.clear();
ownerIndex.clear();
}
}
public int listenerCount() {
synchronized (lock) {
return ownerIndex.size();
}
}
private Subscriber[] scan(Object listener, Module gateModule) {
List<Subscriber> out = new ArrayList<>();
Class<?> cls = listener.getClass();
for (Method method : cls.getDeclaredMethods()) {
if (!method.isAnnotationPresent(EventHandler.class)) continue;
Class<?>[] params = method.getParameterTypes();
if (params.length != 1) continue;
if (!Event.class.isAssignableFrom(params[0])) continue;
EventHandler meta = method.getAnnotation(EventHandler.class);
method.setAccessible(true);
@SuppressWarnings("unchecked")
Class<? extends Event> eventType = (Class<? extends Event>) params[0];
EventInvoker invoker = createInvoker(listener, method);
out.add(new Subscriber(listener, gateModule, method, invoker, eventType, meta.priority()));
}
return out.toArray(Subscriber[]::new);
}
private EventInvoker createInvoker(Object listener, Method method) {
method.setAccessible(true);
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle handle = lookup.unreflect(method).bindTo(listener);
return handle::invoke;
} catch (Throwable t) {
DebugLog.error("Failed to create MethodHandle event invoker, falling back to reflection: %s", t,
listener.getClass().getName() + "#" + method.getName());
return event -> method.invoke(listener, event);
}
}
private Subscriber[] subscribersFor(Class<?> eventType) {
if (eventType == null) return EMPTY_SUBSCRIBERS;
synchronized (lock) {
Subscriber[] cached = dispatchCache.get(eventType);
if (cached != null) return cached;
Subscriber[] built = buildFlattenedSubscribers(eventType);
dispatchCache.put(eventType, built);
return built;
}
}
private Subscriber[] buildFlattenedSubscribers(Class<?> eventType) {
int total = 0;
Class<?> type = eventType;
while (type != null && Event.class.isAssignableFrom(type)) {
Subscriber[] exact = exactHandlers.get(type);
if (exact != null) total += exact.length;
type = type.getSuperclass();
}
if (total == 0) return EMPTY_SUBSCRIBERS;
Subscriber[] out = new Subscriber[total];
int offset = 0;
type = eventType;
while (type != null && Event.class.isAssignableFrom(type)) {
Subscriber[] exact = exactHandlers.get(type);
if (exact != null && exact.length > 0) {
System.arraycopy(exact, 0, out, offset, exact.length);
offset += exact.length;
}
type = type.getSuperclass();
}
return out;
}
@FunctionalInterface
private interface EventInvoker {
void invoke(Event event) throws Throwable;
}
private static final class Subscriber {
final Object owner;
final Module gateModule;
final Method method;
final EventInvoker invoker;
final Class<? extends Event> eventType;
final int priority;
final String description;
Subscriber(Object owner,
Module gateModule,
Method method,
EventInvoker invoker,
Class<? extends Event> eventType,
int priority) {
this.owner = owner;
this.gateModule = gateModule;
this.method = method;
this.invoker = invoker;
this.eventType = eventType;
this.priority = priority;
this.description = owner.getClass().getName() + "#" + method.getName();
}
String describe() {
return description;
}
}
}

View file

@ -0,0 +1,20 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@UsedImplicitly
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EventHandler {
int priority() default 0;
}

View file

@ -0,0 +1,14 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
public enum Events {
;
public static final EventBus BUS = new EventBus();
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks code that is intentionally reached through reflection, Fabric entrypoints,
* addon API calls, event dispatch, serialization, or other non-direct call paths.
*
* <p>This is a source-level documentation and IntelliJ IDEA inspection hint. It is
* not a runtime contract and should not be used for behavior checks.</p>
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE
})
public @interface UsedImplicitly {
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import dev.loki.lovisual.events.Event;
@Getter
public final class AttackEntityEvent extends Event {
private final Player player;
private final Entity target;
public AttackEntityEvent(Player player, Entity target) {
this.player = player;
this.target = target;
}
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of the Combatant Client distribution.
* Combatant modifications copyright (c) 2026 pivosos2007.
*
* Portions of this file are based on LiquidBounce
* (https://github.com/CCBlueX/LiquidBounce).
* Copyright (c) 2015-2026 CCBlueX.
*
* LiquidBounce portions are licensed under GPLv3-or-later.
* Combatant modifications are licensed under GPLv3.
* See THIRD_PARTY_NOTICES.md for details.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.network.protocol.Packet;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.util.network.BlinkManager;
import dev.loki.lovisual.util.network.TransferOrigin;
/**
* Adapted from LiquidBounce's BlinkPacketEvent.
*/
public class BlinkPacketEvent extends Event {
private final Packet<?> packet;
@Getter
private final TransferOrigin origin;
@Getter
private BlinkManager.Action action = BlinkManager.Action.FLUSH;
public BlinkPacketEvent(Packet<?> packet, TransferOrigin origin) {
this.packet = packet;
this.origin = origin;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>> T getPacket() {
return (T) packet;
}
public void setAction(BlinkManager.Action action) {
if (action == null || this.action == action || this.action.getPriority() >= action.getPriority()) {
return;
}
this.action = action;
}
}

View file

@ -0,0 +1,26 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import java.util.List;
public class CombatProtocolBossbarEvent extends Event {
public final List<String> names;
public final long timeMs;
public CombatProtocolBossbarEvent(List<String> names) {
this(names, System.currentTimeMillis());
}
public CombatProtocolBossbarEvent(List<String> names, long timeMs) {
this.names = names == null ? List.of() : List.copyOf(names);
this.timeMs = timeMs;
}
}

View file

@ -0,0 +1,30 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.HitResult;
import dev.loki.lovisual.events.Event;
@Getter
public final class CrosshairTargetUpdateEvent extends Event {
private final float tickDelta;
@Setter
private HitResult hitResult;
@Setter
private Entity targetedEntity;
public CrosshairTargetUpdateEvent(float tickDelta, HitResult hitResult, Entity targetedEntity) {
this.tickDelta = tickDelta;
this.hitResult = hitResult;
this.targetedEntity = targetedEntity;
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.core.BlockPos;
import dev.loki.lovisual.events.Event;
@Getter
public class EventBreakBlock extends Event {
private final BlockPos pos;
public EventBreakBlock(BlockPos pos) {
this.pos = pos;
}
}

View file

@ -0,0 +1,27 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.state.BlockState;
import dev.loki.lovisual.events.Event;
@Getter
public class EventCollision extends Event {
private final BlockPos pos;
@Setter
private BlockState state;
public EventCollision(BlockState state, BlockPos pos) {
this.state = state;
this.pos = pos;
}
}

View file

@ -0,0 +1,15 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
public class EventPostSync extends Event {
public EventPostSync() {
}
}

View file

@ -0,0 +1,23 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
@Getter
public class EventPushOutOfBlocks extends Event {
private final double x;
private final double z;
public EventPushOutOfBlocks(double x, double z) {
this.x = x;
this.z = z;
}
}

View file

@ -0,0 +1,69 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
public class EventSync extends Event {
@Getter
private final float originalYaw;
@Getter
private final float originalPitch;
@Getter
private float yaw;
@Getter
private float pitch;
private boolean rotationOverride;
@Getter
private boolean silentRotation;
@Getter
private Runnable postAction;
public EventSync(float yaw, float pitch) {
this.originalYaw = yaw;
this.originalPitch = pitch;
this.yaw = yaw;
this.pitch = pitch;
}
public void setYaw(float yaw) {
this.yaw = yaw;
this.rotationOverride = true;
}
public void setPitch(float pitch) {
this.pitch = pitch;
this.rotationOverride = true;
}
public void setRotation(float yaw, float pitch, boolean silent) {
this.yaw = yaw;
this.pitch = pitch;
this.rotationOverride = true;
this.silentRotation = silent;
}
public boolean hasRotationOverride() {
return rotationOverride;
}
public void addPostAction(Runnable r) {
if (r == null) return;
if (postAction == null) {
postAction = r;
} else {
Runnable prev = postAction;
postAction = () -> {
prev.run();
r.run();
};
}
}
}

View file

@ -0,0 +1,32 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import net.minecraft.world.entity.LivingEntity;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.util.target.TargetManager;
/**
* Fired when the centralized target changes.
*/
public class EventTargetChanged extends Event {
public final LivingEntity previous;
public final TargetManager.Source previousSource;
public final LivingEntity current;
public final TargetManager.Source currentSource;
public EventTargetChanged(LivingEntity previous,
TargetManager.Source previousSource,
LivingEntity current,
TargetManager.Source currentSource) {
this.previous = previous;
this.previousSource = previousSource;
this.current = current;
this.currentSource = currentSource;
}
}

View file

@ -0,0 +1,24 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Setter
@Getter
public final class FireworkEvent extends Event {
private Vec3 vector;
public FireworkEvent(Vec3 vector) {
this.vector = vector;
}
}

View file

@ -0,0 +1,16 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
/**
* Fired at the start of each client tick.
*/
public final class GameTickEvent extends Event {
}

View file

@ -0,0 +1,94 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.config.SettingDef;
import dev.loki.lovisual.config.SettingOwner;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.features.gui.clickgui.settings.Setting;
import dev.loki.lovisual.features.gui.clickgui.settings.SettingFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Collects setting-backed i18n keys after language resources are loaded.
*/
public final class I18nPreflightCollectEvent extends Event {
private final String reason;
private final ArrayList<Entry> entries = new ArrayList<>();
public I18nPreflightCollectEvent(String reason) {
this.reason = reason != null && !reason.isBlank() ? reason : "i18n preflight";
}
public String reason() {
return reason;
}
public I18nPreflightCollectEvent setting(Setting setting) {
return setting("settings", setting);
}
public I18nPreflightCollectEvent setting(String path, Setting setting) {
if (setting != null) {
entries.add(new Entry(normalizePath(path), setting));
}
return this;
}
public I18nPreflightCollectEvent settings(Iterable<? extends Setting> values) {
return settings("settings", values);
}
public I18nPreflightCollectEvent settings(String path, Iterable<? extends Setting> values) {
if (values == null) return this;
for (Setting setting : values) {
setting(path, setting);
}
return this;
}
public I18nPreflightCollectEvent settingDefs(SettingOwner owner, Iterable<SettingDef> defs) {
return settingDefs(owner != null ? owner.name() : "settings", owner, defs);
}
public I18nPreflightCollectEvent settingDefs(String path, SettingOwner owner, Iterable<SettingDef> defs) {
if (owner == null || defs == null) return this;
for (SettingDef def : defs) {
Setting setting = SettingFactory.fromDef(def);
if (setting == null) continue;
setting.setParent(owner);
setting(path, setting);
}
return this;
}
public List<Entry> entries() {
return Collections.unmodifiableList(entries);
}
public boolean isEmpty() {
return entries.isEmpty();
}
private static String normalizePath(String path) {
if (path == null || path.isBlank()) return "settings";
String normalized = path.trim().replace('\\', '/');
while (normalized.contains("//")) {
normalized = normalized.replace("//", "/");
}
if (normalized.startsWith("/")) normalized = normalized.substring(1);
if (normalized.endsWith("/")) normalized = normalized.substring(0, normalized.length() - 1);
return normalized.isBlank() ? "settings" : normalized;
}
public record Entry(String path, Setting setting) {
}
}

View file

@ -0,0 +1,24 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.client.input.KeyEvent;
import dev.loki.lovisual.events.Event;
@Getter
public final class KeyInputEvent extends Event {
private final int action;
private final KeyEvent input;
public KeyInputEvent(int action, KeyEvent input) {
this.action = action;
this.input = input;
}
}

View file

@ -0,0 +1,27 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.KeyMapping;
import dev.loki.lovisual.events.Event;
@Getter
public final class KeybindIsPressedEvent extends Event {
private final KeyMapping keyBinding;
@Setter
private boolean pressed;
public KeybindIsPressedEvent(KeyMapping keyBinding, boolean pressed) {
this.keyBinding = keyBinding;
this.pressed = pressed;
}
}

View file

@ -0,0 +1,34 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Getter
public class LightmapEvent extends Event {
private final float originalAmbient;
@Setter
private float ambientLight;
public LightmapEvent(float ambientLight) {
this.originalAmbient = ambientLight;
this.ambientLight = ambientLight;
}
public void raiseAmbientLight(float ambientLight) {
if (ambientLight > this.ambientLight) {
this.ambientLight = ambientLight;
}
}
public boolean isModified() {
return Math.abs(ambientLight - originalAmbient) > 1.0e-4f;
}
}

View file

@ -0,0 +1,81 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.client.renderer.state.LightmapRenderState;
import net.minecraft.util.Mth;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import dev.loki.lovisual.events.Event;
public class LightmapModifyEvent extends Event {
private static final float EPSILON = 1.0e-4f;
private final LightmapRenderState state;
private final float originalBrightness;
@Getter
private boolean modified;
public LightmapModifyEvent(LightmapRenderState state) {
this.state = state;
this.originalBrightness = state != null ? state.brightness : 0.0f;
}
public LightmapRenderState state() {
return state;
}
public float originalBrightness() {
return originalBrightness;
}
public void raiseMinimumLight(float minLight) {
if (state == null) return;
float strength = Mth.clamp(minLight, 0.0f, 1.0f);
if (strength <= EPSILON) return;
state.needsUpdate = true;
// Do not emulate FullBright by forcing brightness/night vision to 1.0.
// In the 1.21+ UBO lightmap path that behaves like global exposure and blows out the scene.
float exposureFloor = 0.08f + 0.18f * strength;
state.brightness = Math.max(state.brightness, exposureFloor);
state.nightVisionEffectIntensity = Math.max(state.nightVisionEffectIntensity, 0.10f * strength);
// Lift the generated lightmap itself, but keep vanilla color response instead of whitening it.
state.skyFactor = Math.max(state.skyFactor, 0.55f + 0.35f * strength);
state.blockFactor = Math.max(state.blockFactor, 1.4f + 0.25f * strength);
// FullBright must not be attenuated by darkness/boss-world darkening.
float attenuation = 1.0f - strength;
state.darknessEffectScale *= attenuation;
state.bossOverlayWorldDarkening *= attenuation;
float colorFloor = 0.10f + 0.28f * strength;
state.blockLightTint = raiseColorFloor(state.blockLightTint, colorFloor);
state.skyLightColor = raiseColorFloor(state.skyLightColor, colorFloor);
state.ambientColor = raiseColorFloor(state.ambientColor, colorFloor);
state.nightVisionColor = raiseColorFloor(state.nightVisionColor, colorFloor);
modified = true;
}
private static Vector3fc raiseColorFloor(Vector3fc color, float floor) {
float min = Mth.clamp(floor, 0.0f, 1.0f);
if (color == null) {
return new Vector3f(min, min, min);
}
return new Vector3f(
Math.max(color.x(), min),
Math.max(color.y(), min),
Math.max(color.z(), min)
);
}
}

View file

@ -0,0 +1,45 @@
/*
* This file is part of the Combatant Client distribution.
* Combatant modifications copyright (c) 2026 pivosos2007.
*
* Portions of this file are based on LiquidBounce
* (https://github.com/CCBlueX/LiquidBounce).
* Copyright (c) 2015-2026 CCBlueX.
*
* LiquidBounce portions are licensed under GPLv3-or-later.
* Combatant modifications are licensed under GPLv3.
* See THIRD_PARTY_NOTICES.md for details.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.entity.player.Input;
import dev.loki.lovisual.events.Event;
@Setter
@Getter
public final class MovementInputEvent extends Event {
private boolean forward;
private boolean backward;
private boolean left;
private boolean right;
private boolean jump;
private boolean sneak;
private boolean sprint;
public MovementInputEvent(Input input) {
this.forward = input.forward();
this.backward = input.backward();
this.left = input.left();
this.right = input.right();
this.jump = input.jump();
this.sneak = input.shift();
this.sprint = input.sprint();
}
public Input toPlayerInput() {
return new Input(forward, backward, left, right, jump, sneak, sprint);
}
}

View file

@ -0,0 +1,76 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.network.protocol.Packet;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.util.network.TransferOrigin;
public class PacketEvent extends Event {
private final Packet<?> packet;
@Getter
private final TransferOrigin origin;
@Getter
private final boolean original;
public PacketEvent(Packet<?> packet) {
this(packet, null, true);
}
public PacketEvent(Packet<?> packet, TransferOrigin origin, boolean original) {
this.packet = packet;
this.origin = origin;
this.original = original;
}
@SuppressWarnings("unchecked")
public <T extends Packet<?>> T getPacket() {
return (T) this.packet;
}
public static class Send extends PacketEvent {
public Send(Packet<?> packet) {
super(packet, TransferOrigin.OUTGOING, true);
}
public Send(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.OUTGOING, original);
}
}
public static class Receive extends PacketEvent {
public Receive(Packet<?> packet) {
super(packet, TransferOrigin.INCOMING, true);
}
public Receive(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.INCOMING, original);
}
}
public static class SendPost extends PacketEvent {
public SendPost(Packet<?> packet) {
super(packet, TransferOrigin.OUTGOING, true);
}
@SuppressWarnings("unused")
public SendPost(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.OUTGOING, original);
}
}
public static class ReceivePost extends PacketEvent {
public ReceivePost(Packet<?> packet) {
super(packet, TransferOrigin.INCOMING, true);
}
@SuppressWarnings("unused")
public ReceivePost(Packet<?> packet, boolean original) {
super(packet, TransferOrigin.INCOMING, original);
}
}
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public final class PlayerJumpEvent extends Event {
private float yaw;
private float motion;
public PlayerJumpEvent(float yaw, float motion) {
this.yaw = yaw;
this.motion = motion;
}
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of the Combatant Client distribution.
* Combatant modifications copyright (c) 2026 pivosos2007.
*
* Portions of this file are based on, adapted from, or implemented
* with reference to Meteor Client
* (https://github.com/MeteorDevelopment/meteor-client).
* Copyright (c) Meteor Development.
*
* Licensed under the GNU General Public License v3.0.
* See THIRD_PARTY_NOTICES.md for details.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Getter
public class PlayerMoveEvent extends Event {
private final MoverType type;
@Setter
private Vec3 movement;
public PlayerMoveEvent(MoverType type, Vec3 movement) {
this.type = type;
this.movement = movement;
}
}

View file

@ -0,0 +1,19 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class PlayerSafeWalkEvent extends Event {
private boolean safeWalk;
}

View file

@ -0,0 +1,23 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public final class PlayerStepEvent extends Event {
private float height;
public PlayerStepEvent(float height) {
this.height = height;
}
}

View file

@ -0,0 +1,22 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Getter
public final class PlayerStepSuccessEvent extends Event {
private final Vec3 adjustedVec;
public PlayerStepSuccessEvent(Vec3 adjustedVec) {
this.adjustedVec = adjustedVec;
}
}

View file

@ -0,0 +1,31 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.world.phys.Vec3;
import dev.loki.lovisual.events.Event;
@Getter
public class PlayerVelocityStrafe extends Event {
private final Vec3 movementInput;
private final float speed;
private final float yaw;
@Setter
private Vec3 velocity;
public PlayerVelocityStrafe(Vec3 movementInput, float speed, float yaw, Vec3 velocity) {
this.movementInput = movementInput;
this.speed = speed;
this.yaw = yaw;
this.velocity = velocity;
}
}

View file

@ -0,0 +1,19 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class PostPlayerUpdateEvent extends Event {
private int iterations;
}

View file

@ -0,0 +1,33 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
/**
* Fired when a PvP-related chat or game message is received.
*/
public class PvpChatEvent extends Event {
public final String message;
public final Source source;
public final long timeMs;
public PvpChatEvent(String message, Source source) {
this(message, source, System.currentTimeMillis());
}
public PvpChatEvent(String message, Source source, long timeMs) {
this.message = message;
this.source = source;
this.timeMs = timeMs;
}
public enum Source {
GAME_MESSAGE,
CHAT_MESSAGE
}
}

View file

@ -0,0 +1,30 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import net.minecraft.network.chat.Component;
import dev.loki.lovisual.events.Event;
/**
* Fired when an in-game HUD overlay message is shown (action bar).
*/
public class PvpOverlayEvent extends Event {
public final Component message;
public final boolean tinted;
public final long timeMs;
public PvpOverlayEvent(Component message, boolean tinted) {
this(message, tinted, System.currentTimeMillis());
}
public PvpOverlayEvent(Component message, boolean tinted, long timeMs) {
this.message = message;
this.tinted = tinted;
this.timeMs = timeMs;
}
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
/**
* Fired when the server updates tab-list header/footer text.
*/
public class PvpTabEvent extends Event {
public final String header;
public final String footer;
public final long timeMs;
public PvpTabEvent(String header, String footer) {
this(header, footer, System.currentTimeMillis());
}
public PvpTabEvent(String header, String footer, long timeMs) {
this.header = header == null ? "" : header;
this.footer = footer == null ? "" : footer;
this.timeMs = timeMs;
}
public String combinedText() {
if (header.isBlank()) return footer;
if (footer.isBlank()) return header;
return header + "\n" + footer;
}
}

View file

@ -0,0 +1,81 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import dev.loki.lovisual.render.engine.svg.SvgRegistry;
import dev.loki.lovisual.render.engine.text.FontInfo;
import net.minecraft.resources.Identifier;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Collects render resources that are known to be needed before the first GUI/HUD draw.
* Producers should add only resources implied by current runtime state/config: enabled
* modules, enabled HUD elements, and UI surfaces that can be opened immediately.
*/
public final class RenderPrewarmCollectEvent extends Event {
private final String reason;
private final LinkedHashSet<FontInfo> fonts = new LinkedHashSet<>();
private final LinkedHashSet<Identifier> svgMsdfIcons = new LinkedHashSet<>();
public RenderPrewarmCollectEvent(String reason) {
this.reason = reason != null ? reason : "render prewarm";
}
public String reason() {
return reason;
}
public RenderPrewarmCollectEvent font(String family) {
return font(family, FontInfo.Type.Regular);
}
public RenderPrewarmCollectEvent font(String family, FontInfo.Type type) {
if (family == null || family.isBlank()) return this;
fonts.add(new FontInfo(family.trim(), type != null ? type : FontInfo.Type.Regular));
return this;
}
public RenderPrewarmCollectEvent font(@Nullable FontInfo info) {
if (info != null && info.family() != null && !info.family().isBlank()) {
fonts.add(info);
}
return this;
}
public RenderPrewarmCollectEvent svg(String nameOrPath) {
Identifier id = SvgRegistry.resolve(nameOrPath);
if (id != null) {
svgMsdfIcons.add(id);
}
return this;
}
public RenderPrewarmCollectEvent svg(@Nullable Identifier id) {
if (id != null) {
svgMsdfIcons.add(id);
}
return this;
}
public Set<FontInfo> fonts() {
return Collections.unmodifiableSet(fonts);
}
public Set<Identifier> svgMsdfIcons() {
return Collections.unmodifiableSet(svgMsdfIcons);
}
public boolean isEmpty() {
return fonts.isEmpty() && svgMsdfIcons.isEmpty();
}
}

View file

@ -0,0 +1,28 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
/**
* Rotation lifecycle event fired each tick in two phases.
*/
@Getter
public final class RotationUpdateEvent extends Event {
private final Type type;
public RotationUpdateEvent(Type type) {
this.type = type == null ? Type.PRE : type;
}
public enum Type {
PRE,
POST
}
}

View file

@ -0,0 +1,43 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.events.impl;
import dev.loki.lovisual.events.Event;
import lombok.Getter;
import lombok.Setter;
public class SprintControlEvent extends Event {
@Getter
private final float forward;
@Getter
private final float sideways;
@Getter
private final Source source;
@Setter
private boolean sprint;
public SprintControlEvent(float forward, float sideways, boolean sprint, Source source) {
this.forward = forward;
this.sideways = sideways;
this.sprint = sprint;
this.source = source;
}
public boolean isMoving() {
return forward != 0.0f || sideways != 0.0f;
}
public boolean shouldSprint() {
return sprint;
}
public enum Source {
INPUT,
MOVEMENT_TICK,
NETWORK
}
}

View file

@ -0,0 +1,35 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
public enum AccountAuthType {
OFFLINE("offline"),
MICROSOFT("microsoft");
private final String id;
AccountAuthType(String id) {
this.id = id;
}
public String id() {
return id;
}
public static AccountAuthType byId(String raw) {
if (raw == null || raw.isBlank()) {
return OFFLINE;
}
for (AccountAuthType type : values()) {
if (type.id.equalsIgnoreCase(raw.trim()) || type.name().equalsIgnoreCase(raw.trim())) {
return type;
}
}
return OFFLINE;
}
}

View file

@ -0,0 +1,473 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
import net.minecraft.resources.Identifier;
import dev.loki.lovisual.config.ConfigNameProvider;
import dev.loki.lovisual.config.ConfigSerializer;
import dev.loki.lovisual.config.JsonConfigObject;
import dev.loki.lovisual.config.values.ConfigValue;
import dev.loki.lovisual.config.values.StringValue;
import dev.loki.lovisual.util.session.MicrosoftSessionResult;
import dev.loki.lovisual.util.session.SessionChanger;
import dev.loki.lovisual.util.session.microsoft.MicrosoftAuthService;
import dev.loki.lovisual.util.logging.DebugLog;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public final class AccountConfig implements JsonConfigObject, ConfigNameProvider {
public static final AccountConfig INSTANCE = new AccountConfig();
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
private final AccountsValue accounts = new AccountsValue("accounts");
private final StringValue activeAccountName = new StringValue("active_name", "");
private final StringValue activeAccountDate = new StringValue("active_date", "");
private final StringValue activeAccountSkin = new StringValue("active_skin", "");
private String microsoftAuthorizationRequiredName = "";
private AccountConfig() {
ConfigSerializer.load(this);
applyActiveSession();
}
public static AccountConfig get() {
return INSTANCE;
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
private static String normalizeName(String name) {
return name == null ? "" : name.trim();
}
private static String nowString() {
return LocalDateTime.now().format(DATE_FORMAT);
}
private static Identifier parseIdentifier(String raw) {
if (isBlank(raw)) {
return null;
}
try {
return Identifier.parse(raw);
} catch (Exception ignored) {
return null;
}
}
private static UUID parseUuid(String raw) {
if (isBlank(raw)) {
return null;
}
try {
return UUID.fromString(raw.trim());
} catch (Exception ignored) {
return null;
}
}
public List<AccountEntry> getAccounts() {
return accounts.get();
}
public List<AccountEntry> getSortedAccounts() {
List<AccountEntry> sorted = new ArrayList<>(accounts.get());
sorted.sort(Comparator
.comparing(AccountEntry::isPinned).reversed()
.thenComparingInt(AccountEntry::getOriginalIndex));
return sorted;
}
public AccountEntry getAccountBySortedIndex(int sortedIndex) {
List<AccountEntry> sorted = getSortedAccounts();
if (sortedIndex < 0 || sortedIndex >= sorted.size()) {
return null;
}
return sorted.get(sortedIndex);
}
public AccountEntry findByName(String name) {
String normalized = normalizeName(name);
if (normalized.isEmpty()) {
return null;
}
for (AccountEntry entry : accounts.get()) {
if (normalizeName(entry.getName()).equals(normalized)) {
return entry;
}
}
return null;
}
public AccountEntry addAccount(String name) {
return addAccount(name, nowString(), null);
}
public AccountEntry addAccount(String name, String date, Identifier skin) {
String cleanName = normalizeName(name);
if (cleanName.isEmpty()) {
return null;
}
AccountEntry existing = findByName(cleanName);
if (existing != null) {
existing.setAuthType(AccountAuthType.OFFLINE);
existing.setOnlineUuid(null);
existing.setMicrosoftRefreshToken("");
clearAuthorizationRequired(existing.getName());
if (!isBlank(date)) {
existing.setDate(date);
}
if (skin != null) {
existing.setSkin(skin);
}
save();
return existing;
}
AccountEntry entry = new AccountEntry(cleanName, isBlank(date) ? nowString() : date, skin, false, accounts.get().size());
accounts.get().add(entry);
save();
return entry;
}
public AccountEntry addMicrosoftAccount(MicrosoftSessionResult session) {
if (session == null || isBlank(session.name()) || session.uuid() == null || isBlank(session.refreshToken())) {
return null;
}
AccountEntry existing = findByName(session.name());
if (existing != null) {
existing.applyMicrosoftSession(session);
existing.setDate(nowString());
clearAuthorizationRequired(existing.getName());
save();
return existing;
}
AccountEntry entry = new AccountEntry(
session.name(),
nowString(),
null,
false,
accounts.get().size(),
AccountAuthType.MICROSOFT,
session.uuid(),
session.refreshToken()
);
accounts.get().add(entry);
clearAuthorizationRequired(entry.getName());
save();
return entry;
}
public void removeAccount(AccountEntry entry) {
if (entry == null) {
return;
}
if (!accounts.get().remove(entry)) {
return;
}
if (isActive(entry)) {
clearActiveAccount();
} else {
reindexAccounts();
save();
}
}
public void removeAccountBySortedIndex(int sortedIndex) {
removeAccount(getAccountBySortedIndex(sortedIndex));
}
public void clearAllAccounts() {
accounts.get().clear();
activeAccountName.set("");
activeAccountDate.set("");
activeAccountSkin.set("");
microsoftAuthorizationRequiredName = "";
save();
}
public void togglePin(int sortedIndex) {
AccountEntry entry = getAccountBySortedIndex(sortedIndex);
if (entry == null) {
return;
}
entry.togglePinned();
save();
}
public void setActiveAccount(AccountEntry entry) {
if (entry == null) {
clearActiveAccount();
return;
}
activeAccountName.set(normalizeName(entry.getName()));
activeAccountDate.set(entry.getDate() == null ? "" : entry.getDate());
Identifier skin = entry.getSkin();
activeAccountSkin.set(skin == null ? "" : skin.toString());
applySession(entry);
save();
}
public void setActiveAccount(String name, String date, Identifier skin) {
String cleanName = normalizeName(name);
if (cleanName.isEmpty()) {
clearActiveAccount();
return;
}
AccountEntry entry = findByName(cleanName);
if (entry == null) {
entry = addAccount(cleanName, date, skin);
} else {
if (!isBlank(date)) {
entry.setDate(date);
}
if (skin != null) {
entry.setSkin(skin);
}
}
setActiveAccount(entry);
}
public void clearActiveAccount() {
activeAccountName.set("");
activeAccountDate.set("");
activeAccountSkin.set("");
reindexAccounts();
save();
}
public String getActiveAccountName() {
return activeAccountName.get();
}
public String getActiveAccountDate() {
return activeAccountDate.get();
}
public Identifier getActiveAccountSkin() {
return parseIdentifier(activeAccountSkin.get());
}
public boolean isMicrosoftAuthorizationRequired() {
return getMicrosoftAuthorizationRequiredAccount() != null;
}
public AccountEntry getMicrosoftAuthorizationRequiredAccount() {
if (isBlank(microsoftAuthorizationRequiredName)) {
return null;
}
AccountEntry entry = findByName(microsoftAuthorizationRequiredName);
return entry != null && entry.isMicrosoft() ? entry : null;
}
public void clearMicrosoftAuthorizationRequired() {
microsoftAuthorizationRequiredName = "";
}
public void save() {
reindexAccounts();
ConfigSerializer.requestSave(this);
}
@Override
public String getConfigName() {
return "accounts";
}
@Override
public List<ConfigValue<?>> getConfigValues() {
List<ConfigValue<?>> values = new ArrayList<>();
values.add(accounts);
values.add(activeAccountName);
values.add(activeAccountDate);
values.add(activeAccountSkin);
return values;
}
private void applyActiveSession() {
if (isBlank(activeAccountName.get())) {
return;
}
AccountEntry entry = findByName(activeAccountName.get());
if (entry != null) {
applySession(entry);
} else {
SessionChanger.changeUsername(activeAccountName.get());
}
}
private void applySession(AccountEntry entry) {
if (entry == null) {
return;
}
if (!entry.isMicrosoft()) {
clearAuthorizationRequired(entry.getName());
SessionChanger.changeUsername(entry.getName())
.exceptionally(t -> {
DebugLog.error("[AccountConfig] Failed to apply offline account session: " + entry.getName(), t);
return null;
});
return;
}
String refreshToken = entry.getMicrosoftRefreshToken();
if (isBlank(refreshToken)) {
if (SessionChanger.canUseOriginalLauncherSession(entry.getName(), entry.getOnlineUuid())) {
clearAuthorizationRequired(entry.getName());
SessionChanger.restoreOriginalLauncherSession(false)
.exceptionally(t -> {
DebugLog.error("[AccountConfig] Failed to restore launcher Microsoft session: " + entry.getName(), t);
markAuthorizationRequired(entry);
return null;
});
return;
}
markAuthorizationRequired(entry);
DebugLog.warnOnce("alt-microsoft-token-empty-" + entry.getName(), "[AccountConfig] Microsoft account requires authorization: %s", entry.getName());
return;
}
clearAuthorizationRequired(entry.getName());
MicrosoftAuthService.loginWithRefreshToken(refreshToken)
.thenCompose(session -> {
entry.applyMicrosoftSession(session);
activeAccountName.set(session.name());
activeAccountDate.set(entry.getDate() == null ? "" : entry.getDate());
save();
return SessionChanger.changeSession(session.toLoginData());
})
.exceptionally(t -> {
DebugLog.error("[AccountConfig] Failed to apply Microsoft account session: " + entry.getName(), t);
markAuthorizationRequired(entry);
return null;
});
}
private void markAuthorizationRequired(AccountEntry entry) {
microsoftAuthorizationRequiredName = entry == null ? "" : normalizeName(entry.getName());
}
private void clearAuthorizationRequired(String name) {
if (normalizeName(name).equalsIgnoreCase(normalizeName(microsoftAuthorizationRequiredName))) {
microsoftAuthorizationRequiredName = "";
}
}
private boolean isActive(AccountEntry entry) {
if (entry == null) {
return false;
}
return normalizeName(entry.getName()).equals(normalizeName(activeAccountName.get()));
}
private void reindexAccounts() {
List<AccountEntry> list = accounts.get();
for (int i = 0; i < list.size(); i++) {
list.get(i).setOriginalIndex(i);
}
}
private static final class AccountsValue extends ConfigValue<List<AccountEntry>> {
private AccountsValue(String name) {
super(name, new ArrayList<>());
}
private static String stringValue(Object value) {
if (value == null) {
return "";
}
return String.valueOf(value).trim();
}
private static boolean boolValue(Object value) {
if (value instanceof Boolean bool) {
return bool;
}
if (value instanceof String string) {
return Boolean.parseBoolean(string);
}
return false;
}
private static int intValue(Object value, int fallback) {
if (value instanceof Number number) {
return Math.max(0, number.intValue());
}
if (value instanceof String string) {
try {
return Math.max(0, Integer.parseInt(string.trim()));
} catch (NumberFormatException ignored) {
return fallback;
}
}
return fallback;
}
@Override
public Object toJson() {
List<Object> out = new ArrayList<>();
for (AccountEntry entry : value) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("name", entry.getName());
row.put("date", entry.getDate());
row.put("skin", entry.getSkin() == null ? "" : entry.getSkin().toString());
row.put("pinned", entry.isPinned());
row.put("originalIndex", entry.getOriginalIndex());
row.put("authType", entry.getAuthType().id());
row.put("onlineUuid", entry.getOnlineUuid() == null ? "" : entry.getOnlineUuid().toString());
row.put("microsoftRefreshToken", "");
out.add(row);
}
return out;
}
@Override
public void fromJson(Object json) {
List<AccountEntry> loaded = new ArrayList<>();
if (json instanceof Iterable<?> iterable) {
int fallbackIndex = 0;
for (Object item : iterable) {
if (!(item instanceof Map<?, ?> row)) {
continue;
}
String name = stringValue(row.get("name"));
if (name.isBlank()) {
continue;
}
String date = stringValue(row.get("date"));
Identifier skin = parseIdentifier(stringValue(row.get("skin")));
boolean pinned = boolValue(row.get("pinned"));
int originalIndex = intValue(row.get("originalIndex"), fallbackIndex);
AccountAuthType authType = AccountAuthType.byId(stringValue(row.get("authType")));
UUID onlineUuid = parseUuid(stringValue(row.get("onlineUuid")));
loaded.add(new AccountEntry(name, date, skin, pinned, originalIndex, authType, onlineUuid, ""));
fallbackIndex++;
}
}
loaded.sort(Comparator.comparingInt(AccountEntry::getOriginalIndex));
value = loaded;
}
}
}

View file

@ -0,0 +1,91 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
import dev.loki.lovisual.util.session.MicrosoftSessionResult;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.resources.Identifier;
import java.util.UUID;
@Getter
public final class AccountEntry {
private String name;
private String date;
@Setter
private Identifier skin;
@Setter
private boolean pinned;
private int originalIndex;
private AccountAuthType authType;
@Setter
private UUID onlineUuid;
private String microsoftRefreshToken;
public AccountEntry(String name, String date, Identifier skin, boolean pinned, int originalIndex) {
this(name, date, skin, pinned, originalIndex, AccountAuthType.OFFLINE, null, "");
}
public AccountEntry(String name,
String date,
Identifier skin,
boolean pinned,
int originalIndex,
AccountAuthType authType,
UUID onlineUuid,
String microsoftRefreshToken) {
this.name = name == null ? "" : name;
this.date = date == null ? "" : date;
this.skin = skin;
this.pinned = pinned;
this.originalIndex = Math.max(0, originalIndex);
this.authType = authType == null ? AccountAuthType.OFFLINE : authType;
this.onlineUuid = onlineUuid;
this.microsoftRefreshToken = microsoftRefreshToken == null ? "" : microsoftRefreshToken;
}
public void setName(String name) {
this.name = name == null ? "" : name;
}
public void setDate(String date) {
this.date = date == null ? "" : date;
}
public void togglePinned() {
pinned = !pinned;
}
public void setOriginalIndex(int originalIndex) {
this.originalIndex = Math.max(0, originalIndex);
}
public void setAuthType(AccountAuthType authType) {
this.authType = authType == null ? AccountAuthType.OFFLINE : authType;
}
public boolean isMicrosoft() {
return authType == AccountAuthType.MICROSOFT;
}
public void setMicrosoftRefreshToken(String microsoftRefreshToken) {
this.microsoftRefreshToken = microsoftRefreshToken == null ? "" : microsoftRefreshToken;
}
public void applyMicrosoftSession(MicrosoftSessionResult session) {
if (session == null) {
return;
}
this.authType = AccountAuthType.MICROSOFT;
this.name = session.name();
this.onlineUuid = session.uuid();
this.microsoftRefreshToken = session.refreshToken();
}
}

View file

@ -0,0 +1,183 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.account;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.player.PlayerSkin;
import dev.loki.lovisual.util.player.PlayerSkinResolver;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
public enum SkinManager {
;
private static final Map<String, Identifier> CACHE = new ConcurrentHashMap<>();
private static final Map<String, Boolean> LOADING = new ConcurrentHashMap<>();
private static final Executor EXECUTOR = Executors.newFixedThreadPool(3, runnable -> {
Thread thread = new Thread(runnable, "LoVisual-AltSkinLoader");
thread.setDaemon(true);
return thread;
});
public static Identifier getSkin(String playerName) {
String key = normalizeKey(playerName);
if (key.isEmpty()) {
return defaultSkin(playerName);
}
Identifier cached = CACHE.get(key);
if (cached != null) {
return cached;
}
if (LOADING.putIfAbsent(key, Boolean.TRUE) == null) {
CompletableFuture.runAsync(() -> loadSkin(playerName, key), EXECUTOR);
}
return defaultSkin(playerName);
}
public static void removeSkin(String playerName) {
String key = normalizeKey(playerName);
if (key.isEmpty()) {
return;
}
CACHE.remove(key);
LOADING.remove(key);
}
public static void reloadSkin(String playerName) {
removeSkin(playerName);
getSkin(playerName);
}
public static void clearCache() {
CACHE.clear();
LOADING.clear();
}
private static void loadSkin(String playerName, String key) {
try {
UUID uuid = fetchUuid(playerName);
if (uuid == null) {
return;
}
Minecraft client = Minecraft.getInstance();
if (client == null || client.getSkinManager() == null) {
return;
}
GameProfile profile = new GameProfile(uuid, playerName);
Supplier<PlayerSkin> supplier = client.getSkinManager().createLookup(profile, false);
if (supplier == null) {
return;
}
PlayerSkin textures = supplier.get();
Identifier skin = PlayerSkinResolver.resolveAssetId(textures == null ? null : textures.body());
if (skin != null) {
CACHE.put(key, skin);
}
} catch (Throwable ignored) {
} finally {
LOADING.remove(key);
}
}
private static UUID fetchUuid(String playerName) {
String cleanName = normalizeName(playerName);
if (cleanName.isEmpty()) {
return null;
}
try {
HttpURLConnection connection = (HttpURLConnection) URI
.create("https://api.mojang.com/users/profiles/minecraft/" + cleanName)
.toURL()
.openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "LoVisual");
if (connection.getResponseCode() != 200) {
connection.disconnect();
return null;
}
try (InputStreamReader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
if (!json.has("id")) {
return null;
}
return parseUuid(json.get("id").getAsString());
} finally {
connection.disconnect();
}
} catch (Throwable ignored) {
return null;
}
}
private static UUID parseUuid(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
String value = raw.trim();
if (value.length() == 32) {
value = value.substring(0, 8) + "-" + value.substring(8, 12) + "-" + value.substring(12, 16)
+ "-" + value.substring(16, 20) + "-" + value.substring(20);
}
try {
return UUID.fromString(value);
} catch (IllegalArgumentException ignored) {
return null;
}
}
private static Identifier defaultSkin(String playerName) {
String cleanName = normalizeName(playerName);
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + cleanName).getBytes(StandardCharsets.UTF_8));
GameProfile profile = new GameProfile(uuid, cleanName);
PlayerSkin textures = DefaultPlayerSkin.get(profile);
Identifier resolved = PlayerSkinResolver.resolveAssetId(textures == null ? null : textures.body());
if (resolved != null) {
return resolved;
}
return Identifier.fromNamespaceAndPath("minecraft", "textures/entity/player/wide/steve.png");
}
private static String normalizeKey(String playerName) {
String cleanName = normalizeName(playerName);
return cleanName.isEmpty() ? "" : cleanName.toLowerCase();
}
private static String normalizeName(String playerName) {
return playerName == null ? "" : playerName.trim();
}
}

View file

@ -0,0 +1,63 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import java.util.List;
public interface ClientCommand {
default CommandMetadata metadata() {
return CommandMetadata.from(this);
}
/**
* Legacy addon API v0 metadata hook. New commands must use {@link CommandInfo}.
*/
@Deprecated(forRemoval = true)
default String name() {
return CommandMetadata.fromAnnotation(getClass()).id();
}
/**
* Legacy addon API v0 metadata hook. New commands must use {@link CommandInfo}.
*/
@Deprecated(forRemoval = true)
default List<String> aliases() {
CommandMetadata metadata = CommandMetadata.annotated(getClass());
return metadata == null ? List.of() : metadata.aliases();
}
/**
* Legacy addon API v0 metadata hook. New commands must use {@link CommandInfo}.
*/
@Deprecated(forRemoval = true)
@SuppressWarnings("removal")
default String usage() {
CommandMetadata metadata = CommandMetadata.annotated(getClass());
return metadata == null ? name() : metadata.usage();
}
/**
* Legacy addon API v0 metadata hook. New commands must use {@link CommandInfo}.
*/
@Deprecated(forRemoval = true)
@SuppressWarnings("removal")
default String description() {
CommandMetadata metadata = CommandMetadata.annotated(getClass());
return metadata == null ? usage() : metadata.description();
}
default boolean isAvailable() {
return true;
}
default List<String> suggest(CommandContext ctx, int argIndex, String token) {
return List.of();
}
boolean execute(CommandContext ctx);
}

View file

@ -0,0 +1,20 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import net.minecraft.client.Minecraft;
import java.util.List;
public record CommandContext(Minecraft mc, String raw, String name, List<String> args) {
public String arg(int idx) {
if (idx < 0 || idx >= args.size()) return null;
return args.get(idx);
}
}

View file

@ -0,0 +1,28 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import dev.loki.lovisual.events.UsedImplicitly;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@UsedImplicitly
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CommandInfo {
String id();
String[] aliases() default {};
String usage() default "";
String descriptionKey() default "";
}

View file

@ -0,0 +1,212 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import com.mojang.brigadier.context.StringRange;
import com.mojang.brigadier.suggestion.Suggestion;
import dev.loki.lovisual.util.logging.DebugLog;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
import net.minecraft.client.Minecraft;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public enum CommandManager {
;
private static final List<ClientCommand> COMMANDS = new ArrayList<>();
private static boolean initialized;
public static synchronized void init() {
if (initialized) return;
initialized = true;
discover("dev.loki.lovisual.features.command.impl");
}
public static List<ClientCommand> getCommands() {
if (!initialized) init();
return Collections.unmodifiableList(COMMANDS);
}
public static void register(ClientCommand cmd) {
if (cmd == null) return;
CommandMetadata metadata = cmd.metadata();
if (findRegistered(metadata.id()) != null) {
throw new IllegalArgumentException("Duplicate client command: @" + metadata.id());
}
for (String alias : metadata.aliases()) {
if (findRegistered(alias) != null) {
throw new IllegalArgumentException("Duplicate client command alias: @" + alias);
}
}
COMMANDS.add(cmd);
}
public static boolean handle(String raw) {
if (raw == null) return false;
String trimmed = raw.trim();
if (!isCommandLike(trimmed)) return false;
if (!initialized) init();
String body = trimmed.substring(1).trim();
if (body.isEmpty()) return false;
String[] parts = body.split("\\s+");
if (parts.length == 0) return false;
String name = parts[0].toLowerCase();
ClientCommand cmd = find(name);
if (cmd == null) {
CommandOutput.error("Unknown client command: @" + name + ". Use @help.");
return true;
}
if (!cmd.isAvailable()) {
return true; // silently ignore when command is disabled
}
List<String> args = new ArrayList<>();
args.addAll(Arrays.asList(parts).subList(1, parts.length));
CommandContext ctx = new CommandContext(Minecraft.getInstance(), raw, name, args);
return cmd.execute(ctx);
}
public static List<Suggestion> suggest(String input, int cursor) {
if (input == null) return List.of();
int start = firstNonWhitespace(input);
if (start < 0 || input.charAt(start) != '@') return List.of();
if (!initialized) init();
int cursorClamped = Math.max(start + 1, Math.min(cursor, input.length()));
String before = input.substring(start + 1, cursorClamped);
String[] parts = before.split("\\s+", -1);
if (parts.length == 0) return List.of();
int argIndex = parts.length - 1;
String token = parts[argIndex];
String cmdName = parts[0].toLowerCase();
int tokenStartInBefore = before.lastIndexOf(' ');
tokenStartInBefore = tokenStartInBefore >= 0 ? tokenStartInBefore + 1 : 0;
int tokenStartInInput = start + 1 + tokenStartInBefore;
int tokenEndInInput = tokenStartInInput + token.length();
StringRange range = StringRange.between(tokenStartInInput, tokenEndInInput);
List<String> suggestions;
if (argIndex == 0) {
suggestions = suggestCommandNames(token);
} else {
ClientCommand cmd = find(cmdName);
if (cmd == null || !cmd.isAvailable()) return List.of();
List<String> args = new ArrayList<>();
args.addAll(Arrays.asList(parts).subList(1, parts.length));
CommandContext ctx = new CommandContext(Minecraft.getInstance(), input, cmdName, args);
suggestions = cmd.suggest(ctx, argIndex, token);
}
if (suggestions == null || suggestions.isEmpty()) return List.of();
List<Suggestion> out = new ArrayList<>(suggestions.size());
for (String s : suggestions) {
if (s == null || s.isBlank()) continue;
out.add(new Suggestion(range, s));
}
return out;
}
public static ClientCommand find(String name) {
if (!initialized) init();
return findRegistered(name);
}
private static ClientCommand findRegistered(String name) {
if (name == null || name.isBlank()) return null;
for (ClientCommand cmd : COMMANDS) {
CommandMetadata metadata = cmd.metadata();
if (metadata.id().equalsIgnoreCase(name)) return cmd;
for (String alias : metadata.aliases()) {
if (alias.equalsIgnoreCase(name)) return cmd;
}
}
return null;
}
private static boolean isCommandLike(String text) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isWhitespace(c)) continue;
return c == '@';
}
return false;
}
private static List<String> suggestCommandNames(String token) {
String lower = token == null ? "" : token.toLowerCase();
List<String> out = new ArrayList<>();
for (ClientCommand cmd : COMMANDS) {
if (!cmd.isAvailable()) continue;
CommandMetadata metadata = cmd.metadata();
if (lower.isEmpty() || metadata.id().startsWith(lower)) {
out.add(metadata.id());
}
for (String alias : metadata.aliases()) {
if (alias == null || alias.isBlank()) continue;
if (lower.isEmpty() || alias.startsWith(lower)) {
out.add(alias);
}
}
}
return out;
}
private static int firstNonWhitespace(String text) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (!Character.isWhitespace(c)) return i;
}
return -1;
}
private static void discover(String basePackage) {
try (ScanResult scan = new ClassGraph()
.enableClassInfo()
.enableAnnotationInfo()
.acceptPackages(basePackage)
.scan()) {
scan.getClassesWithAnnotation(CommandInfo.class.getName()).stream()
.map(ClassInfo::getName)
.sorted(String.CASE_INSENSITIVE_ORDER)
.forEach(CommandManager::loadCandidate);
}
}
private static void loadCandidate(String className) {
try {
Class<?> type = Class.forName(className, false, CommandManager.class.getClassLoader());
if (!ClientCommand.class.isAssignableFrom(type)) {
DebugLog.config("Skipping annotated non-command: %s", type.getName());
return;
}
int modifiers = type.getModifiers();
if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers) || type.isAnnotation()) {
DebugLog.config("Skipping non-concrete command class: %s", type.getName());
return;
}
Constructor<?> constructor = type.getDeclaredConstructor();
constructor.setAccessible(true);
register((ClientCommand) constructor.newInstance());
DebugLog.config("Loaded command: %s", type.getName());
} catch (NoSuchMethodException exception) {
DebugLog.error("Failed to load command %s: no no-args constructor", exception, className);
} catch (Throwable throwable) {
DebugLog.error("Failed to load command: %s", throwable, className);
}
}
}

View file

@ -0,0 +1,124 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import net.minecraft.client.resources.language.I18n;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
public final class CommandMetadata {
private static final ClassValue<Optional<CommandMetadata>> ANNOTATED = new ClassValue<>() {
@Override
protected Optional<CommandMetadata> computeValue(Class<?> type) {
CommandInfo info = type.getAnnotation(CommandInfo.class);
return info == null ? Optional.empty() : Optional.of(from(info));
}
};
private final String id;
private final List<String> aliases;
private final String usage;
private final String description;
private final boolean localizedDescription;
private CommandMetadata(String id,
List<String> aliases,
String usage,
String description,
boolean localizedDescription) {
this.id = normalizeId(id);
this.aliases = normalizeAliases(aliases, this.id);
this.usage = usage == null || usage.isBlank() ? "@" + this.id : usage.trim();
if (description == null || description.isBlank()) {
this.description = this.usage;
this.localizedDescription = false;
} else {
this.description = description.trim();
this.localizedDescription = localizedDescription;
}
}
public String id() {
return id;
}
public List<String> aliases() {
return aliases;
}
public String usage() {
return usage;
}
public String description() {
return localizedDescription ? I18n.get(description) : description;
}
public String descriptionKey() {
return localizedDescription ? description : "";
}
public static CommandMetadata from(ClientCommand command) {
if (command == null) throw new IllegalArgumentException("command cannot be null");
CommandMetadata annotated = annotated(command.getClass());
if (annotated != null) return annotated;
return fromLegacy(command);
}
static CommandMetadata fromAnnotation(Class<?> type) {
CommandMetadata annotated = annotated(type);
if (annotated == null) {
throw new IllegalStateException(type.getName() + " must be annotated with @CommandInfo");
}
return annotated;
}
static CommandMetadata annotated(Class<?> type) {
return ANNOTATED.get(type).orElse(null);
}
private static CommandMetadata from(CommandInfo info) {
return new CommandMetadata(info.id(), List.of(info.aliases()), info.usage(), info.descriptionKey(), true);
}
@SuppressWarnings("removal")
private static CommandMetadata fromLegacy(ClientCommand command) {
String id = command.name();
List<String> aliases = command.aliases();
String usage = command.usage();
String description = command.description();
return new CommandMetadata(id, aliases, usage, description, false);
}
private static String normalizeId(String id) {
if (id == null || id.isBlank()) throw new IllegalArgumentException("Command id cannot be blank");
String normalized = id.trim().toLowerCase(Locale.ROOT);
if (normalized.charAt(0) == '@') normalized = normalized.substring(1);
if (normalized.isBlank() || normalized.chars().anyMatch(Character::isWhitespace)) {
throw new IllegalArgumentException("Invalid command id: " + id);
}
return normalized;
}
private static List<String> normalizeAliases(List<String> aliases, String id) {
if (aliases == null || aliases.isEmpty()) return List.of();
List<String> normalized = new ArrayList<>(aliases.size());
for (String alias : aliases) {
if (alias == null || alias.isBlank()) continue;
String value = alias.trim().toLowerCase(Locale.ROOT);
if (value.charAt(0) == '@') value = value.substring(1);
if (value.isBlank() || value.chars().anyMatch(Character::isWhitespace) || value.equals(id)) continue;
if (!normalized.contains(value)) normalized.add(value);
}
return List.copyOf(normalized);
}
}

View file

@ -0,0 +1,195 @@
/*
* This file is part of the LoVisual Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import dev.loki.lovisual.features.theme.Theme;
import dev.loki.lovisual.features.theme.Themes;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
public enum CommandOutput {
;
public static final String PREFIX = "[LoVisual]";
private static final int MAX_RECENT_MESSAGES = 128;
private static final Map<Component, Tone> LOVISUAL_MESSAGES =
Collections.synchronizedMap(new WeakHashMap<>());
private static final Deque<MessageLine> RECENT_MESSAGES = new ArrayDeque<>();
public record MessageLine(Component text, long timestampMs, Tone tone) {
}
public enum Tone {
INFO,
SUCCESS,
WARNING,
ERROR
}
public static void send(String message) {
send(message, Tone.INFO);
}
public static void success(String message) {
send(message, Tone.SUCCESS);
}
public static void warning(String message) {
send(message, Tone.WARNING);
}
public static void error(String message) {
send(message, Tone.ERROR);
}
public static void send(String message, Tone tone) {
if (message == null || message.isBlank()) return;
send(Component.literal(message), tone == null ? Tone.INFO : tone);
}
public static void send(Component text) {
send(text, Tone.INFO);
}
public static void send(Component text, Tone tone) {
if (text == null) return;
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null || mc.gui.hud == null) return;
Tone resolvedTone = tone == null ? Tone.INFO : tone;
Component formatted = mark(format(text, resolvedTone), resolvedTone);
remember(formatted, resolvedTone);
mc.gui.hud.getChat().addClientSystemMessage(formatted);
}
public static boolean isLoVisualMessage(Component text) {
if (text == null) return false;
synchronized (LOVISUAL_MESSAGES) {
return LOVISUAL_MESSAGES.containsKey(text);
}
}
public static Tone toneOf(Component text) {
if (text == null) return Tone.INFO;
synchronized (LOVISUAL_MESSAGES) {
Tone tone = LOVISUAL_MESSAGES.get(text);
return tone == null ? Tone.INFO : tone;
}
}
public static List<MessageLine> recentMessages() {
synchronized (RECENT_MESSAGES) {
return new ArrayList<>(RECENT_MESSAGES);
}
}
public static void clearRecentMessages() {
synchronized (RECENT_MESSAGES) {
RECENT_MESSAGES.clear();
}
}
private static void remember(Component text, Tone tone) {
synchronized (RECENT_MESSAGES) {
RECENT_MESSAGES.addLast(new MessageLine(text, System.currentTimeMillis(), tone));
while (RECENT_MESSAGES.size() > MAX_RECENT_MESSAGES) {
RECENT_MESSAGES.removeFirst();
}
}
}
private static Component mark(Component text, Tone tone) {
synchronized (LOVISUAL_MESSAGES) {
LOVISUAL_MESSAGES.put(text, tone == null ? Tone.INFO : tone);
}
return text;
}
private static MutableComponent format(Component body, Tone tone) {
MutableComponent out = Component.empty();
appendGradientPrefix(out, tone);
out.append(Component.literal(" "));
out.append(copyBody(body, bodyColor(tone)).withStyle(style -> style.withBold(false)));
return out;
}
private static MutableComponent copyBody(Component body, int color) {
MutableComponent copy = body.copy();
return copy.withStyle(style -> style.withColor(color & 0x00FFFFFF));
}
private static void appendGradientPrefix(MutableComponent out, Tone tone) {
String prefix = PREFIX;
int start = prefixStartColor(tone);
int end = prefixEndColor(tone);
int steps = Math.max(1, prefix.length() - 1);
for (int i = 0; i < prefix.length(); i++) {
final int color = mixRgb(start, end, i / (float) steps) & 0x00FFFFFF;
out.append(Component.literal(String.valueOf(prefix.charAt(i)))
.withStyle(style -> style.withColor(color).withBold(true)));
}
}
public static int prefixStartColor(Tone tone) {
Themes.Theme theme = Theme.theme();
int accent = theme.accent();
return switch (tone) {
case SUCCESS -> mixRgb(accent, 0xFF55FF93, 0.45f);
case WARNING -> mixRgb(accent, 0xFFFFC85A, 0.45f);
case ERROR -> mixRgb(accent, 0xFFFF6A6A, 0.55f);
default -> accent;
};
}
public static int prefixEndColor(Tone tone) {
Themes.Theme theme = Theme.theme();
int text = theme.textPrimary();
int accentSoft = theme.accentSoft();
return switch (tone) {
case SUCCESS -> mixRgb(text, 0xFF55FF93, 0.28f);
case WARNING -> mixRgb(text, 0xFFFFD985, 0.32f);
case ERROR -> mixRgb(text, 0xFFFF8A8A, 0.42f);
default -> mixRgb(text, accentSoft, 0.35f);
};
}
public static int bodyColor(Tone tone) {
Themes.Theme theme = Theme.theme();
int base = mixRgb(theme.textPrimary(), 0xFFFFFFFF, 0.24f);
return switch (tone) {
case SUCCESS -> mixRgb(base, 0xFFBFFFE0, 0.18f);
case WARNING -> mixRgb(base, 0xFFFFE5A8, 0.18f);
case ERROR -> mixRgb(base, 0xFFFFB0B0, 0.25f);
default -> base;
};
}
public static int mixRgb(int a, int b, float t) {
t = Math.max(0.0f, Math.min(1.0f, t));
int ar = (a >> 16) & 0xFF;
int ag = (a >> 8) & 0xFF;
int ab = a & 0xFF;
int br = (b >> 16) & 0xFF;
int bg = (b >> 8) & 0xFF;
int bb = b & 0xFF;
int r = Math.round(ar + (br - ar) * t);
int g = Math.round(ag + (bg - ag) * t);
int bl = Math.round(ab + (bb - ab) * t);
return 0xFF000000 | (r << 16) | (g << 8) | bl;
}
}

View file

@ -0,0 +1,25 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.ChatComponent;
public enum VanillaChatRuntimeCleanup {
;
public static void clearVanillaChatCache() {
Minecraft mc = Minecraft.getInstance();
if (mc == null || mc.gui == null || mc.gui.hud == null) return;
ChatComponent chat = mc.gui.hud.getChat();
if (chat != null) {
chat.clearMessages(true);
}
CommandOutput.clearRecentMessages();
}
}

View file

@ -0,0 +1,98 @@
/*
* This file is part of the Combatant Client distribution.
* Copyright (c) 2026 pivosos2007.
*
* Licensed under the GNU General Public License v3.0.
*/
package dev.loki.lovisual.features.command.impl;
import dev.loki.lovisual.addon.AddonIssue;
import dev.loki.lovisual.addon.AddonManager;
import dev.loki.lovisual.addon.AddonSnapshot;
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 java.util.List;
import java.util.Locale;
@CommandInfo(
id = "addons",
usage = "@addons [list|scan|enable|disable] [id]",
descriptionKey = "command.addons.description"
)
public final class AddonsCommand implements ClientCommand {
@Override
public List<String> suggest(CommandContext ctx, int argIndex, String token) {
String lower = token == null ? "" : token.toLowerCase(Locale.ROOT);
if (argIndex == 1) {
return List.of("list", "scan", "enable", "disable").stream()
.filter(value -> value.startsWith(lower))
.toList();
}
if (argIndex == 2) {
return AddonManager.snapshots().stream()
.map(AddonSnapshot::id)
.filter(id -> lower.isEmpty() || id.startsWith(lower))
.toList();
}
return List.of();
}
@Override
public boolean execute(CommandContext ctx) {
String action = ctx.arg(0);
if (action == null || action.isBlank() || "list".equalsIgnoreCase(action)) {
list();
return true;
}
if ("scan".equalsIgnoreCase(action)) {
scan();
return true;
}
if ("enable".equalsIgnoreCase(action) || "disable".equalsIgnoreCase(action)) {
String id = ctx.arg(1);
if (id == null || id.isBlank()) {
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
boolean enabled = "enable".equalsIgnoreCase(action);
boolean ok = AddonManager.setEnabled(id, enabled);
CommandOutput.send(ok
? "Addon " + id + " " + (enabled ? "enabled" : "disabled")
: "Addon not found: " + id);
return true;
}
CommandOutput.send("Usage: " + metadata().usage());
return true;
}
private static void list() {
List<AddonSnapshot> addons = AddonManager.snapshots();
if (addons.isEmpty()) {
CommandOutput.send("No LoVisual addons installed.");
return;
}
for (AddonSnapshot addon : addons) {
CommandOutput.send(addon.id() + " " + addon.version()
+ " [" + addon.status().name().toLowerCase(Locale.ROOT) + "]"
+ " modules=" + addon.modules()
+ " hud=" + (addon.draggableHudElements() + addon.staticHudElements())
+ " commands=" + addon.commands()
+ " clickGui=" + addon.clickGuiSections()
+ " extensions=" + addon.moduleExtensions()
+ " irisPatches=" + addon.irisPatchManifests()
+ (addon.restartRequired() ? " restart-required" : ""));
}
}
private static void scan() {
for (AddonIssue issue : AddonManager.scan()) {
CommandOutput.send("Addon scan " + issue.severity().name().toLowerCase(Locale.ROOT)
+ " [" + issue.addonId() + "]: " + issue.message()
+ (issue.detail() == null || issue.detail().isBlank() ? "" : " (" + issue.detail() + ")"));
}
}
}

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