chore(history): squash 59 commit(s) from 2026-09-23
- refactor(hud/weather/render): Scoreboard 931→240 + Rain 903→159 + UiMeshGeometry 956→99 (8.5.2) - refactor(chams): Chams 985 → 129 + 4×≤195 (8.5.2) - refactor(module): Module 1031 → 139 + 4×≤134 (8.5.2) - refactor(tooltips): BetterTooltips 960 → 181 + 4×≤199 (8.5.2) - refactor(clickgui): ClickGuiPickerState 970→166 + ModulesMenuScreen 966→145 (8.5.2) - refactor(clickgui): CombatProtocolHeuristicsEditorState 932→79 + 4×≤192 (8.5.2) - refactor(hud): CompactHudStatModel 894 → 125 + 4×≤175 (8.5.2) - refactor(iris): ShaderPatchCompiler 843→66 + 4×≤174 (8.5.2) - refactor(tab): CustomTabList 834→136 + 4×≤166 (8.5.2) - refactor(relations): OnlineRelationPlayerPickerComponent 837→74 + 4×≤192 (8.5.2) - refactor(hits): HitEffect 770→120 + 4×≤176 (8.5.2) - refactor(predict): Predictions 815→150 + 4×≤195 (8.5.2) - refactor(config): ConfigProfilesComponent 799→125 + 4×≤195 (8.5.2) - refactor(sim): PlayerMovementSimulation 757→157 + 4×≤194 (8.5.2) - refactor(predict): ProjectilePuncher 747→104 + 3×≤134 (8.5.2) - refactor(crosshair): Crosshair 743→143 + 4×≤167 (8.5.2) - refactor(mediaplayer): MediaPlayer 743→174 + 4×≤196 (8.5.2) - refactor(hud): Itemizer 699→193 + Cooldowns 707→151 (8.5.2) - refactor(hud): Potions 617→176 + 4×≤166 (8.5.2) - refactor(hud): Admins 702→118 + 4×≤138 (8.5.2) - refactor(hud): Keybinds 611→157 + 4×≤160 (8.5.2) - refactor(hud): ModuleList 499→181 + 3×≤150 (8.5.2) - refactor(hud): Radar 392→161 + 2×≤124 (8.5.2) - refactor(hud): Fps 309→168 + 3×≤107 (8.5.2) - refactor(hud): Memory 304→151 + 3×≤144 (8.5.2) - refactor(hud): Tps 339→154 + 3×≤143 (8.5.2) - refactor(hud): Ping 309→145 + 3×≤125 (8.5.2) - refactor(hud): SpeedBps 334→156 + 3×≤142 (8.5.2) - refactor(hud): GameTime 314→150 + 3×≤127 (8.5.2) - refactor(hud): SystemTime 300→136 + 3×≤130 (8.5.2) - refactor(hud): Coordinates 337→174 + 2×≤172 (8.5.2) - refactor(hud): Armor 324→162 + 2×≤148 (8.5.2) - refactor(hud): Inventory 476→153 + 3×≤181 (8.5.2) - docs(todo): обновлён 8.5.2 — отмечены готовые гиганты (BetterButtons/InventorySwap/Svg/Темы/WorldParticles/Module/Chams и хвост) - docs(api): папка combatant-client-26.2/docs + addons.md (API можно ломать при рефакторе) - refactor(visuals): BlockHighlight 692→271 + 4×≤200 (8.5.2) - refactor(mixins): GameRendererMixin 830→344 (хуки) + 4 хелпера (8.5.2) - refactor(visuals): WorldParticles 821→260 + 6×≤200, режимы добиты (8.5.2) - docs(todo): 8.5.2 — WorldParticles/GameRendererMixin/BlockHighlight отмечены ГОТОВО - refactor(render): MeshBuilder 738→447 (фасад write-API) + 3 хелпера, FrameStats снесён (8.5.2) - docs(todo): Фаза 10 — дизайн платформы (аккаунты/конфиги/аватарки), backlog RPC-чата - docs(todo): Подсистема 3 — Аддоны 2.0 (скрипты/версии) + витрина аддонов + админка - docs(todo): Подсистема 2 — RPC-чат/друзья/виджеты-телеметрия + рейт-лимиты, доп. правки Подсистемы 3 - chore: переименование combatant-client-26.2 -> mod, добавлены backend/ и frontend/ - docs(backend): implementation plan for accounts-service (Подсистема 1, часть 1) - chore: пересоздать backend/frontend через cargo new и bun create vite + tailwind; убрать таблицу компонентов из TODO.md - docs(backend): edition 2024 в плане вместо 2021 - chore: обновить версии до реально актуальных (проверено компиляцией) - docs: правила платформы (лимит 250 строк, антипаттерны backend/frontend по итогам ресёрча) + frontend/ARCHITECTURE.md - docs: добавить правило ≤4 файла на папку в правила платформы (backend/frontend) - docs: commit messages in English from now on - chore: gitignore .superpowers/ scratch directory - docs: commit messages in English from now on (mod) - feat(backend): scaffold accounts-service with health check - chore(backend): remove target/ build artifacts from git, add gitignore - chore: track docs/ in git (was accidentally gitignored, never committed) - chore(backend): convert to Cargo workspace, plan full microservice layout - feat(backend): accounts/avatars/device_links schema + migration - feat(backend): argon2id password hashing
This commit is contained in:
parent
ec10395511
commit
9d08fa910a
2239 changed files with 35265 additions and 28110 deletions
|
|
@ -0,0 +1,301 @@
|
|||
/*
|
||||
* This file is part of the LoVisual Client distribution.
|
||||
* Copyright (c) 2026 loki5512344.
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0.
|
||||
*/
|
||||
|
||||
package dev.loki.lovisual.features.command.impl;
|
||||
|
||||
import dev.loki.lovisual.features.command.ClientCommand;
|
||||
import dev.loki.lovisual.features.command.CommandContext;
|
||||
import dev.loki.lovisual.features.command.CommandInfo;
|
||||
import dev.loki.lovisual.features.command.CommandOutput;
|
||||
import dev.loki.lovisual.render.engine.profiler.FrameStutterProfiler;
|
||||
import dev.loki.lovisual.render.engine.profiler.JfrProfiler;
|
||||
import dev.loki.lovisual.render.engine.profiler.ProfilerSettings;
|
||||
import dev.loki.lovisual.render.engine.profiler.TracyProfiler;
|
||||
import dev.loki.lovisual.Lifecycle;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@CommandInfo(
|
||||
id = "profiler",
|
||||
aliases = "prof",
|
||||
usage = "@profiler [2d|3d|all|sample|stutter|tracy|jfr] ...",
|
||||
descriptionKey = "command.profiler.description"
|
||||
)
|
||||
public final class ProfilerCommand implements ClientCommand {
|
||||
|
||||
@Override
|
||||
public boolean isAvailable() {
|
||||
return Lifecycle.isActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean execute(CommandContext ctx) {
|
||||
if (!Lifecycle.isActive()) {
|
||||
CommandOutput.send("Profiler: disabled until client is active.");
|
||||
return true;
|
||||
}
|
||||
String target = ctx.arg(0);
|
||||
if (target == null
|
||||
|| !(target.equalsIgnoreCase("2d")
|
||||
|| target.equalsIgnoreCase("3d")
|
||||
|| target.equalsIgnoreCase("all")
|
||||
|| target.equalsIgnoreCase("sample")
|
||||
|| target.equalsIgnoreCase("stutter")
|
||||
|| target.equalsIgnoreCase("tracy")
|
||||
|| target.equalsIgnoreCase("jfr"))) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
|
||||
String mode = ctx.arg(1);
|
||||
String targetArg = ctx.arg(2);
|
||||
String detailArg = ctx.arg(3);
|
||||
if (target.equalsIgnoreCase("jfr")) {
|
||||
return executeJfr(mode, targetArg);
|
||||
}
|
||||
if (target.equalsIgnoreCase("stutter")) {
|
||||
return executeStutter(mode, targetArg, detailArg);
|
||||
}
|
||||
if (target.equalsIgnoreCase("tracy")) {
|
||||
boolean enable = mode == null || mode.equalsIgnoreCase("on");
|
||||
if (mode != null && !mode.equalsIgnoreCase("on") && !mode.equalsIgnoreCase("off")) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
boolean active = TracyProfiler.setEnabled(enable);
|
||||
if (!enable) {
|
||||
CommandOutput.send("Profiler tracy: off");
|
||||
} else if (active) {
|
||||
CommandOutput.send("Profiler tracy: on (streams to external Tracy viewer, not latest.log)");
|
||||
} else {
|
||||
CommandOutput.send("Profiler tracy: unavailable");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (mode == null) {
|
||||
mode = "chat";
|
||||
}
|
||||
|
||||
ProfilerSettings.OutputMode modeOutput = ProfilerSettings.parseOutput(mode);
|
||||
ProfilerSettings.SampleTarget modeTarget = ProfilerSettings.parseTarget(mode);
|
||||
ProfilerSettings.SampleTarget targetTarget = ProfilerSettings.parseTarget(targetArg);
|
||||
ProfilerSettings.OutputMode targetOutput = ProfilerSettings.parseOutput(targetArg);
|
||||
Boolean detailMode = parseDetailMode(detailArg);
|
||||
|
||||
boolean modeIsOutput = modeOutput != null;
|
||||
boolean modeIsTarget = modeTarget != null;
|
||||
|
||||
if (!modeIsOutput && !modeIsTarget) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
|
||||
String t = target.toLowerCase();
|
||||
if (!t.equals("sample") && !modeIsOutput) {
|
||||
CommandOutput.send("Usage: " + metadata().usage());
|
||||
return true;
|
||||
}
|
||||
if (t.equals("2d")) {
|
||||
ProfilerSettings.setOutput2d(modeOutput);
|
||||
} else if (t.equals("3d")) {
|
||||
ProfilerSettings.setOutput3d(modeOutput);
|
||||
} else if (t.equals("sample")) {
|
||||
if (modeIsTarget) {
|
||||
ProfilerSettings.setSampleTarget(modeTarget);
|
||||
if (targetOutput != null) {
|
||||
ProfilerSettings.setSampleOutput(targetOutput);
|
||||
modeOutput = targetOutput;
|
||||
} else {
|
||||
ProfilerSettings.setSampleOutput(ProfilerSettings.OutputMode.CHAT);
|
||||
modeOutput = ProfilerSettings.OutputMode.CHAT;
|
||||
}
|
||||
} else {
|
||||
ProfilerSettings.setSampleOutput(modeOutput);
|
||||
}
|
||||
if (targetTarget != null) {
|
||||
ProfilerSettings.setSampleTarget(targetTarget);
|
||||
}
|
||||
if (detailMode != null) {
|
||||
ProfilerSettings.setSampleDetailedStacks(detailMode);
|
||||
}
|
||||
} else {
|
||||
ProfilerSettings.setOutput2d(modeOutput);
|
||||
ProfilerSettings.setOutput3d(modeOutput);
|
||||
}
|
||||
if (t.equals("sample")) {
|
||||
CommandOutput.send("Profiler sample output: " + modeOutput.name().toLowerCase()
|
||||
+ " (target " + ProfilerSettings.formatTarget(ProfilerSettings.getSampleTarget())
|
||||
+ ", stacks " + (ProfilerSettings.isSampleDetailedStacks() ? "on" : "off") + ")");
|
||||
} else {
|
||||
CommandOutput.send("Profiler " + t + " output: " + modeOutput.name().toLowerCase());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> suggest(CommandContext ctx, int argIndex, String token) {
|
||||
if (argIndex == 1) {
|
||||
return matchToken(token, List.of("2d", "3d", "all", "sample", "stutter", "tracy", "jfr"));
|
||||
}
|
||||
if (argIndex == 2) {
|
||||
String t = ctx.arg(0);
|
||||
if (t != null && (t.equalsIgnoreCase("sample") || t.equalsIgnoreCase("stutter"))) {
|
||||
return matchToken(token, List.of("off", "log", "chat", "2d", "3d", "all"));
|
||||
}
|
||||
if (t != null && t.equalsIgnoreCase("tracy")) {
|
||||
return matchToken(token, List.of("on", "off"));
|
||||
}
|
||||
if (t != null && t.equalsIgnoreCase("jfr")) {
|
||||
return matchToken(token, List.of("start", "stop", "dump", "status"));
|
||||
}
|
||||
return matchToken(token, List.of("off", "log", "chat"));
|
||||
}
|
||||
if (argIndex == 3) {
|
||||
String t = ctx.arg(0);
|
||||
if (t != null && t.equalsIgnoreCase("sample")) {
|
||||
return matchToken(token, List.of("2d", "3d", "all"));
|
||||
}
|
||||
if (t != null && t.equalsIgnoreCase("jfr")) {
|
||||
String action = ctx.arg(1);
|
||||
if (action == null || action.equalsIgnoreCase("start")) {
|
||||
return matchToken(token, List.of("gc", "alloc", "full"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (argIndex == 4) {
|
||||
String t = ctx.arg(0);
|
||||
if (t != null && t.equalsIgnoreCase("sample")) {
|
||||
return matchToken(token, List.of("stacks", "nostacks"));
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private boolean executeStutter(String mode, String thresholdArg, String sampleArg) {
|
||||
if (mode == null || mode.equalsIgnoreCase("status")) {
|
||||
CommandOutput.send(FrameStutterProfiler.statusLine());
|
||||
return true;
|
||||
}
|
||||
ProfilerSettings.OutputMode output = ProfilerSettings.parseOutput(mode);
|
||||
if (output == null) {
|
||||
CommandOutput.send("Profiler stutter usage: @profiler stutter [off|log|chat|status] [thresholdMs] [sampleMs]");
|
||||
return true;
|
||||
}
|
||||
double thresholdMs = parseDouble(thresholdArg, 35.0);
|
||||
double sampleMs = parseDouble(sampleArg, 2.0);
|
||||
FrameStutterProfiler.configure(output, thresholdMs, sampleMs);
|
||||
CommandOutput.send(FrameStutterProfiler.statusLine());
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean executeJfr(String action, String presetArg) {
|
||||
if (action == null || action.equalsIgnoreCase("status")) {
|
||||
CommandOutput.send(JfrProfiler.statusLine());
|
||||
return true;
|
||||
}
|
||||
if (action.equalsIgnoreCase("start")) {
|
||||
JfrProfiler.Preset preset = JfrProfiler.Preset.parse(presetArg);
|
||||
if (preset == null) {
|
||||
CommandOutput.send("Profiler JFR usage: @profiler jfr start [gc|alloc|full]");
|
||||
return true;
|
||||
}
|
||||
JfrProfiler.StartResult result = JfrProfiler.start(preset);
|
||||
if (result.started()) {
|
||||
CommandOutput.send("Profiler JFR: started " + preset.getId() + " -> " + absolute(result.path()));
|
||||
return true;
|
||||
}
|
||||
if (result.alreadyRunning()) {
|
||||
CommandOutput.send("Profiler JFR: already running ("
|
||||
+ result.preset().getId() + ", file " + absolute(result.path()) + ")");
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR: unavailable"
|
||||
+ (result.error() == null ? "" : " (" + result.error() + ")"));
|
||||
return true;
|
||||
}
|
||||
if (action.equalsIgnoreCase("dump")) {
|
||||
JfrProfiler.DumpResult result = JfrProfiler.dumpSnapshot();
|
||||
if (result.dumped()) {
|
||||
CommandOutput.send("Profiler JFR: snapshot -> " + absolute(result.path()));
|
||||
return true;
|
||||
}
|
||||
if (result.notRunning()) {
|
||||
CommandOutput.send("Profiler JFR: not running");
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR: snapshot failed"
|
||||
+ (result.error() == null ? "" : " (" + result.error() + ")"));
|
||||
return true;
|
||||
}
|
||||
if (action.equalsIgnoreCase("stop")) {
|
||||
JfrProfiler.StopResult result = JfrProfiler.stop();
|
||||
if (result.stopped()) {
|
||||
long seconds = result.startedAt() == null
|
||||
? 0L
|
||||
: Math.max(0L, Duration.between(result.startedAt(), Instant.now()).toSeconds());
|
||||
CommandOutput.send("Profiler JFR: saved " + result.preset().getId()
|
||||
+ " (" + formatDuration(seconds) + ") -> " + absolute(result.path()));
|
||||
return true;
|
||||
}
|
||||
if (result.notRunning()) {
|
||||
CommandOutput.send("Profiler JFR: not running");
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR: stop failed"
|
||||
+ (result.error() == null ? "" : " (" + result.error() + ")"));
|
||||
return true;
|
||||
}
|
||||
CommandOutput.send("Profiler JFR usage: @profiler jfr [start|stop|dump|status] [gc|alloc|full]");
|
||||
return true;
|
||||
}
|
||||
|
||||
private Boolean parseDetailMode(String raw) {
|
||||
if (raw == null) return null;
|
||||
return switch (raw.toLowerCase()) {
|
||||
case "stacks", "stack", "detail", "detailed" -> Boolean.TRUE;
|
||||
case "nostacks", "nostack", "basic", "light" -> Boolean.FALSE;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private double parseDouble(String raw, double fallback) {
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
try {
|
||||
double value = Double.parseDouble(raw.trim());
|
||||
return Double.isFinite(value) ? value : fallback;
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> matchToken(String token, List<String> options) {
|
||||
String lower = token == null ? "" : token.toLowerCase();
|
||||
List<String> out = new java.util.ArrayList<>();
|
||||
for (String opt : options) {
|
||||
if (lower.isEmpty() || opt.startsWith(lower)) {
|
||||
out.add(opt);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private String absolute(Path path) {
|
||||
return path == null ? "<unknown>" : path.toAbsolutePath().toString();
|
||||
}
|
||||
|
||||
private String formatDuration(long totalSeconds) {
|
||||
long minutes = totalSeconds / 60L;
|
||||
long seconds = totalSeconds % 60L;
|
||||
if (minutes <= 0L) {
|
||||
return seconds + "s";
|
||||
}
|
||||
return minutes + "m " + seconds + "s";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package dev.loki.lovisual.mixins;
|
||||
|
||||
import net.minecraft.util.profiling.InactiveProfiler;
|
||||
import net.minecraft.util.profiling.Profiler;
|
||||
import net.minecraft.util.profiling.ProfilerFiller;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
import dev.loki.lovisual.render.engine.profiler.DevTracyProfiler;
|
||||
|
||||
@Mixin(Profiler.class)
|
||||
public abstract class ProfilersMixin {
|
||||
|
||||
@Inject(method = "getDefaultFiller", at = @At("HEAD"), cancellable = true)
|
||||
private static void lovisual$limitVanillaTracyToRenderThread(CallbackInfoReturnable<ProfilerFiller> cir) {
|
||||
if (!DevTracyProfiler.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (DevTracyProfiler.shouldTraceCurrentThread()) {
|
||||
return;
|
||||
}
|
||||
cir.setReturnValue(InactiveProfiler.INSTANCE);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,494 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import com.sun.management.GarbageCollectionNotificationInfo;
|
||||
import com.sun.management.GcInfo;
|
||||
import dev.loki.lovisual.util.screen.ClientScreen;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
|
||||
import javax.management.Notification;
|
||||
import javax.management.NotificationEmitter;
|
||||
import javax.management.openmbean.CompositeData;
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryUsage;
|
||||
import java.util.*;
|
||||
|
||||
public enum DevFrameStutterProfiler {
|
||||
;
|
||||
private static final long DEFAULT_THRESHOLD_NS = 35_000_000L;
|
||||
private static final long DEFAULT_SAMPLE_INTERVAL_NS = 2_000_000L;
|
||||
private static final long GC_CORRELATION_WINDOW_NS = 75_000_000L;
|
||||
private static final int MAX_STACK_FRAMES = 6;
|
||||
private static final int MAX_SAMPLES = 2048;
|
||||
private static final int MAX_GC_EVENTS = 64;
|
||||
private static final int TOP_STACKS = 8;
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static final Sample[] SAMPLES = new Sample[MAX_SAMPLES];
|
||||
private static final GcEvent[] GC_EVENTS = new GcEvent[MAX_GC_EVENTS];
|
||||
|
||||
private static volatile ProfilerSettings.OutputMode output = ProfilerSettings.OutputMode.OFF;
|
||||
private static volatile long thresholdNs = DEFAULT_THRESHOLD_NS;
|
||||
private static volatile long sampleIntervalNs = DEFAULT_SAMPLE_INTERVAL_NS;
|
||||
private static volatile Thread renderThread;
|
||||
private static volatile Thread samplerThread;
|
||||
private static volatile boolean running;
|
||||
private static volatile boolean gcListenerInstalled;
|
||||
|
||||
private static int sampleCursor;
|
||||
private static int sampleCount;
|
||||
private static int gcCursor;
|
||||
private static int gcCount;
|
||||
private static long lastPresentedNs;
|
||||
private static long lastLoggedNs;
|
||||
|
||||
public static void configure(ProfilerSettings.OutputMode mode, double thresholdMs, double sampleMs) {
|
||||
output = mode == null ? ProfilerSettings.OutputMode.OFF : mode;
|
||||
thresholdNs = clampMs(thresholdMs, 1.0, 5000.0, DEFAULT_THRESHOLD_NS);
|
||||
sampleIntervalNs = clampMs(sampleMs, 1.0, 100.0, DEFAULT_SAMPLE_INTERVAL_NS);
|
||||
if (output == ProfilerSettings.OutputMode.OFF) {
|
||||
stopSampler();
|
||||
synchronized (LOCK) {
|
||||
sampleCursor = 0;
|
||||
sampleCount = 0;
|
||||
lastPresentedNs = 0L;
|
||||
lastLoggedNs = 0L;
|
||||
}
|
||||
return;
|
||||
}
|
||||
installGcListener();
|
||||
ensureSampler();
|
||||
}
|
||||
|
||||
public static String statusLine() {
|
||||
if (output == ProfilerSettings.OutputMode.OFF) {
|
||||
return "Profiler stutter: off";
|
||||
}
|
||||
return String.format(Locale.ROOT,
|
||||
"Profiler stutter: %s (threshold %.1f ms, sample %.1f ms)",
|
||||
output.name().toLowerCase(Locale.ROOT),
|
||||
thresholdNs / 1_000_000.0,
|
||||
sampleIntervalNs / 1_000_000.0);
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return output != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static void onFramePresented(RhiStatsSnapshot rhi,
|
||||
UniformAllocatorStatsSnapshot uniforms,
|
||||
RenderResourceStatsSnapshot resources) {
|
||||
try {
|
||||
if (!isEnabled()) return;
|
||||
|
||||
renderThread = Thread.currentThread();
|
||||
ensureSampler();
|
||||
|
||||
long now = System.nanoTime();
|
||||
long previous;
|
||||
synchronized (LOCK) {
|
||||
previous = lastPresentedNs;
|
||||
lastPresentedNs = now;
|
||||
}
|
||||
if (previous == 0L) return;
|
||||
|
||||
long elapsedNs = now - previous;
|
||||
if (elapsedNs < thresholdNs) return;
|
||||
if (now - lastLoggedNs < thresholdNs) return;
|
||||
lastLoggedNs = now;
|
||||
|
||||
List<String> lines = buildReport(previous, now, elapsedNs, rhi, uniforms, resources);
|
||||
emit(lines);
|
||||
} catch (Throwable t) {
|
||||
ProfilerLog.warn("[FrameStutter] disabled after profiler failure: %s",
|
||||
t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
configure(ProfilerSettings.OutputMode.OFF, 0.0, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> buildReport(long frameStartNs,
|
||||
long frameEndNs,
|
||||
long elapsedNs,
|
||||
RhiStatsSnapshot rhi,
|
||||
UniformAllocatorStatsSnapshot uniforms,
|
||||
RenderResourceStatsSnapshot resources) {
|
||||
List<Sample> samples = samplesInWindow(frameStartNs, frameEndNs);
|
||||
List<GcEvent> gcEvents = gcNearWindow(frameStartNs, frameEndNs);
|
||||
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
String screen = mc == null || ClientScreen.current() == null ? "none" : ClientScreen.current().getClass().getSimpleName();
|
||||
String world = mc == null || mc.level == null ? "none" : mc.level.dimension().identifier().toString();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] frame %.2f ms over %.2f ms, samples %d, screen=%s, world=%s",
|
||||
elapsedNs / 1_000_000.0,
|
||||
thresholdNs / 1_000_000.0,
|
||||
samples.size(),
|
||||
screen,
|
||||
world));
|
||||
|
||||
if (rhi != null) {
|
||||
long uploaded = rhi.uploadedVertexBytes() + rhi.uploadedIndexBytes();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] rhi draw=%d fs=%d meshUpload=%d/%s copies=%d/%d ringWrap=%d stall=%d fallback=%d backlog=%d",
|
||||
rhi.drawCalls(),
|
||||
rhi.fullscreenPasses(),
|
||||
rhi.meshUploads(),
|
||||
formatBytes(uploaded),
|
||||
rhi.textureFastCopies(),
|
||||
rhi.textureShaderCopies(),
|
||||
rhi.ringWraps(),
|
||||
rhi.ringStalls(),
|
||||
rhi.immediateFallbackUploads(),
|
||||
rhi.dynamicArenaBacklogEvents()));
|
||||
}
|
||||
if (uniforms != null || resources != null) {
|
||||
long uniformWrites = uniforms == null ? 0L : uniforms.writes();
|
||||
long uniformBytes = uniforms == null ? 0L : uniforms.uploadedBytes();
|
||||
int retireBacklog = resources == null ? 0 : resources.retirementBacklog();
|
||||
int leaks = resources == null ? 0 : resources.leakedResources();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] uniforms writes=%d/%s resourceBacklog=%d leaks=%d",
|
||||
uniformWrites,
|
||||
formatBytes(uniformBytes),
|
||||
retireBacklog,
|
||||
leaks));
|
||||
}
|
||||
|
||||
if (gcEvents.isEmpty()) {
|
||||
lines.add("[FrameStutter] gc nearby: none");
|
||||
} else {
|
||||
for (GcEvent gc : gcEvents) {
|
||||
double relativeEndMs = (gc.endNs - frameStartNs) / 1_000_000.0;
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] gc nearby: %s %s %.2f ms at %+,.2f ms, freed %s",
|
||||
gc.name,
|
||||
gc.cause,
|
||||
(double) gc.durationMs,
|
||||
relativeEndMs,
|
||||
formatBytes(gc.freedBytes)));
|
||||
}
|
||||
}
|
||||
|
||||
appendSampleSummary(lines, samples);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void appendSampleSummary(List<String> lines, List<Sample> samples) {
|
||||
if (samples.isEmpty()) {
|
||||
lines.add("[FrameStutter] sample top: none");
|
||||
return;
|
||||
}
|
||||
Map<String, Integer> counts = new HashMap<>();
|
||||
int glWait = 0;
|
||||
int glUpload = 0;
|
||||
int glDraw = 0;
|
||||
int glState = 0;
|
||||
for (Sample sample : samples) {
|
||||
counts.merge(sample.stack, 1, Integer::sum);
|
||||
if (sample.stack.startsWith("GL WAIT:")) {
|
||||
glWait++;
|
||||
} else if (sample.stack.startsWith("GL UPLOAD:")) {
|
||||
glUpload++;
|
||||
} else if (sample.stack.startsWith("GL DRAW:")) {
|
||||
glDraw++;
|
||||
} else if (sample.stack.startsWith("GL STATE:")) {
|
||||
glState++;
|
||||
}
|
||||
}
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] gl samples wait/upload/draw/state=%d/%d/%d/%d",
|
||||
glWait,
|
||||
glUpload,
|
||||
glDraw,
|
||||
glState));
|
||||
|
||||
List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
|
||||
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
lines.add("[FrameStutter] sample top:");
|
||||
int top = Math.min(TOP_STACKS, entries.size());
|
||||
for (int i = 0; i < top; i++) {
|
||||
Map.Entry<String, Integer> entry = entries.get(i);
|
||||
double pct = entry.getValue() * 100.0 / samples.size();
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
"[FrameStutter] %d) %s (%d, %.1f%%)",
|
||||
i + 1,
|
||||
entry.getKey(),
|
||||
entry.getValue(),
|
||||
pct));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Sample> samplesInWindow(long startNs, long endNs) {
|
||||
List<Sample> out = new ArrayList<>();
|
||||
synchronized (LOCK) {
|
||||
for (int i = 0; i < sampleCount; i++) {
|
||||
Sample sample = SAMPLES[i];
|
||||
if (sample != null && sample.timeNs >= startNs && sample.timeNs <= endNs) {
|
||||
out.add(sample);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort((a, b) -> Long.compare(a.timeNs, b.timeNs));
|
||||
return out;
|
||||
}
|
||||
|
||||
private static List<GcEvent> gcNearWindow(long startNs, long endNs) {
|
||||
long from = startNs - GC_CORRELATION_WINDOW_NS;
|
||||
long to = endNs + GC_CORRELATION_WINDOW_NS;
|
||||
List<GcEvent> out = new ArrayList<>();
|
||||
synchronized (LOCK) {
|
||||
for (int i = 0; i < gcCount; i++) {
|
||||
GcEvent event = GC_EVENTS[i];
|
||||
if (event != null && event.endNs >= from && event.endNs <= to) {
|
||||
out.add(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort((a, b) -> Long.compare(a.endNs, b.endNs));
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void ensureSampler() {
|
||||
if (running || output == ProfilerSettings.OutputMode.OFF) return;
|
||||
running = true;
|
||||
samplerThread = new Thread(DevFrameStutterProfiler::sampleLoop, "LoVisual-DevFrameStutterProfiler");
|
||||
samplerThread.setDaemon(true);
|
||||
samplerThread.start();
|
||||
}
|
||||
|
||||
private static void stopSampler() {
|
||||
running = false;
|
||||
Thread thread = samplerThread;
|
||||
samplerThread = null;
|
||||
if (thread != null) {
|
||||
thread.interrupt();
|
||||
}
|
||||
renderThread = null;
|
||||
}
|
||||
|
||||
private static void sampleLoop() {
|
||||
long lastSampleNs = 0L;
|
||||
while (running) {
|
||||
if (output == ProfilerSettings.OutputMode.OFF) {
|
||||
sleepMs(20L);
|
||||
continue;
|
||||
}
|
||||
Thread target = renderThread;
|
||||
if (target == null) {
|
||||
sleepMs(10L);
|
||||
continue;
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSampleNs >= sampleIntervalNs) {
|
||||
recordSample(now, target);
|
||||
lastSampleNs = now;
|
||||
}
|
||||
sleepMs(1L);
|
||||
}
|
||||
}
|
||||
|
||||
private static void recordSample(long now, Thread target) {
|
||||
StackTraceElement[] stack = target.getStackTrace();
|
||||
if (stack == null || stack.length == 0) return;
|
||||
String key = buildKey(stack);
|
||||
if (key == null || key.isBlank()) return;
|
||||
synchronized (LOCK) {
|
||||
SAMPLES[sampleCursor] = new Sample(now, key);
|
||||
sampleCursor = (sampleCursor + 1) % MAX_SAMPLES;
|
||||
if (sampleCount < MAX_SAMPLES) {
|
||||
sampleCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String buildKey(StackTraceElement[] stack) {
|
||||
StringBuilder sb = new StringBuilder(320);
|
||||
String glCat = glCategory(stack);
|
||||
if (glCat != null) {
|
||||
sb.append("GL ").append(glCat).append(": ");
|
||||
}
|
||||
int added = 0;
|
||||
for (StackTraceElement e : stack) {
|
||||
if (added >= MAX_STACK_FRAMES) break;
|
||||
if (isNoise(e)) continue;
|
||||
if (added > 0) sb.append(" <= ");
|
||||
sb.append(formatElement(e));
|
||||
added++;
|
||||
}
|
||||
return added == 0 ? null : sb.toString();
|
||||
}
|
||||
|
||||
private static String glCategory(StackTraceElement[] stack) {
|
||||
for (StackTraceElement e : stack) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
if (!isGlFrame(cls)) continue;
|
||||
if (method == null) continue;
|
||||
if (method.equals("glfwSwapBuffers")
|
||||
|| method.equals("glClientWaitSync")
|
||||
|| method.equals("nglClientWaitSync")
|
||||
|| method.equals("glWaitSync")
|
||||
|| method.equals("glFinish")) {
|
||||
return "WAIT";
|
||||
}
|
||||
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
|
||||
return "DRAW";
|
||||
}
|
||||
if (method.contains("BufferSubData")
|
||||
|| method.contains("BufferData")
|
||||
|| method.contains("TexImage")
|
||||
|| method.contains("TexSubImage")
|
||||
|| method.contains("FlushMapped")
|
||||
|| method.contains("MapBuffer")
|
||||
|| method.contains("MapBufferRange")
|
||||
|| method.contains("UnmapBuffer")) {
|
||||
return "UPLOAD";
|
||||
}
|
||||
if (method.startsWith("glUseProgram")
|
||||
|| method.startsWith("glBind")
|
||||
|| method.startsWith("glTexParameter")
|
||||
|| method.startsWith("glBlend")
|
||||
|| method.startsWith("glEnable")
|
||||
|| method.startsWith("glDisable")
|
||||
|| method.startsWith("glDepth")
|
||||
|| method.startsWith("glColorMask")
|
||||
|| method.startsWith("glViewport")
|
||||
|| method.startsWith("glScissor")
|
||||
|| method.startsWith("glActiveTexture")
|
||||
|| method.startsWith("glUniform")
|
||||
|| method.startsWith("glVertexAttrib")) {
|
||||
return "STATE";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isGlFrame(String cls) {
|
||||
return cls != null
|
||||
&& (cls.startsWith("org.lwjgl.opengl.")
|
||||
|| cls.startsWith("org.lwjgl.glfw.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.platform.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.systems."));
|
||||
}
|
||||
|
||||
private static boolean isNoise(StackTraceElement e) {
|
||||
String cls = e.getClassName();
|
||||
return cls.startsWith("java.lang.Thread")
|
||||
|| cls.startsWith("jdk.internal")
|
||||
|| cls.startsWith("sun.")
|
||||
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevFrameStutterProfiler");
|
||||
}
|
||||
|
||||
private static String formatElement(StackTraceElement e) {
|
||||
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
|
||||
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + e.getLineNumber() + ")";
|
||||
}
|
||||
|
||||
private static void installGcListener() {
|
||||
if (gcListenerInstalled) return;
|
||||
synchronized (LOCK) {
|
||||
if (gcListenerInstalled) return;
|
||||
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
|
||||
if (bean instanceof NotificationEmitter emitter) {
|
||||
emitter.addNotificationListener(DevFrameStutterProfiler::onGcNotification, null, null);
|
||||
}
|
||||
}
|
||||
gcListenerInstalled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void onGcNotification(Notification notification, Object handback) {
|
||||
if (output == ProfilerSettings.OutputMode.OFF) return;
|
||||
if (!GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) return;
|
||||
Object data = notification.getUserData();
|
||||
if (!(data instanceof CompositeData compositeData)) return;
|
||||
try {
|
||||
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(compositeData);
|
||||
GcInfo gcInfo = info.getGcInfo();
|
||||
long freed = usedBefore(gcInfo) - usedAfter(gcInfo);
|
||||
GcEvent event = new GcEvent(
|
||||
System.nanoTime(),
|
||||
info.getGcName(),
|
||||
info.getGcCause(),
|
||||
Math.max(0L, gcInfo.getDuration()),
|
||||
Math.max(0L, freed));
|
||||
synchronized (LOCK) {
|
||||
GC_EVENTS[gcCursor] = event;
|
||||
gcCursor = (gcCursor + 1) % MAX_GC_EVENTS;
|
||||
if (gcCount < MAX_GC_EVENTS) {
|
||||
gcCount++;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static long usedBefore(GcInfo info) {
|
||||
return used(info == null ? null : info.getMemoryUsageBeforeGc());
|
||||
}
|
||||
|
||||
private static long usedAfter(GcInfo info) {
|
||||
return used(info == null ? null : info.getMemoryUsageAfterGc());
|
||||
}
|
||||
|
||||
private static long used(Map<String, MemoryUsage> usage) {
|
||||
if (usage == null || usage.isEmpty()) return 0L;
|
||||
long total = 0L;
|
||||
for (MemoryUsage value : usage.values()) {
|
||||
if (value != null && value.getUsed() > 0L) {
|
||||
total += value.getUsed();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static void emit(List<String> lines) {
|
||||
ProfilerSettings.OutputMode mode = output;
|
||||
if (mode == ProfilerSettings.OutputMode.OFF || lines == null || lines.isEmpty()) return;
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("%s", line);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal(line));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long clampMs(double valueMs, double minMs, double maxMs, long fallbackNs) {
|
||||
if (!Double.isFinite(valueMs) || valueMs <= 0.0) return fallbackNs;
|
||||
double clamped = Math.max(minMs, Math.min(maxMs, valueMs));
|
||||
return (long) (clamped * 1_000_000.0);
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
private static void sleepMs(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private record Sample(long timeNs, String stack) {
|
||||
}
|
||||
|
||||
private record GcEvent(long endNs, String name, String cause, long durationMs, long freedBytes) {
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,253 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import jdk.jfr.EventSettings;
|
||||
import jdk.jfr.Recording;
|
||||
import net.minecraft.client.Minecraft;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public enum DevJfrProfiler {
|
||||
;
|
||||
|
||||
private static final DateTimeFormatter FILE_TIME =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
|
||||
|
||||
private static Recording recording;
|
||||
private static Preset activePreset;
|
||||
private static Instant startedAt;
|
||||
private static Path outputPath;
|
||||
|
||||
public static synchronized StartResult start(Preset preset) {
|
||||
if (recording != null) {
|
||||
return StartResult.alreadyRunning(activePreset, outputPath, startedAt);
|
||||
}
|
||||
try {
|
||||
Path dir = ensureOutputDirectory();
|
||||
Path file = dir.resolve(defaultFileName(preset, false));
|
||||
|
||||
Recording next = new Recording();
|
||||
next.setName("LoVisual " + preset.getId());
|
||||
next.setToDisk(true);
|
||||
next.setDumpOnExit(false);
|
||||
configure(next, preset);
|
||||
next.start();
|
||||
|
||||
recording = next;
|
||||
activePreset = preset;
|
||||
startedAt = Instant.now();
|
||||
outputPath = file;
|
||||
|
||||
ProfilerLog.info("JFR started (%s) -> %s", preset.getId(), file.toAbsolutePath());
|
||||
return StartResult.started(preset, file, startedAt);
|
||||
} catch (Throwable t) {
|
||||
ProfilerLog.warn("JFR unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
return StartResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized DumpResult dumpSnapshot() {
|
||||
if (recording == null) {
|
||||
return DumpResult.notRunningResult();
|
||||
}
|
||||
try {
|
||||
Path dir = ensureOutputDirectory();
|
||||
Path snapshot = dir.resolve(defaultFileName(activePreset, true));
|
||||
recording.dump(snapshot);
|
||||
ProfilerLog.info("JFR snapshot dumped -> %s", snapshot.toAbsolutePath());
|
||||
return DumpResult.dumped(snapshot);
|
||||
} catch (Throwable t) {
|
||||
ProfilerLog.warn("JFR snapshot failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
return DumpResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized StopResult stop() {
|
||||
if (recording == null) {
|
||||
return StopResult.notRunningResult();
|
||||
}
|
||||
Recording current = recording;
|
||||
Preset preset = activePreset;
|
||||
Instant started = startedAt;
|
||||
Path destination = outputPath;
|
||||
recording = null;
|
||||
activePreset = null;
|
||||
startedAt = null;
|
||||
outputPath = null;
|
||||
try {
|
||||
current.stop();
|
||||
Files.createDirectories(destination.getParent());
|
||||
current.dump(destination);
|
||||
current.close();
|
||||
ProfilerLog.info("JFR stopped (%s) -> %s", preset.getId(), destination.toAbsolutePath());
|
||||
return StopResult.stopped(preset, destination, started);
|
||||
} catch (Throwable t) {
|
||||
try {
|
||||
current.close();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
ProfilerLog.warn("JFR stop failed: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
return StopResult.failed(t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized String statusLine() {
|
||||
if (recording == null) {
|
||||
return "Profiler JFR: off";
|
||||
}
|
||||
long seconds = Math.max(0L, Duration.between(startedAt, Instant.now()).toSeconds());
|
||||
return "Profiler JFR: on (" + activePreset.getId()
|
||||
+ ", " + formatDuration(seconds)
|
||||
+ ", file " + outputPath.toAbsolutePath() + ")";
|
||||
}
|
||||
|
||||
private static void configure(Recording recording, Preset preset) {
|
||||
enable(recording, "jdk.GarbageCollection", true, null, null);
|
||||
enable(recording, "jdk.GCHeapSummary", false, null, null);
|
||||
enable(recording, "jdk.MetaspaceSummary", false, null, null);
|
||||
enable(recording, "jdk.CPULoad", false, Duration.ofSeconds(1), null);
|
||||
enable(recording, "jdk.JavaThreadStatistics", false, Duration.ofSeconds(1), null);
|
||||
if (preset.capturesAllocations()) {
|
||||
enable(recording, "jdk.ObjectAllocationSample", true, null, null);
|
||||
}
|
||||
if (preset == Preset.FULL) {
|
||||
enable(recording, "jdk.ExecutionSample", true, Duration.ofMillis(20), null);
|
||||
enable(recording, "jdk.NativeMethodSample", true, Duration.ofMillis(20), null);
|
||||
enable(recording, "jdk.ThreadPark", true, null, Duration.ofMillis(1));
|
||||
enable(recording, "jdk.JavaMonitorEnter", true, null, Duration.ofMillis(1));
|
||||
}
|
||||
}
|
||||
|
||||
private static void enable(
|
||||
Recording recording,
|
||||
String eventName,
|
||||
boolean stackTrace,
|
||||
Duration period,
|
||||
Duration threshold
|
||||
) {
|
||||
try {
|
||||
EventSettings settings = recording.enable(eventName);
|
||||
settings = stackTrace ? settings.withStackTrace() : settings.withoutStackTrace();
|
||||
if (period != null) {
|
||||
settings = settings.withPeriod(period);
|
||||
}
|
||||
if (threshold != null) {
|
||||
settings = settings.withThreshold(threshold);
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// Some runtimes ship a slightly different event set.
|
||||
}
|
||||
}
|
||||
|
||||
private static Path ensureOutputDirectory() throws Exception {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
Path dir;
|
||||
if (mc != null && mc.gameDirectory != null) {
|
||||
dir = mc.gameDirectory.toPath().resolve("profile").resolve("jfr");
|
||||
} else {
|
||||
dir = Path.of("profile", "jfr");
|
||||
}
|
||||
Files.createDirectories(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static String defaultFileName(Preset preset, boolean snapshot) {
|
||||
String timestamp = FILE_TIME.format(LocalDateTime.now(ZoneId.systemDefault()));
|
||||
String suffix = snapshot ? "-snapshot" : "";
|
||||
return "lovisual-" + preset.getId() + suffix + "-" + timestamp + ".jfr";
|
||||
}
|
||||
|
||||
private static String formatDuration(long totalSeconds) {
|
||||
long minutes = totalSeconds / 60L;
|
||||
long seconds = totalSeconds % 60L;
|
||||
if (minutes <= 0L) {
|
||||
return seconds + "s";
|
||||
}
|
||||
return minutes + "m " + seconds + "s";
|
||||
}
|
||||
|
||||
public enum Preset {
|
||||
GC("gc"),
|
||||
ALLOC("alloc"),
|
||||
FULL("full");
|
||||
|
||||
private final String id;
|
||||
|
||||
Preset(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public static Preset parse(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return FULL;
|
||||
}
|
||||
return switch (raw.toLowerCase()) {
|
||||
case "gc" -> GC;
|
||||
case "alloc", "allocation", "allocs" -> ALLOC;
|
||||
case "full", "all", "profile" -> FULL;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean capturesAllocations() {
|
||||
return this == ALLOC || this == FULL;
|
||||
}
|
||||
}
|
||||
|
||||
public record StartResult(boolean started, boolean alreadyRunning, Preset preset, Path path, Instant startedAt,
|
||||
String error) {
|
||||
private static StartResult started(Preset preset, Path path, Instant startedAt) {
|
||||
return new StartResult(true, false, preset, path, startedAt, null);
|
||||
}
|
||||
|
||||
private static StartResult alreadyRunning(Preset preset, Path path, Instant startedAt) {
|
||||
return new StartResult(false, true, preset, path, startedAt, null);
|
||||
}
|
||||
|
||||
private static StartResult failed(String error) {
|
||||
return new StartResult(false, false, null, null, null, error);
|
||||
}
|
||||
}
|
||||
|
||||
public record DumpResult(boolean dumped, boolean notRunning, Path path, String error) {
|
||||
private static DumpResult dumped(Path path) {
|
||||
return new DumpResult(true, false, path, null);
|
||||
}
|
||||
|
||||
private static DumpResult notRunningResult() {
|
||||
return new DumpResult(false, true, null, null);
|
||||
}
|
||||
|
||||
private static DumpResult failed(String error) {
|
||||
return new DumpResult(false, false, null, error);
|
||||
}
|
||||
}
|
||||
|
||||
public record StopResult(boolean stopped, boolean notRunning, Preset preset, Path path, Instant startedAt,
|
||||
String error) {
|
||||
private static StopResult stopped(Preset preset, Path path, Instant startedAt) {
|
||||
return new StopResult(true, false, preset, path, startedAt, null);
|
||||
}
|
||||
|
||||
private static StopResult notRunningResult() {
|
||||
return new StopResult(false, true, null, null, null, null);
|
||||
}
|
||||
|
||||
private static StopResult failed(String error) {
|
||||
return new StopResult(false, false, null, null, null, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,457 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Low-overhead owner/effect profiler for the new RHI path.
|
||||
*
|
||||
* <p>The existing DevRenderProfiler2D/3D tree answers "which Java section is hot".
|
||||
* This profiler answers the practical render question: which phase/widget/node/effect/pass
|
||||
* consumed CPU time and caused RHI work (draws, uploads, fullscreen passes, copies, uniforms).</p>
|
||||
*/
|
||||
public enum DevRenderCostProfiler {
|
||||
;
|
||||
private static final int MAX_BUCKETS = 768;
|
||||
private static final long NS_IN_MS = 1_000_000L;
|
||||
private static final int DEFAULT_LOG_INTERVAL_FRAMES = 120;
|
||||
private static final int DEFAULT_LOG_TOP = 20;
|
||||
private static final double DEFAULT_LOG_MIN_MS = 0.02;
|
||||
|
||||
private static final String PROP_ENABLED = "lovisual.profiler.renderCost";
|
||||
private static final String PROP_LOG = "lovisual.profiler.renderCost.log";
|
||||
private static final String PROP_INTERVAL = "lovisual.profiler.renderCost.interval";
|
||||
private static final String PROP_TOP = "lovisual.profiler.renderCost.top";
|
||||
private static final String PROP_MIN_MS = "lovisual.profiler.renderCost.minMs";
|
||||
|
||||
private static final LinkedHashMap<String, Bucket> buckets = new LinkedHashMap<>();
|
||||
private static final HashMap<String, String> labelCache = new HashMap<>(256);
|
||||
private static final ThreadLocal<Deque<Scope>> scopeStack = ThreadLocal.withInitial(ArrayDeque::new);
|
||||
private static long frameId = Long.MIN_VALUE;
|
||||
private static long lastLoggedFrameId = Long.MIN_VALUE;
|
||||
private static boolean active;
|
||||
private static Snapshot snapshot = Snapshot.EMPTY;
|
||||
|
||||
public static void beginFrame(long newFrameId) {
|
||||
if (frameId == newFrameId) return;
|
||||
frameId = newFrameId;
|
||||
active = isProfilerEnabled();
|
||||
if (!active) {
|
||||
snapshot = Snapshot.EMPTY;
|
||||
return;
|
||||
}
|
||||
buckets.clear();
|
||||
scopeStack.get().clear();
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (!active) return;
|
||||
snapshot = Snapshot.from(frameId, buckets);
|
||||
emitLogIfDue(snapshot);
|
||||
active = false;
|
||||
}
|
||||
|
||||
public static Snapshot snapshot() {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public static boolean isConfigured() {
|
||||
return Boolean.getBoolean(PROP_ENABLED);
|
||||
}
|
||||
|
||||
public static Scope scope(String domain, String name) {
|
||||
if (!active) return Scope.NOOP;
|
||||
String d = clean(domain, "unknown");
|
||||
String n = clean(name, "unnamed");
|
||||
String owner = clean(DevProfilerPhase.current(), "unknown");
|
||||
Bucket bucket = bucket(d, owner, n);
|
||||
if (bucket == null) return Scope.NOOP;
|
||||
Scope scope = new Scope(bucket, System.nanoTime(), Counters.capture(), true);
|
||||
scopeStack.get().push(scope);
|
||||
return scope;
|
||||
}
|
||||
|
||||
public static Scope phase(String label) {
|
||||
return scope("phase", label);
|
||||
}
|
||||
|
||||
public static Scope uiNode(Object label) {
|
||||
return scope("ui.node", String.valueOf(label));
|
||||
}
|
||||
|
||||
public static Scope uiRuntime(String label) {
|
||||
return scope("ui.runtime", label);
|
||||
}
|
||||
|
||||
public static Scope uiEffect(String label) {
|
||||
return scope("ui.effect", label);
|
||||
}
|
||||
|
||||
public static Scope postPass(String label) {
|
||||
return scope("post.pass", label);
|
||||
}
|
||||
|
||||
public static Scope rhiDraw(String label) {
|
||||
return scope("rhi.draw", label);
|
||||
}
|
||||
|
||||
public static Scope itemRender(String label) {
|
||||
return scope("item.render", label);
|
||||
}
|
||||
|
||||
public static Scope worldEffect(String label) {
|
||||
return scope("world.effect", label);
|
||||
}
|
||||
|
||||
public static List<String> debugLines(String title, String domainPrefix, int limit, double minMs) {
|
||||
Snapshot snap = snapshot;
|
||||
if (snap == null || snap.entries.isEmpty()) return List.of();
|
||||
String prefix = domainPrefix == null ? "" : domainPrefix;
|
||||
List<Entry> filtered = new ArrayList<>();
|
||||
for (Entry entry : snap.entries) {
|
||||
if (prefix.isEmpty() || entry.domain.startsWith(prefix)) {
|
||||
filtered.add(entry);
|
||||
}
|
||||
}
|
||||
if (filtered.isEmpty()) return List.of();
|
||||
|
||||
filtered.sort(Comparator
|
||||
.comparingLong((Entry e) -> e.totalNs).reversed()
|
||||
.thenComparingLong((Entry e) -> e.uploadedBytes).reversed()
|
||||
.thenComparingLong((Entry e) -> e.drawCalls).reversed());
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add(title + ":");
|
||||
int count = 0;
|
||||
for (Entry e : filtered) {
|
||||
double ms = e.totalNs / (double) NS_IN_MS;
|
||||
if (ms < minMs) continue;
|
||||
lines.add(String.format(Locale.ROOT,
|
||||
" %d) [%s] %s:%s %.2f ms max %.2f calls %d | draw %d upload %d/%s fs %d copy %d/%d uni %d/%s",
|
||||
count + 1,
|
||||
shorten(e.owner, 42),
|
||||
e.domain,
|
||||
shorten(e.name, 56),
|
||||
ms,
|
||||
e.maxNs / (double) NS_IN_MS,
|
||||
e.calls,
|
||||
e.drawCalls,
|
||||
e.meshUploads,
|
||||
formatBytes(e.uploadedBytes),
|
||||
e.fullscreenPasses,
|
||||
e.fastCopies,
|
||||
e.shaderCopies,
|
||||
e.uniformWrites,
|
||||
formatBytes(e.uniformBytes)));
|
||||
count++;
|
||||
if (count >= limit) break;
|
||||
}
|
||||
if (count == 0) return List.of();
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static boolean isProfilerEnabled() {
|
||||
return Boolean.getBoolean(PROP_ENABLED);
|
||||
}
|
||||
|
||||
private static boolean shouldLogToLatest() {
|
||||
if (!Boolean.getBoolean(PROP_ENABLED)) return false;
|
||||
return Boolean.parseBoolean(System.getProperty(PROP_LOG, "true"));
|
||||
}
|
||||
|
||||
private static void emitLogIfDue(Snapshot snap) {
|
||||
if (!shouldLogToLatest()) return;
|
||||
if (snap == null || snap.entries.isEmpty()) return;
|
||||
|
||||
int interval = intProperty(PROP_INTERVAL, DEFAULT_LOG_INTERVAL_FRAMES, 1, 60_000);
|
||||
if (lastLoggedFrameId != Long.MIN_VALUE && snap.frameId - lastLoggedFrameId < interval) return;
|
||||
lastLoggedFrameId = snap.frameId;
|
||||
|
||||
int top = intProperty(PROP_TOP, DEFAULT_LOG_TOP, 1, 200);
|
||||
double minMs = doubleProperty(PROP_MIN_MS, DEFAULT_LOG_MIN_MS, 0.0, 1_000.0);
|
||||
|
||||
ProfilerLog.info("[RenderCost] frame=%d buckets=%d interval=%d top=%d minMs=%.3f", snap.frameId, snap.entries.size(), interval, top, minMs);
|
||||
emitDomainToLog("phases", "phase", top, minMs);
|
||||
emitDomainToLog("ui runtime", "ui.runtime", top, minMs);
|
||||
emitDomainToLog("ui nodes", "ui.node", top, minMs);
|
||||
emitDomainToLog("ui effects", "ui.effect", top, minMs);
|
||||
emitDomainToLog("item render", "item.render", top, minMs);
|
||||
emitDomainToLog("world effects", "world.effect", top, minMs);
|
||||
emitDomainToLog("post passes", "post.pass", top, minMs);
|
||||
emitDomainToLog("rhi draws", "rhi.draw", top, minMs);
|
||||
}
|
||||
|
||||
private static void emitDomainToLog(String title, String prefix, int top, double minMs) {
|
||||
List<String> lines = debugLines("[RenderCost] " + title, prefix, top, minMs);
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("%s", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static int intProperty(String key, int fallback, int min, int max) {
|
||||
String raw = System.getProperty(key);
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
try {
|
||||
int value = Integer.parseInt(raw.trim());
|
||||
return Math.max(min, Math.min(max, value));
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static double doubleProperty(String key, double fallback, double min, double max) {
|
||||
String raw = System.getProperty(key);
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
try {
|
||||
double value = Double.parseDouble(raw.trim());
|
||||
if (!Double.isFinite(value)) return fallback;
|
||||
return Math.max(min, Math.min(max, value));
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
private static Bucket bucket(String domain, String owner, String name) {
|
||||
String key = domain + '\u001F' + owner + '\u001F' + name;
|
||||
Bucket existing = buckets.get(key);
|
||||
if (existing != null) return existing;
|
||||
if (buckets.size() >= MAX_BUCKETS) {
|
||||
key = "overflow\u001F" + owner + "\u001Fother";
|
||||
existing = buckets.get(key);
|
||||
if (existing != null) return existing;
|
||||
if (buckets.size() >= MAX_BUCKETS + 1) return null;
|
||||
Bucket overflow = new Bucket("overflow", owner, "other");
|
||||
buckets.put(key, overflow);
|
||||
return overflow;
|
||||
}
|
||||
Bucket created = new Bucket(domain, owner, name);
|
||||
buckets.put(key, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
private static String clean(String raw, String fallback) {
|
||||
if (raw == null || raw.isBlank()) return fallback;
|
||||
String s = raw.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').trim();
|
||||
return s.isEmpty() ? fallback : s;
|
||||
}
|
||||
|
||||
private static String shorten(String s, int max) {
|
||||
if (s == null) return "";
|
||||
if (s.length() <= max) return s;
|
||||
if (max <= 3) return s.substring(0, max);
|
||||
return s.substring(0, max - 3) + "...";
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
public static final class Scope implements AutoCloseable {
|
||||
private static final Scope NOOP = new Scope(null, 0L, Counters.ZERO, false);
|
||||
private final Bucket bucket;
|
||||
private final long startNs;
|
||||
private final Counters begin;
|
||||
private final boolean enabled;
|
||||
private boolean closed;
|
||||
private long childNs;
|
||||
private Counters childCounters = Counters.ZERO;
|
||||
|
||||
private Scope(Bucket bucket, long startNs, Counters begin, boolean enabled) {
|
||||
this.bucket = bucket;
|
||||
this.startNs = startNs;
|
||||
this.begin = begin;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!enabled || closed || bucket == null) return;
|
||||
closed = true;
|
||||
long elapsed = Math.max(0L, System.nanoTime() - startNs);
|
||||
Counters rawDelta = begin.deltaTo(Counters.capture());
|
||||
|
||||
Deque<Scope> stack = scopeStack.get();
|
||||
if (!stack.isEmpty() && stack.peek() == this) {
|
||||
stack.pop();
|
||||
} else {
|
||||
stack.remove(this);
|
||||
}
|
||||
|
||||
if (!stack.isEmpty()) {
|
||||
Scope parent = stack.peek();
|
||||
parent.childNs += elapsed;
|
||||
parent.childCounters = parent.childCounters.plus(rawDelta);
|
||||
}
|
||||
|
||||
long bucketNs = elapsed;
|
||||
Counters bucketCounters = rawDelta;
|
||||
if ("ui.node".equals(bucket.domain)) {
|
||||
bucketNs = Math.max(0L, elapsed - childNs);
|
||||
bucketCounters = rawDelta.minus(childCounters);
|
||||
}
|
||||
bucket.add(bucketNs, bucketCounters);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Bucket {
|
||||
final String domain;
|
||||
final String owner;
|
||||
final String name;
|
||||
long calls;
|
||||
long totalNs;
|
||||
long maxNs;
|
||||
long drawCalls;
|
||||
long meshUploads;
|
||||
long fullscreenPasses;
|
||||
long fastCopies;
|
||||
long shaderCopies;
|
||||
long uploadedBytes;
|
||||
long uniformWrites;
|
||||
long uniformBytes;
|
||||
|
||||
private Bucket(String domain, String owner, String name) {
|
||||
this.domain = domain;
|
||||
this.owner = owner;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
void add(long ns, Counters d) {
|
||||
calls++;
|
||||
totalNs += ns;
|
||||
maxNs = Math.max(maxNs, ns);
|
||||
if (d == null) return;
|
||||
drawCalls += d.drawCalls;
|
||||
meshUploads += d.meshUploads;
|
||||
fullscreenPasses += d.fullscreenPasses;
|
||||
fastCopies += d.fastCopies;
|
||||
shaderCopies += d.shaderCopies;
|
||||
uploadedBytes += d.uploadedBytes;
|
||||
uniformWrites += d.uniformWrites;
|
||||
uniformBytes += d.uniformBytes;
|
||||
}
|
||||
}
|
||||
|
||||
private record Counters(long drawCalls,
|
||||
long meshUploads,
|
||||
long fullscreenPasses,
|
||||
long fastCopies,
|
||||
long shaderCopies,
|
||||
long uploadedBytes,
|
||||
long uniformWrites,
|
||||
long uniformBytes) {
|
||||
static final Counters ZERO = new Counters(0, 0, 0, 0, 0, 0, 0, 0);
|
||||
|
||||
static Counters capture() {
|
||||
try {
|
||||
long uploaded = LoVisualRenderSystem.rhi().stats().uploadedVertexBytes()
|
||||
+ LoVisualRenderSystem.rhi().stats().uploadedIndexBytes();
|
||||
return new Counters(
|
||||
LoVisualRenderSystem.rhi().stats().drawCalls(),
|
||||
LoVisualRenderSystem.rhi().stats().meshUploads(),
|
||||
LoVisualRenderSystem.rhi().stats().fullscreenPasses(),
|
||||
LoVisualRenderSystem.rhi().stats().textureFastCopies(),
|
||||
LoVisualRenderSystem.rhi().stats().textureShaderCopies(),
|
||||
uploaded,
|
||||
LoVisualRenderSystem.uniforms().stats().writes(),
|
||||
LoVisualRenderSystem.uniforms().stats().uploadedBytes()
|
||||
);
|
||||
} catch (Throwable ignored) {
|
||||
return ZERO;
|
||||
}
|
||||
}
|
||||
|
||||
Counters deltaTo(Counters end) {
|
||||
if (end == null) return ZERO;
|
||||
return new Counters(
|
||||
Math.max(0L, end.drawCalls - drawCalls),
|
||||
Math.max(0L, end.meshUploads - meshUploads),
|
||||
Math.max(0L, end.fullscreenPasses - fullscreenPasses),
|
||||
Math.max(0L, end.fastCopies - fastCopies),
|
||||
Math.max(0L, end.shaderCopies - shaderCopies),
|
||||
Math.max(0L, end.uploadedBytes - uploadedBytes),
|
||||
Math.max(0L, end.uniformWrites - uniformWrites),
|
||||
Math.max(0L, end.uniformBytes - uniformBytes)
|
||||
);
|
||||
}
|
||||
|
||||
Counters plus(Counters other) {
|
||||
if (other == null) return this;
|
||||
return new Counters(
|
||||
drawCalls + other.drawCalls,
|
||||
meshUploads + other.meshUploads,
|
||||
fullscreenPasses + other.fullscreenPasses,
|
||||
fastCopies + other.fastCopies,
|
||||
shaderCopies + other.shaderCopies,
|
||||
uploadedBytes + other.uploadedBytes,
|
||||
uniformWrites + other.uniformWrites,
|
||||
uniformBytes + other.uniformBytes
|
||||
);
|
||||
}
|
||||
|
||||
Counters minus(Counters other) {
|
||||
if (other == null) return this;
|
||||
return new Counters(
|
||||
Math.max(0L, drawCalls - other.drawCalls),
|
||||
Math.max(0L, meshUploads - other.meshUploads),
|
||||
Math.max(0L, fullscreenPasses - other.fullscreenPasses),
|
||||
Math.max(0L, fastCopies - other.fastCopies),
|
||||
Math.max(0L, shaderCopies - other.shaderCopies),
|
||||
Math.max(0L, uploadedBytes - other.uploadedBytes),
|
||||
Math.max(0L, uniformWrites - other.uniformWrites),
|
||||
Math.max(0L, uniformBytes - other.uniformBytes)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public record Snapshot(long frameId, List<Entry> entries) {
|
||||
static final Snapshot EMPTY = new Snapshot(Long.MIN_VALUE, List.of());
|
||||
|
||||
static Snapshot from(long frameId, Map<String, Bucket> buckets) {
|
||||
if (buckets == null || buckets.isEmpty()) return EMPTY;
|
||||
List<Entry> out = new ArrayList<>(buckets.size());
|
||||
for (Bucket b : buckets.values()) {
|
||||
out.add(new Entry(
|
||||
b.domain,
|
||||
b.owner,
|
||||
b.name,
|
||||
b.calls,
|
||||
b.totalNs,
|
||||
b.maxNs,
|
||||
b.drawCalls,
|
||||
b.meshUploads,
|
||||
b.fullscreenPasses,
|
||||
b.fastCopies,
|
||||
b.shaderCopies,
|
||||
b.uploadedBytes,
|
||||
b.uniformWrites,
|
||||
b.uniformBytes
|
||||
));
|
||||
}
|
||||
return new Snapshot(frameId, List.copyOf(out));
|
||||
}
|
||||
}
|
||||
|
||||
public record Entry(String domain,
|
||||
String owner,
|
||||
String name,
|
||||
long calls,
|
||||
long totalNs,
|
||||
long maxNs,
|
||||
long drawCalls,
|
||||
long meshUploads,
|
||||
long fullscreenPasses,
|
||||
long fastCopies,
|
||||
long shaderCopies,
|
||||
long uploadedBytes,
|
||||
long uniformWrites,
|
||||
long uniformBytes) {
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,498 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import dev.loki.lovisual.render.engine.command.UiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.renderer.Renderer2D;
|
||||
import dev.loki.lovisual.render.engine.renderer.ui.runtime.script.CachedUiScriptRuntime;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.text.TextCommandStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.text.TextRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.uniform.MeshBuilder;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public enum DevRenderProfiler2D {
|
||||
;
|
||||
|
||||
private static final long NS_IN_MS = 1_000_000L;
|
||||
private static final int DEFAULT_TOP_LIMIT = 6;
|
||||
private static final int DEFAULT_TREE_DEPTH = 32;
|
||||
private static final double DEFAULT_MIN_MS = 0.0;
|
||||
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
|
||||
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
|
||||
private static boolean active;
|
||||
private static Node root;
|
||||
private static Node snapshot;
|
||||
private static long lastEmitNs;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static void beginFrame(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
|
||||
if (!isEnabled()) return;
|
||||
CachedUiScriptRuntime.resetFrameStats();
|
||||
MeshBuilder.resetFrameStats();
|
||||
active = true;
|
||||
root = new Node(name, null);
|
||||
stack.clear();
|
||||
stack.push(root);
|
||||
root.startNs = System.nanoTime();
|
||||
}
|
||||
|
||||
public static boolean beginFrameIfNeeded(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.UI);
|
||||
if (!isEnabled() || active) return false;
|
||||
beginFrame(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (!isEnabled() || !active) return;
|
||||
long now = System.nanoTime();
|
||||
while (stack.size() > 1) {
|
||||
endSection();
|
||||
}
|
||||
Node r = stack.peek();
|
||||
if (r != null) {
|
||||
r.calls = Math.max(1, r.calls);
|
||||
r.totalNs += now - r.startNs;
|
||||
r.startNs = 0L;
|
||||
snapshot = r;
|
||||
DevTracyProfiler.plotUiFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
|
||||
}
|
||||
active = false;
|
||||
emitIfDue(now);
|
||||
}
|
||||
|
||||
public static Section section(String name) {
|
||||
if (!isEnabled() || !active) return Section.NOOP;
|
||||
beginSection(name);
|
||||
return new Section(true);
|
||||
}
|
||||
|
||||
private static void beginSection(String name) {
|
||||
Node parent = stack.peek();
|
||||
if (parent == null) return;
|
||||
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
|
||||
child.calls += 1;
|
||||
child.startNs = System.nanoTime();
|
||||
stack.push(child);
|
||||
}
|
||||
|
||||
private static void endSection() {
|
||||
Node node = stack.poll();
|
||||
if (node == null) return;
|
||||
long now = System.nanoTime();
|
||||
node.totalNs += now - node.startNs;
|
||||
node.startNs = 0L;
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines() {
|
||||
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
|
||||
if (!isEnabled()) return List.of();
|
||||
Node snap = snapshot;
|
||||
if (snap == null) return List.of();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
double totalMs = snap.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format("ui prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
|
||||
appendRuntimeCounters(lines);
|
||||
|
||||
List<Node> flat = new ArrayList<>();
|
||||
collectFlat(snap, flat);
|
||||
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
|
||||
int top = Math.min(topLimit, flat.size());
|
||||
if (top > 0) {
|
||||
lines.add("ui prof top:");
|
||||
for (int i = 0; i < top; i++) {
|
||||
Node n = flat.get(i);
|
||||
double ms = n.totalNs / (double) NS_IN_MS;
|
||||
if (ms < minMs) break;
|
||||
double selfMs = selfNs(n) / (double) NS_IN_MS;
|
||||
Node hot = hottestChild(n);
|
||||
if (hot != null) {
|
||||
double hotMs = hot.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
hot.name,
|
||||
hotMs,
|
||||
n.calls
|
||||
));
|
||||
} else {
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
n.calls
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.add("ui prof tree:");
|
||||
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void appendRuntimeCounters(List<String> lines) {
|
||||
CachedUiScriptRuntime.FrameStatsSnapshot ui = CachedUiScriptRuntime.frameStatsSnapshot();
|
||||
if (ui.bakeCalls() > 0 || ui.jsRenders() > 0 || ui.layoutPasses() > 0 || ui.propPatches() > 0 || ui.boundsPatches() > 0) {
|
||||
lines.add(String.format(
|
||||
"ui runtime: bake %d, js %d, layout %d, propPatch %d/%d, boundsPatch %d/%d, blocked %d, fail %d",
|
||||
ui.bakeCalls(),
|
||||
ui.jsRenders(),
|
||||
ui.layoutPasses(),
|
||||
ui.propPatchPasses(),
|
||||
ui.propPatches(),
|
||||
ui.boundsPatchPasses(),
|
||||
ui.boundsPatches(),
|
||||
ui.blockedCalls(),
|
||||
ui.failedRenders()
|
||||
));
|
||||
}
|
||||
|
||||
TextCommandStatsSnapshot textStats = LoVisualRenderSystem.textStatsSnapshot();
|
||||
if (textStats.recorded() > 0 || textStats.meshUploads() > 0 || textStats.glyphs() > 0) {
|
||||
lines.add(String.format(
|
||||
"text: rec/sub %d/%d, backend vanilla/bitmap/msdf/world %d/%d/%d/%d, effect/clip %d/%d, glyphs %d, meshUploads %d, router hit/miss/fallback %d/%d/%d, adjacent %d, uploaded v/i %s/%s",
|
||||
textStats.recorded(),
|
||||
textStats.submitted(),
|
||||
textStats.vanilla(),
|
||||
textStats.bitmap(),
|
||||
textStats.msdf(),
|
||||
textStats.world(),
|
||||
textStats.effect(),
|
||||
textStats.clipped(),
|
||||
textStats.glyphs(),
|
||||
textStats.meshUploads(),
|
||||
textStats.routerCacheHits(),
|
||||
textStats.routerCacheMisses(),
|
||||
textStats.routerFallbackMisses(),
|
||||
textStats.adjacentBatchedCommands(),
|
||||
formatBytes(textStats.uploadedVertexBytes()),
|
||||
formatBytes(textStats.uploadedIndexBytes())
|
||||
));
|
||||
}
|
||||
var glyphStats = TextRenderSystem.glyphAtlases().stats();
|
||||
if (glyphStats.pageCount() > 0 || glyphStats.dirtyUploads() > 0) {
|
||||
lines.add(String.format(
|
||||
"glyph atlas: pages %d, glyphs %d, dirtyUploads %d, uploaded %s",
|
||||
glyphStats.pageCount(),
|
||||
glyphStats.glyphCount(),
|
||||
glyphStats.dirtyUploads(),
|
||||
formatBytes(glyphStats.uploadedBytes())
|
||||
));
|
||||
}
|
||||
|
||||
UiStatsSnapshot uiDraw = Renderer2D.getUiStatsSnapshot();
|
||||
if (uiDraw.recordedCommands() > 0 || uiDraw.compiledBatches() > 0) {
|
||||
lines.add(String.format(
|
||||
"ui commands: total %d, shape/path/tex/text/item/effect %d/%d/%d/%d/%d/%d, compiled %d, backend %d",
|
||||
uiDraw.recordedCommands(),
|
||||
uiDraw.shapeCommands(),
|
||||
uiDraw.pathCommands(),
|
||||
uiDraw.textureCommands(),
|
||||
uiDraw.textCommands(),
|
||||
uiDraw.itemCommands(),
|
||||
uiDraw.effectCommands(),
|
||||
uiDraw.compiledBatches(),
|
||||
uiDraw.backendCommands()
|
||||
));
|
||||
}
|
||||
|
||||
Renderer2D.BatchStats batch = Renderer2D.getBatchStats();
|
||||
int frameBatches = batch.getFrameBatches();
|
||||
int frameDraws = batch.getFrameDraws();
|
||||
int frameVertices = batch.getFrameVertices();
|
||||
int frameIndices = batch.getFrameIndices();
|
||||
Map<Renderer2D.FlushReason, Integer> flushReasons = batch.getFrameFlushReasons();
|
||||
if (frameBatches > 0 || frameDraws > 0 || frameVertices > 0 || frameIndices > 0 || !flushReasons.isEmpty()) {
|
||||
lines.add(String.format(
|
||||
"ui batch: batches %d, draws %d, vertices %d, indices %d, pool %d, last %d/%d/%d, flush %s %s",
|
||||
frameBatches,
|
||||
frameDraws,
|
||||
frameVertices,
|
||||
frameIndices,
|
||||
batch.getPoolTotal(),
|
||||
batch.getLastOrder(),
|
||||
batch.getLastDraws(),
|
||||
batch.getLastVertices(),
|
||||
batch.getLastFlushReason(),
|
||||
formatFlushReasons(flushReasons)
|
||||
));
|
||||
}
|
||||
if (!batch.getLastError().isEmpty()) {
|
||||
lines.add("ui batch error: " + batch.getLastError());
|
||||
}
|
||||
|
||||
MeshBuilder.FrameStatsSnapshot mesh = MeshBuilder.frameStatsSnapshot();
|
||||
if (mesh.initialAllocations() > 0 || mesh.vertexReallocs() > 0 || mesh.indexReallocs() > 0) {
|
||||
lines.add(String.format(
|
||||
"ui mesh: alloc %d, realloc v/i %d/%d, bytes %s, max v/i %s/%s",
|
||||
mesh.initialAllocations(),
|
||||
mesh.vertexReallocs(),
|
||||
mesh.indexReallocs(),
|
||||
formatBytes(mesh.allocatedBytes()),
|
||||
formatBytes(mesh.maxVertexBytes()),
|
||||
formatBytes(mesh.maxIndexBytes())
|
||||
));
|
||||
}
|
||||
|
||||
appendRhiCounters(lines);
|
||||
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
|
||||
if (immediatelyFast.modLoaded()) {
|
||||
lines.add(immediatelyFast.shortLine());
|
||||
}
|
||||
appendCostCounters(lines);
|
||||
}
|
||||
|
||||
private static String formatFlushReasons(Map<Renderer2D.FlushReason, Integer> reasons) {
|
||||
if (reasons == null || reasons.isEmpty()) return "{}";
|
||||
List<String> parts = new ArrayList<>();
|
||||
for (Map.Entry<Renderer2D.FlushReason, Integer> entry : reasons.entrySet()) {
|
||||
if (entry.getValue() != null && entry.getValue() > 0) {
|
||||
parts.add(entry.getKey().name().toLowerCase(Locale.ROOT) + "=" + entry.getValue());
|
||||
}
|
||||
}
|
||||
return parts.isEmpty() ? "{}" : "{" + String.join(",", parts) + "}";
|
||||
}
|
||||
|
||||
private static void appendCostCounters(List<String> lines) {
|
||||
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
|
||||
if (!phase.isEmpty()) lines.addAll(phase);
|
||||
List<String> runtime = DevRenderCostProfiler.debugLines("ui cost runtime", "ui.runtime", 8, 0.02);
|
||||
if (!runtime.isEmpty()) lines.addAll(runtime);
|
||||
List<String> nodes = DevRenderCostProfiler.debugLines("ui cost nodes", "ui.node", 10, 0.02);
|
||||
if (!nodes.isEmpty()) lines.addAll(nodes);
|
||||
List<String> effects = DevRenderCostProfiler.debugLines("ui cost effects", "ui.effect", 8, 0.02);
|
||||
if (!effects.isEmpty()) lines.addAll(effects);
|
||||
List<String> items = DevRenderCostProfiler.debugLines("ui cost item render", "item.render", 8, 0.02);
|
||||
if (!items.isEmpty()) lines.addAll(items);
|
||||
List<String> rhi = DevRenderCostProfiler.debugLines("ui cost rhi draws", "rhi.draw", 8, 0.02);
|
||||
if (!rhi.isEmpty()) lines.addAll(rhi);
|
||||
}
|
||||
|
||||
private static void appendRhiCounters(List<String> lines) {
|
||||
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
|
||||
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
|
||||
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|
||||
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
|
||||
rhi.drawCalls(),
|
||||
rhi.renderPasses(),
|
||||
rhi.renderPassAttachmentSwitches(),
|
||||
rhi.meshUploads(),
|
||||
rhi.fullscreenPasses(),
|
||||
rhi.textureFastCopies(),
|
||||
rhi.textureShaderCopies(),
|
||||
formatBytes(rhi.uploadedVertexBytes()),
|
||||
formatBytes(rhi.uploadedIndexBytes())
|
||||
));
|
||||
}
|
||||
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
|
||||
rhi.ringWraps(),
|
||||
rhi.ringStalls(),
|
||||
rhi.immediateFallbackUploads(),
|
||||
rhi.dynamicArenaReuses(),
|
||||
rhi.dynamicArenaRetires()
|
||||
));
|
||||
}
|
||||
if (rhi.legacyPathUses() > 0) {
|
||||
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
|
||||
}
|
||||
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
|
||||
lines.add(String.format(
|
||||
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
|
||||
uniforms.writes(),
|
||||
formatBytes(uniforms.uploadedBytes()),
|
||||
uniforms.activeStreams(),
|
||||
uniforms.ringRotations(),
|
||||
uniforms.ringGrows(),
|
||||
uniforms.staleReadMisses()
|
||||
));
|
||||
}
|
||||
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
|
||||
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|
||||
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
|
||||
lines.add(String.format(
|
||||
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
|
||||
resources.persistentFramebuffers(),
|
||||
resources.temporaryFramebuffers(),
|
||||
resources.framebufferCreates(),
|
||||
resources.framebufferResizes(),
|
||||
resources.framebufferBorrows(),
|
||||
resources.framebufferReleases(),
|
||||
resources.retirementBacklog(),
|
||||
resources.leakedResources()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
private static void collectFlat(Node node, List<Node> out) {
|
||||
for (Node child : node.children.values()) {
|
||||
out.add(child);
|
||||
collectFlat(child, out);
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
|
||||
if (node == null) return;
|
||||
double ms = node.totalNs / (double) NS_IN_MS;
|
||||
if (depth > 0 && ms < minMs) return;
|
||||
double selfMs = selfNs(node) / (double) NS_IN_MS;
|
||||
String line = depth == 0
|
||||
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
|
||||
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
|
||||
out.add(line);
|
||||
if (depth >= maxDepth) return;
|
||||
List<Node> children = new ArrayList<>(node.children.values());
|
||||
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
String childIndent = indent + "| ";
|
||||
for (Node child : children) {
|
||||
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitIfDue(long nowNs) {
|
||||
ProfilerSettings.OutputMode mode = getOutputMode();
|
||||
if (mode == ProfilerSettings.OutputMode.OFF) return;
|
||||
|
||||
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
|
||||
lastEmitNs = nowNs;
|
||||
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
emitToLog();
|
||||
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
emitToChat();
|
||||
}
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputMode() {
|
||||
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
|
||||
return getOutputModeRaw();
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputModeRaw() {
|
||||
return ProfilerSettings.getOutput2d();
|
||||
}
|
||||
|
||||
private static void emitToLog() {
|
||||
List<String> lines = getDebugLines();
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("[UIProfiler] %s", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitToChat() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
List<String> lines = getDebugLines(4, 2, 0.05);
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[UIProfiler] " + line));
|
||||
}
|
||||
}
|
||||
|
||||
private static long selfNs(Node node) {
|
||||
if (node == null) return 0L;
|
||||
long childrenNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
childrenNs += child.totalNs;
|
||||
}
|
||||
long self = node.totalNs - childrenNs;
|
||||
return Math.max(0L, self);
|
||||
}
|
||||
|
||||
private static Node hottestChild(Node node) {
|
||||
if (node == null || node.children.isEmpty()) return null;
|
||||
Node best = null;
|
||||
long bestNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
if (best == null || child.totalNs > bestNs) {
|
||||
best = child;
|
||||
bestNs = child.totalNs;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static String nodePath(Node node) {
|
||||
if (node == null) return "";
|
||||
List<String> parts = new ArrayList<>();
|
||||
Node cur = node;
|
||||
while (cur != null) {
|
||||
parts.add(cur.name);
|
||||
cur = cur.parent;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = parts.size() - 1; i >= 0; i--) {
|
||||
if (sb.length() > 0) sb.append(" > ");
|
||||
sb.append(parts.get(i));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static final class Section implements AutoCloseable {
|
||||
private static final Section NOOP = new Section(false);
|
||||
private final boolean active;
|
||||
|
||||
private Section(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!active) return;
|
||||
endSection();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Node {
|
||||
final String name;
|
||||
final Node parent;
|
||||
final Map<String, Node> children = new HashMap<>();
|
||||
long totalNs;
|
||||
long startNs;
|
||||
int calls;
|
||||
|
||||
private Node(String name, Node parent) {
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
int countNodes() {
|
||||
int count = 1;
|
||||
for (Node child : children.values()) {
|
||||
count += child.countNodes();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,420 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import dev.loki.lovisual.render.engine.core.LoVisualRenderSystem;
|
||||
import dev.loki.lovisual.render.engine.rhi.RhiStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.resource.RenderResourceStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.rhi.uniform.UniformAllocatorStatsSnapshot;
|
||||
import dev.loki.lovisual.render.engine.world.WorldRenderStatsSnapshot;
|
||||
import dev.loki.lovisual.render.iris.IrisRuntimeSnapshot;
|
||||
import dev.loki.lovisual.render.sodium.SodiumTerrainInteropStatsSnapshot;
|
||||
import dev.loki.lovisual.render.sodium.SodiumVisibilityStatsSnapshot;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public enum DevRenderProfiler3D {
|
||||
;
|
||||
|
||||
private static final long NS_IN_MS = 1_000_000L;
|
||||
private static final int DEFAULT_TOP_LIMIT = 6;
|
||||
private static final int DEFAULT_TREE_DEPTH = 32;
|
||||
private static final double DEFAULT_MIN_MS = 0.0;
|
||||
private static final long DEFAULT_EMIT_INTERVAL_NS = 1_000_000_000L;
|
||||
private static final ArrayDeque<Node> stack = new ArrayDeque<>();
|
||||
private static boolean active;
|
||||
private static Node root;
|
||||
private static Node snapshot;
|
||||
private static long lastEmitNs;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static void beginFrame(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
|
||||
if (!isEnabled()) return;
|
||||
active = true;
|
||||
root = new Node(name, null);
|
||||
stack.clear();
|
||||
stack.push(root);
|
||||
root.startNs = System.nanoTime();
|
||||
}
|
||||
|
||||
public static boolean beginFrameIfNeeded(String name) {
|
||||
DevSamplingProfiler.onClientFrame(DevSamplingProfiler.Target.WORLD);
|
||||
if (!isEnabled() || active) return false;
|
||||
beginFrame(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (!isEnabled() || !active) return;
|
||||
long now = System.nanoTime();
|
||||
while (stack.size() > 1) {
|
||||
endSection();
|
||||
}
|
||||
Node r = stack.peek();
|
||||
if (r != null) {
|
||||
r.calls = Math.max(1, r.calls);
|
||||
r.totalNs += now - r.startNs;
|
||||
r.startNs = 0L;
|
||||
snapshot = r;
|
||||
DevTracyProfiler.plotWorldFrame(r.totalNs / (double) NS_IN_MS, r.countNodes());
|
||||
}
|
||||
active = false;
|
||||
emitIfDue(now);
|
||||
}
|
||||
|
||||
public static Section section(String name) {
|
||||
if (!isEnabled() || !active) return Section.NOOP;
|
||||
beginSection(name);
|
||||
return new Section(true);
|
||||
}
|
||||
|
||||
private static void beginSection(String name) {
|
||||
Node parent = stack.peek();
|
||||
if (parent == null) return;
|
||||
Node child = parent.children.computeIfAbsent(name, n -> new Node(n, parent));
|
||||
child.calls += 1;
|
||||
child.startNs = System.nanoTime();
|
||||
stack.push(child);
|
||||
}
|
||||
|
||||
private static void endSection() {
|
||||
Node node = stack.poll();
|
||||
if (node == null) return;
|
||||
long now = System.nanoTime();
|
||||
node.totalNs += now - node.startNs;
|
||||
node.startNs = 0L;
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines() {
|
||||
return getDebugLines(DEFAULT_TOP_LIMIT, DEFAULT_TREE_DEPTH, DEFAULT_MIN_MS);
|
||||
}
|
||||
|
||||
public static List<String> getDebugLines(int topLimit, int depthLimit, double minMs) {
|
||||
if (!isEnabled()) return List.of();
|
||||
Node snap = snapshot;
|
||||
if (snap == null) return List.of();
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
double totalMs = snap.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format("world prof: %.2f ms, nodes %d", totalMs, snap.countNodes()));
|
||||
appendRhiCounters(lines);
|
||||
appendCostCounters(lines);
|
||||
|
||||
List<Node> flat = new ArrayList<>();
|
||||
collectFlat(snap, flat);
|
||||
flat.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
|
||||
int top = Math.min(topLimit, flat.size());
|
||||
if (top > 0) {
|
||||
lines.add("world prof top:");
|
||||
for (int i = 0; i < top; i++) {
|
||||
Node n = flat.get(i);
|
||||
double ms = n.totalNs / (double) NS_IN_MS;
|
||||
if (ms < minMs) break;
|
||||
double selfMs = selfNs(n) / (double) NS_IN_MS;
|
||||
Node hot = hottestChild(n);
|
||||
if (hot != null) {
|
||||
double hotMs = hot.totalNs / (double) NS_IN_MS;
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, hot %s %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
hot.name,
|
||||
hotMs,
|
||||
n.calls
|
||||
));
|
||||
} else {
|
||||
lines.add(String.format(
|
||||
" %d) %s %.2f ms (self %.2f, %d)",
|
||||
i + 1,
|
||||
nodePath(n),
|
||||
ms,
|
||||
selfMs,
|
||||
n.calls
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.add("world prof tree:");
|
||||
appendTreeAscii(lines, snap, "", 0, depthLimit, minMs);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void appendCostCounters(List<String> lines) {
|
||||
List<String> phase = DevRenderCostProfiler.debugLines("render cost phases", "phase", 6, 0.02);
|
||||
if (!phase.isEmpty()) lines.addAll(phase);
|
||||
List<String> post = DevRenderCostProfiler.debugLines("world cost post", "post.pass", 8, 0.02);
|
||||
if (!post.isEmpty()) lines.addAll(post);
|
||||
List<String> effects = DevRenderCostProfiler.debugLines("world cost effects", "world.effect", 8, 0.02);
|
||||
if (!effects.isEmpty()) lines.addAll(effects);
|
||||
List<String> rhi = DevRenderCostProfiler.debugLines("world cost rhi draws", "rhi.draw", 8, 0.02);
|
||||
if (!rhi.isEmpty()) lines.addAll(rhi);
|
||||
}
|
||||
|
||||
private static void appendRhiCounters(List<String> lines) {
|
||||
RhiStatsSnapshot rhi = LoVisualRenderSystem.rhiStatsSnapshot();
|
||||
UniformAllocatorStatsSnapshot uniforms = LoVisualRenderSystem.uniformStatsSnapshot();
|
||||
if (rhi.drawCalls() > 0 || rhi.renderPasses() > 0 || rhi.meshUploads() > 0 || rhi.fullscreenPasses() > 0
|
||||
|| rhi.textureFastCopies() > 0 || rhi.textureShaderCopies() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi: draws %d, passes/switches %d/%d, meshUploads %d, fullscreen %d, copies fast/shader %d/%d, uploaded v/i %s/%s",
|
||||
rhi.drawCalls(),
|
||||
rhi.renderPasses(),
|
||||
rhi.renderPassAttachmentSwitches(),
|
||||
rhi.meshUploads(),
|
||||
rhi.fullscreenPasses(),
|
||||
rhi.textureFastCopies(),
|
||||
rhi.textureShaderCopies(),
|
||||
formatBytes(rhi.uploadedVertexBytes()),
|
||||
formatBytes(rhi.uploadedIndexBytes())
|
||||
));
|
||||
}
|
||||
WorldRenderStatsSnapshot world = LoVisualRenderSystem.worldRenderStatsSnapshot();
|
||||
if (world.recordedCommands() > 0 || world.submittedCommands() > 0 || world.skippedEmptyCommands() > 0) {
|
||||
lines.add(String.format(
|
||||
"world3d: commands rec/sub/skip %d/%d/%d, vertices/indices %d/%d, fog %d, depth pre/main/none %d/%d/%d",
|
||||
world.recordedCommands(),
|
||||
world.submittedCommands(),
|
||||
world.skippedEmptyCommands(),
|
||||
world.submittedVertices(),
|
||||
world.submittedIndices(),
|
||||
world.fogBindings(),
|
||||
world.depthPrePassBindings(),
|
||||
world.depthMainBindings(),
|
||||
world.depthDisabledBindings()
|
||||
));
|
||||
}
|
||||
|
||||
if (rhi.ringWraps() > 0 || rhi.ringStalls() > 0 || rhi.immediateFallbackUploads() > 0) {
|
||||
lines.add(String.format(
|
||||
"rhi upload: wraps %d, stalls %d, immediateFallback %d, arena reuse/retire %d/%d",
|
||||
rhi.ringWraps(),
|
||||
rhi.ringStalls(),
|
||||
rhi.immediateFallbackUploads(),
|
||||
rhi.dynamicArenaReuses(),
|
||||
rhi.dynamicArenaRetires()
|
||||
));
|
||||
}
|
||||
if (rhi.legacyPathUses() > 0) {
|
||||
lines.add("rhi legacy paths: " + rhi.legacyPathUses() + " " + rhi.legacyPathBreakdown());
|
||||
}
|
||||
if (uniforms.writes() > 0 || uniforms.ringRotations() > 0 || uniforms.staleReadMisses() > 0) {
|
||||
lines.add(String.format(
|
||||
"uniforms: writes %d, bytes %s, activeStreams %d, rotations %d, grows %d, staleMiss %d",
|
||||
uniforms.writes(),
|
||||
formatBytes(uniforms.uploadedBytes()),
|
||||
uniforms.activeStreams(),
|
||||
uniforms.ringRotations(),
|
||||
uniforms.ringGrows(),
|
||||
uniforms.staleReadMisses()
|
||||
));
|
||||
}
|
||||
RenderResourceStatsSnapshot resources = LoVisualRenderSystem.resourceStatsSnapshot();
|
||||
if (resources.persistentFramebuffers() > 0 || resources.temporaryFramebuffers() > 0
|
||||
|| resources.retirementBacklog() > 0 || resources.leakedResources() > 0) {
|
||||
lines.add(String.format(
|
||||
"resources: fb persistent/temp %d/%d, create/resize %d/%d, borrow/release %d/%d, retire backlog/leaks %d/%d",
|
||||
resources.persistentFramebuffers(),
|
||||
resources.temporaryFramebuffers(),
|
||||
resources.framebufferCreates(),
|
||||
resources.framebufferResizes(),
|
||||
resources.framebufferBorrows(),
|
||||
resources.framebufferReleases(),
|
||||
resources.retirementBacklog(),
|
||||
resources.leakedResources()
|
||||
));
|
||||
}
|
||||
|
||||
IrisRuntimeSnapshot iris = LoVisualRenderSystem.irisSnapshot();
|
||||
if (iris.modLoaded() || iris.shaderpackInUse()) {
|
||||
lines.add(iris.shortLine());
|
||||
}
|
||||
|
||||
var immediatelyFast = LoVisualRenderSystem.immediatelyFastSnapshot();
|
||||
if (immediatelyFast.modLoaded()) {
|
||||
lines.add(immediatelyFast.shortLine());
|
||||
}
|
||||
|
||||
SodiumVisibilityStatsSnapshot sodiumVisibility = LoVisualRenderSystem.sodiumVisibilityStatsSnapshot();
|
||||
if (sodiumVisibility.queries() > 0 || sodiumVisibility.errors() > 0) {
|
||||
lines.add(String.format(
|
||||
"sodium vis: queries %d, accepts/rejects %d/%d, bypass %d (unavail %d, optout %d), errors %d",
|
||||
sodiumVisibility.queries(),
|
||||
sodiumVisibility.accepts(),
|
||||
sodiumVisibility.rejects(),
|
||||
sodiumVisibility.bypasses(),
|
||||
sodiumVisibility.unavailableBypasses(),
|
||||
sodiumVisibility.optOutBypasses(),
|
||||
sodiumVisibility.errors()
|
||||
));
|
||||
}
|
||||
|
||||
SodiumTerrainInteropStatsSnapshot sodiumTerrain = LoVisualRenderSystem.sodiumTerrainStatsSnapshot();
|
||||
if (sodiumTerrain.terrainUpdatesScheduled() > 0
|
||||
|| sodiumTerrain.rebuildsScheduled() > 0
|
||||
|| sodiumTerrain.interopErrors() > 0) {
|
||||
lines.add(String.format(
|
||||
"sodium terrain: updates %d, rebuilds %d, errors %d",
|
||||
sodiumTerrain.terrainUpdatesScheduled(),
|
||||
sodiumTerrain.rebuildsScheduled(),
|
||||
sodiumTerrain.interopErrors()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatBytes(long bytes) {
|
||||
if (bytes < 1024L) return bytes + " B";
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024.0) return String.format(Locale.ROOT, "%.1f KiB", kb);
|
||||
return String.format(Locale.ROOT, "%.2f MiB", kb / 1024.0);
|
||||
}
|
||||
|
||||
private static void collectFlat(Node node, List<Node> out) {
|
||||
for (Node child : node.children.values()) {
|
||||
out.add(child);
|
||||
collectFlat(child, out);
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendTreeAscii(List<String> out, Node node, String indent, int depth, int maxDepth, double minMs) {
|
||||
if (node == null) return;
|
||||
double ms = node.totalNs / (double) NS_IN_MS;
|
||||
if (depth > 0 && ms < minMs) return;
|
||||
double selfMs = selfNs(node) / (double) NS_IN_MS;
|
||||
String line = depth == 0
|
||||
? String.format("%s %.2f ms (self %.2f, %d)", node.name, ms, selfMs, node.calls)
|
||||
: String.format("%s|-- %s %.2f ms (self %.2f, %d)", indent, node.name, ms, selfMs, node.calls);
|
||||
out.add(line);
|
||||
if (depth >= maxDepth) return;
|
||||
List<Node> children = new ArrayList<>(node.children.values());
|
||||
children.sort(Comparator.comparingLong((Node n) -> n.totalNs).reversed());
|
||||
String childIndent = indent + "| ";
|
||||
for (Node child : children) {
|
||||
appendTreeAscii(out, child, childIndent, depth + 1, maxDepth, minMs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitIfDue(long nowNs) {
|
||||
ProfilerSettings.OutputMode mode = getOutputMode();
|
||||
if (mode == ProfilerSettings.OutputMode.OFF) return;
|
||||
|
||||
if (nowNs - lastEmitNs < DEFAULT_EMIT_INTERVAL_NS) return;
|
||||
lastEmitNs = nowNs;
|
||||
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
emitToLog();
|
||||
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
emitToChat();
|
||||
}
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputMode() {
|
||||
if (!isEnabled()) return ProfilerSettings.OutputMode.OFF;
|
||||
return getOutputModeRaw();
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputModeRaw() {
|
||||
return ProfilerSettings.getOutput3d();
|
||||
}
|
||||
|
||||
private static void emitToLog() {
|
||||
List<String> lines = getDebugLines();
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("[WorldProfiler] %s", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitToChat() {
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
List<String> lines = getDebugLines(4, 2, 0.05);
|
||||
if (lines.isEmpty()) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[WorldProfiler] " + line));
|
||||
}
|
||||
}
|
||||
|
||||
private static long selfNs(Node node) {
|
||||
if (node == null) return 0L;
|
||||
long childrenNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
childrenNs += child.totalNs;
|
||||
}
|
||||
long self = node.totalNs - childrenNs;
|
||||
return Math.max(0L, self);
|
||||
}
|
||||
|
||||
private static Node hottestChild(Node node) {
|
||||
if (node == null || node.children.isEmpty()) return null;
|
||||
Node best = null;
|
||||
long bestNs = 0L;
|
||||
for (Node child : node.children.values()) {
|
||||
if (best == null || child.totalNs > bestNs) {
|
||||
best = child;
|
||||
bestNs = child.totalNs;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static String nodePath(Node node) {
|
||||
if (node == null) return "";
|
||||
List<String> parts = new ArrayList<>();
|
||||
Node cur = node;
|
||||
while (cur != null) {
|
||||
parts.add(cur.name);
|
||||
cur = cur.parent;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = parts.size() - 1; i >= 0; i--) {
|
||||
if (sb.length() > 0) sb.append(" > ");
|
||||
sb.append(parts.get(i));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static final class Section implements AutoCloseable {
|
||||
private static final Section NOOP = new Section(false);
|
||||
private final boolean active;
|
||||
|
||||
private Section(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (!active) return;
|
||||
endSection();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Node {
|
||||
final String name;
|
||||
final Node parent;
|
||||
final Map<String, Node> children = new HashMap<>();
|
||||
long totalNs;
|
||||
long startNs;
|
||||
int calls;
|
||||
|
||||
private Node(String name, Node parent) {
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
int countNodes() {
|
||||
int count = 1;
|
||||
for (Node child : children.values()) {
|
||||
count += child.countNodes();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,442 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public enum DevSamplingProfiler {
|
||||
;
|
||||
|
||||
private static final long SAMPLE_INTERVAL_NS = 10_000_000L; // 10 ms
|
||||
private static final long EMIT_INTERVAL_NS = 1_000_000_000L; // 1 s
|
||||
private static final int TOP_LIMIT = 8;
|
||||
private static final int TOP_LIMIT_NON_GL = 4;
|
||||
private static final int TOP_LIMIT_GL_WAIT = 3;
|
||||
private static final int MAX_STACK_FRAMES = 4;
|
||||
private static final int MAX_ENTRIES = 256;
|
||||
|
||||
private static final Object LOCK = new Object();
|
||||
private static final Map<String, Integer> COUNTS = new HashMap<>();
|
||||
private static int idleSamples;
|
||||
|
||||
private static volatile Thread targetThread;
|
||||
private static volatile Thread samplerThread;
|
||||
private static volatile boolean running;
|
||||
private static volatile long lastEmitNs;
|
||||
private static volatile List<String> pendingChatLines;
|
||||
private static volatile Target lastSource = Target.WORLD;
|
||||
|
||||
public static void onClientFrame(Target source) {
|
||||
if (!isEnabled()) {
|
||||
DevProfilerPhase.clearCurrent();
|
||||
stopIfRunning();
|
||||
return;
|
||||
}
|
||||
|
||||
lastSource = source;
|
||||
flushPendingChat();
|
||||
if (!matchesTarget(source)) return;
|
||||
targetThread = Thread.currentThread();
|
||||
ensureRunning();
|
||||
}
|
||||
|
||||
private static boolean isEnabled() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
public static boolean isActive() {
|
||||
return getOutputModeRaw() != ProfilerSettings.OutputMode.OFF;
|
||||
}
|
||||
|
||||
private static void ensureRunning() {
|
||||
if (running) return;
|
||||
running = true;
|
||||
samplerThread = new Thread(DevSamplingProfiler::runLoop, "LoVisual-DevSamplingProfiler");
|
||||
samplerThread.setDaemon(true);
|
||||
samplerThread.start();
|
||||
}
|
||||
|
||||
private static void stopIfRunning() {
|
||||
if (!running) return;
|
||||
running = false;
|
||||
Thread t = samplerThread;
|
||||
samplerThread = null;
|
||||
if (t != null) t.interrupt();
|
||||
synchronized (LOCK) {
|
||||
COUNTS.clear();
|
||||
idleSamples = 0;
|
||||
}
|
||||
DevGlSyncTracker.reset();
|
||||
pendingChatLines = null;
|
||||
}
|
||||
|
||||
private static void runLoop() {
|
||||
long lastSampleNs = 0L;
|
||||
while (running) {
|
||||
if (!isEnabled()) {
|
||||
running = false;
|
||||
synchronized (LOCK) {
|
||||
COUNTS.clear();
|
||||
idleSamples = 0;
|
||||
}
|
||||
DevGlSyncTracker.reset();
|
||||
pendingChatLines = null;
|
||||
break;
|
||||
}
|
||||
Thread t = targetThread;
|
||||
if (t == null) {
|
||||
sleepMs(10);
|
||||
continue;
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
if (now - lastSampleNs >= SAMPLE_INTERVAL_NS) {
|
||||
if (matchesTarget(lastSource)) {
|
||||
sample(t);
|
||||
}
|
||||
lastSampleNs = now;
|
||||
}
|
||||
if (now - lastEmitNs >= EMIT_INTERVAL_NS) {
|
||||
emit(now);
|
||||
}
|
||||
sleepMs(2);
|
||||
}
|
||||
}
|
||||
|
||||
private static void sample(Thread t) {
|
||||
StackTraceElement[] stack = t.getStackTrace();
|
||||
if (stack == null || stack.length == 0) return;
|
||||
if (isIdleStack(stack)) {
|
||||
synchronized (LOCK) {
|
||||
idleSamples += 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
String key = buildKey(stack);
|
||||
if (key == null || key.isEmpty()) return;
|
||||
synchronized (LOCK) {
|
||||
COUNTS.merge(key, 1, Integer::sum);
|
||||
if (COUNTS.size() > MAX_ENTRIES) {
|
||||
trimToLimit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void emit(long now) {
|
||||
ProfilerSettings.OutputMode mode = getOutputModeRaw();
|
||||
if (mode == ProfilerSettings.OutputMode.OFF) return;
|
||||
List<String> lines = buildOutputLines();
|
||||
if (lines.isEmpty()) return;
|
||||
lastEmitNs = now;
|
||||
|
||||
if (mode == ProfilerSettings.OutputMode.LOG) {
|
||||
for (String line : lines) {
|
||||
ProfilerLog.info("[SampleProfiler] %s", line);
|
||||
}
|
||||
} else if (mode == ProfilerSettings.OutputMode.CHAT) {
|
||||
pendingChatLines = lines;
|
||||
}
|
||||
|
||||
synchronized (LOCK) {
|
||||
COUNTS.clear();
|
||||
idleSamples = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> buildOutputLines() {
|
||||
List<Map.Entry<String, Integer>> entries;
|
||||
int total;
|
||||
int idle;
|
||||
synchronized (LOCK) {
|
||||
if (COUNTS.isEmpty() && idleSamples == 0) return List.of();
|
||||
entries = new ArrayList<>(COUNTS.entrySet());
|
||||
int sum = 0;
|
||||
for (Integer count : COUNTS.values()) {
|
||||
if (count != null) {
|
||||
sum += count;
|
||||
}
|
||||
}
|
||||
total = sum;
|
||||
idle = idleSamples;
|
||||
}
|
||||
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
|
||||
List<String> lines = new ArrayList<>();
|
||||
int all = total + idle;
|
||||
double idlePct = all == 0 ? 0.0 : (idle * 100.0) / all;
|
||||
lines.add(String.format("sample prof: %d samples, idle %d (%.1f%%), entries %d", all, idle, idlePct, entries.size()));
|
||||
|
||||
int glWait = 0;
|
||||
int glUpload = 0;
|
||||
int glDraw = 0;
|
||||
int glState = 0;
|
||||
int glWaitClient = 0;
|
||||
int glWaitSwap = 0;
|
||||
int glWaitFinish = 0;
|
||||
int glWaitSync = 0;
|
||||
int glWaitOther = 0;
|
||||
|
||||
List<Map.Entry<String, Integer>> nonGl = new ArrayList<>();
|
||||
List<Map.Entry<String, Integer>> glWaitList = new ArrayList<>();
|
||||
for (Map.Entry<String, Integer> e : entries) {
|
||||
String k = e.getKey();
|
||||
int c = e.getValue();
|
||||
if (k.startsWith("GL WAIT:")) {
|
||||
glWait += c;
|
||||
glWaitList.add(e);
|
||||
if (containsAny(k, "glClientWaitSync", "nglClientWaitSync")) {
|
||||
glWaitClient += c;
|
||||
} else if (containsAny(k, "glfwSwapBuffers")) {
|
||||
glWaitSwap += c;
|
||||
} else if (containsAny(k, "glFinish", "nglFinish")) {
|
||||
glWaitFinish += c;
|
||||
} else if (containsAny(k, "glWaitSync", "nglWaitSync")) {
|
||||
glWaitSync += c;
|
||||
} else {
|
||||
glWaitOther += c;
|
||||
}
|
||||
} else if (k.startsWith("GL UPLOAD:")) {
|
||||
glUpload += c;
|
||||
} else if (k.startsWith("GL DRAW:")) {
|
||||
glDraw += c;
|
||||
} else if (k.startsWith("GL STATE:")) {
|
||||
glState += c;
|
||||
} else {
|
||||
nonGl.add(e);
|
||||
}
|
||||
}
|
||||
int glTotal = glWait + glUpload + glDraw + glState;
|
||||
if (glTotal > 0) {
|
||||
double waitPct = all == 0 ? 0.0 : (glWait * 100.0) / all;
|
||||
double uploadPct = all == 0 ? 0.0 : (glUpload * 100.0) / all;
|
||||
double drawPct = all == 0 ? 0.0 : (glDraw * 100.0) / all;
|
||||
double statePct = all == 0 ? 0.0 : (glState * 100.0) / all;
|
||||
lines.add(String.format(
|
||||
"gl samples: wait %d (%.1f%%), upload %d (%.1f%%), draw %d (%.1f%%), state %d (%.1f%%)",
|
||||
glWait, waitPct, glUpload, uploadPct, glDraw, drawPct, glState, statePct
|
||||
));
|
||||
if (glWait > 0) {
|
||||
lines.add(String.format(
|
||||
"gl wait breakdown: client %d, swap %d, finish %d, waitsync %d, other %d",
|
||||
glWaitClient, glWaitSwap, glWaitFinish, glWaitSync, glWaitOther
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> waitPhaseLines = DevGlSyncTracker.drainLines();
|
||||
if (!waitPhaseLines.isEmpty()) {
|
||||
lines.addAll(waitPhaseLines);
|
||||
}
|
||||
lines.add("sample prof top:");
|
||||
|
||||
int top = Math.min(TOP_LIMIT, entries.size());
|
||||
for (int i = 0; i < top; i++) {
|
||||
Map.Entry<String, Integer> e = entries.get(i);
|
||||
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
|
||||
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
|
||||
}
|
||||
|
||||
if (!nonGl.isEmpty()) {
|
||||
int topNon = Math.min(TOP_LIMIT_NON_GL, nonGl.size());
|
||||
lines.add("sample prof top non-gl:");
|
||||
for (int i = 0; i < topNon; i++) {
|
||||
Map.Entry<String, Integer> e = nonGl.get(i);
|
||||
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
|
||||
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
|
||||
}
|
||||
}
|
||||
|
||||
if (!glWaitList.isEmpty()) {
|
||||
int topWait = Math.min(TOP_LIMIT_GL_WAIT, glWaitList.size());
|
||||
lines.add("sample prof top gl wait:");
|
||||
for (int i = 0; i < topWait; i++) {
|
||||
Map.Entry<String, Integer> e = glWaitList.get(i);
|
||||
double pct = all == 0 ? 0.0 : (e.getValue() * 100.0) / all;
|
||||
lines.add(String.format(" %d) %s (%d, %.1f%%)", i + 1, e.getKey(), e.getValue(), pct));
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void flushPendingChat() {
|
||||
List<String> lines = pendingChatLines;
|
||||
if (lines == null || lines.isEmpty()) return;
|
||||
pendingChatLines = null;
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
if (mc == null || mc.gui == null) return;
|
||||
for (String line : lines) {
|
||||
mc.gui.hud.getChat().addClientSystemMessage(Component.literal("[SampleProfiler] " + line));
|
||||
}
|
||||
}
|
||||
|
||||
private static String buildKey(StackTraceElement[] stack) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String glCat = glCategory(stack);
|
||||
boolean hasPrefix = false;
|
||||
if (glCat != null) {
|
||||
sb.append("GL ").append(glCat).append(": ");
|
||||
hasPrefix = true;
|
||||
}
|
||||
int added = 0;
|
||||
for (StackTraceElement e : stack) {
|
||||
if (added >= MAX_STACK_FRAMES) break;
|
||||
if (isNoise(e)) continue;
|
||||
if (added > 0 || (sb.length() > 0 && !hasPrefix)) sb.append(" <= ");
|
||||
sb.append(formatElement(e));
|
||||
added++;
|
||||
}
|
||||
return added == 0 ? null : sb.toString();
|
||||
}
|
||||
|
||||
private static boolean isNoise(StackTraceElement e) {
|
||||
String cls = e.getClassName();
|
||||
return cls.startsWith("java.lang.Thread")
|
||||
|| cls.startsWith("java.util.concurrent")
|
||||
|| cls.startsWith("jdk.internal")
|
||||
|| cls.startsWith("sun.")
|
||||
|| cls.startsWith("dev.loki.lovisual.render.engine.profiler.DevSamplingProfiler");
|
||||
}
|
||||
|
||||
private static String glCategory(StackTraceElement[] stack) {
|
||||
for (StackTraceElement e : stack) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
if (!isGlFrame(cls)) continue;
|
||||
String cat = glCategoryForMethod(method);
|
||||
if (cat != null) return cat;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isGlFrame(String cls) {
|
||||
if (cls == null) return false;
|
||||
return cls.startsWith("org.lwjgl.opengl.")
|
||||
|| cls.startsWith("org.lwjgl.glfw.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.platform.")
|
||||
|| cls.startsWith("com.mojang.blaze3d.systems.");
|
||||
}
|
||||
|
||||
private static String glCategoryForMethod(String method) {
|
||||
if (method == null) return null;
|
||||
if (method.equals("glfwSwapBuffers")
|
||||
|| method.equals("glClientWaitSync")
|
||||
|| method.equals("glWaitSync")
|
||||
|| method.equals("glFinish")) {
|
||||
return "WAIT";
|
||||
}
|
||||
if (method.startsWith("glDraw") || method.startsWith("glMultiDraw")) {
|
||||
return "DRAW";
|
||||
}
|
||||
if (method.contains("BufferSubData")
|
||||
|| method.contains("BufferData")
|
||||
|| method.contains("TexImage")
|
||||
|| method.contains("TexSubImage")
|
||||
|| method.contains("CompressedTex")
|
||||
|| method.contains("FlushMapped")
|
||||
|| method.contains("MapBuffer")
|
||||
|| method.contains("MapBufferRange")
|
||||
|| method.contains("UnmapBuffer")) {
|
||||
return "UPLOAD";
|
||||
}
|
||||
if (method.startsWith("glUseProgram")
|
||||
|| method.startsWith("glBind")
|
||||
|| method.startsWith("glTexParameter")
|
||||
|| method.startsWith("glBlendFunc")
|
||||
|| method.startsWith("glBlendEquation")
|
||||
|| method.startsWith("glEnable")
|
||||
|| method.startsWith("glDisable")
|
||||
|| method.startsWith("glDepthFunc")
|
||||
|| method.startsWith("glDepthMask")
|
||||
|| method.startsWith("glColorMask")
|
||||
|| method.startsWith("glCullFace")
|
||||
|| method.startsWith("glFrontFace")
|
||||
|| method.startsWith("glViewport")
|
||||
|| method.startsWith("glScissor")
|
||||
|| method.startsWith("glPolygonMode")
|
||||
|| method.startsWith("glActiveTexture")
|
||||
|| method.startsWith("glUniform")
|
||||
|| method.startsWith("glVertexAttrib")) {
|
||||
return "STATE";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean containsAny(String text, String... needles) {
|
||||
if (text == null) return false;
|
||||
for (String n : needles) {
|
||||
if (n != null && !n.isEmpty() && text.contains(n)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isIdleStack(StackTraceElement[] stack) {
|
||||
boolean hasWait = false;
|
||||
boolean hasLimit = false;
|
||||
for (StackTraceElement e : stack) {
|
||||
String cls = e.getClassName();
|
||||
String method = e.getMethodName();
|
||||
if ("org.lwjgl.glfw.GLFW".equals(cls) && "glfwWaitEventsTimeout".equals(method)) {
|
||||
hasWait = true;
|
||||
}
|
||||
if ("com.mojang.blaze3d.systems.RenderSystem".equals(cls) && "limitDisplayFPS".equals(method)) {
|
||||
hasLimit = true;
|
||||
}
|
||||
if (hasWait || hasLimit) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String formatElement(StackTraceElement e) {
|
||||
String file = e.getFileName() == null ? "Unknown" : e.getFileName();
|
||||
int line = e.getLineNumber();
|
||||
return e.getClassName() + "." + e.getMethodName() + "(" + file + ":" + line + ")";
|
||||
}
|
||||
|
||||
private static boolean matchesTarget(Target source) {
|
||||
if (source == null) return true;
|
||||
Target target = getTargetRaw();
|
||||
return target == Target.ALL || target == source;
|
||||
}
|
||||
|
||||
private static Target getTargetRaw() {
|
||||
ProfilerSettings.SampleTarget target = ProfilerSettings.getSampleTarget();
|
||||
if (target == null) return Target.ALL;
|
||||
return switch (target) {
|
||||
case D2 -> Target.UI;
|
||||
case D3 -> Target.WORLD;
|
||||
case ALL -> Target.ALL;
|
||||
};
|
||||
}
|
||||
|
||||
private static void trimToLimit() {
|
||||
if (COUNTS.size() <= MAX_ENTRIES) return;
|
||||
List<Map.Entry<String, Integer>> entries = new ArrayList<>(COUNTS.entrySet());
|
||||
entries.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
|
||||
for (int i = MAX_ENTRIES; i < entries.size(); i++) {
|
||||
COUNTS.remove(entries.get(i).getKey());
|
||||
}
|
||||
}
|
||||
|
||||
private static ProfilerSettings.OutputMode getOutputModeRaw() {
|
||||
return ProfilerSettings.getSampleOutput();
|
||||
}
|
||||
|
||||
private static void sleepMs(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public enum Target {
|
||||
ALL,
|
||||
UI,
|
||||
WORLD
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,230 @@
|
|||
package dev.loki.lovisual.render.engine.profiler;
|
||||
|
||||
import com.mojang.jtracy.Plot;
|
||||
import com.mojang.jtracy.TracyClient;
|
||||
import com.mojang.jtracy.Zone;
|
||||
|
||||
public enum DevTracyProfiler {
|
||||
;
|
||||
|
||||
private static final Scope NOOP_SCOPE = new Scope(null);
|
||||
private static final ThreadLocal<Boolean> THREAD_NAMED =
|
||||
ThreadLocal.withInitial(() -> Boolean.FALSE);
|
||||
|
||||
private static volatile boolean loadAttempted;
|
||||
private static volatile boolean available;
|
||||
private static volatile Plot uiFrameMsPlot;
|
||||
private static volatile Plot uiNodeCountPlot;
|
||||
private static volatile Plot worldFrameMsPlot;
|
||||
private static volatile Plot worldNodeCountPlot;
|
||||
private static volatile Plot glWaitMsPlot;
|
||||
private static volatile Plot glWaitCallsPlot;
|
||||
private static volatile Plot uiBatchDrawsPlot;
|
||||
private static volatile Plot uiBatchVerticesPlot;
|
||||
|
||||
public static boolean isEnabled() {
|
||||
return ProfilerSettings.isTracyEnabled() && isAvailable();
|
||||
}
|
||||
|
||||
public static boolean isAvailable() {
|
||||
ensureLoaded();
|
||||
return available;
|
||||
}
|
||||
|
||||
public static synchronized boolean setEnabled(boolean enabled) {
|
||||
ProfilerSettings.setTracyEnabled(enabled);
|
||||
if (!enabled) {
|
||||
ProfilerLog.info("Tracy disabled");
|
||||
return false;
|
||||
}
|
||||
boolean active = isAvailable();
|
||||
if (active) {
|
||||
ProfilerLog.info("Tracy enabled; data is streamed to the external Tracy viewer, not latest.log");
|
||||
TracyClient.message("LoVisual Tracy enabled");
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
public static Scope beginZone(String name) {
|
||||
if (!isEnabled() || name == null || name.isBlank()) {
|
||||
return NOOP_SCOPE;
|
||||
}
|
||||
ensureThreadNamed();
|
||||
return new Scope(TracyClient.beginZone(name, false));
|
||||
}
|
||||
|
||||
public static void markFrame() {
|
||||
if (!isEnabled()) return;
|
||||
ensureThreadNamed();
|
||||
TracyClient.markFrame();
|
||||
}
|
||||
|
||||
public static boolean shouldTraceCurrentThread() {
|
||||
String threadName = Thread.currentThread().getName();
|
||||
if (threadName == null || threadName.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
return "Render thread".equals(threadName)
|
||||
|| threadName.startsWith("Render thread")
|
||||
|| "main".equals(threadName)
|
||||
|| "Main thread".equals(threadName);
|
||||
}
|
||||
|
||||
public static void plotUiFrame(double ms, int nodes) {
|
||||
if (!isEnabled()) return;
|
||||
plotUiFrameMs().setValue(ms);
|
||||
plotUiNodeCount().setValue(nodes);
|
||||
}
|
||||
|
||||
public static void plotWorldFrame(double ms, int nodes) {
|
||||
if (!isEnabled()) return;
|
||||
plotWorldFrameMs().setValue(ms);
|
||||
plotWorldNodeCount().setValue(nodes);
|
||||
}
|
||||
|
||||
public static void plotGlWait(double ms, int calls) {
|
||||
if (!isEnabled()) return;
|
||||
plotGlWaitMs().setValue(ms);
|
||||
plotGlWaitCalls().setValue(calls);
|
||||
}
|
||||
|
||||
public static void plotUiBatch(int draws, int vertices) {
|
||||
if (!isEnabled()) return;
|
||||
plotUiBatchDraws().setValue(draws);
|
||||
plotUiBatchVertices().setValue(vertices);
|
||||
}
|
||||
|
||||
private static void ensureLoaded() {
|
||||
if (loadAttempted) {
|
||||
return;
|
||||
}
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (loadAttempted) {
|
||||
return;
|
||||
}
|
||||
loadAttempted = true;
|
||||
try {
|
||||
TracyClient.load();
|
||||
TracyClient.reportAppInfo("LoVisual render profiler");
|
||||
available = TracyClient.isAvailable();
|
||||
if (available) {
|
||||
ProfilerLog.info("Tracy client loaded");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
available = false;
|
||||
ProfilerLog.warn("Tracy unavailable: %s", t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ensureThreadNamed() {
|
||||
if (Boolean.TRUE.equals(THREAD_NAMED.get())) {
|
||||
return;
|
||||
}
|
||||
TracyClient.setThreadName(Thread.currentThread().getName(), 0);
|
||||
THREAD_NAMED.set(Boolean.TRUE);
|
||||
}
|
||||
|
||||
private static Plot plotUiFrameMs() {
|
||||
Plot plot = uiFrameMsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiFrameMsPlot == null) {
|
||||
uiFrameMsPlot = TracyClient.createPlot("render.ui.ms");
|
||||
}
|
||||
return uiFrameMsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotUiNodeCount() {
|
||||
Plot plot = uiNodeCountPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiNodeCountPlot == null) {
|
||||
uiNodeCountPlot = TracyClient.createPlot("render.ui.nodes");
|
||||
}
|
||||
return uiNodeCountPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotWorldFrameMs() {
|
||||
Plot plot = worldFrameMsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (worldFrameMsPlot == null) {
|
||||
worldFrameMsPlot = TracyClient.createPlot("render.world.ms");
|
||||
}
|
||||
return worldFrameMsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotWorldNodeCount() {
|
||||
Plot plot = worldNodeCountPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (worldNodeCountPlot == null) {
|
||||
worldNodeCountPlot = TracyClient.createPlot("render.world.nodes");
|
||||
}
|
||||
return worldNodeCountPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotGlWaitMs() {
|
||||
Plot plot = glWaitMsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (glWaitMsPlot == null) {
|
||||
glWaitMsPlot = TracyClient.createPlot("render.gl_wait.ms");
|
||||
}
|
||||
return glWaitMsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotGlWaitCalls() {
|
||||
Plot plot = glWaitCallsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (glWaitCallsPlot == null) {
|
||||
glWaitCallsPlot = TracyClient.createPlot("render.gl_wait.calls");
|
||||
}
|
||||
return glWaitCallsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotUiBatchDraws() {
|
||||
Plot plot = uiBatchDrawsPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiBatchDrawsPlot == null) {
|
||||
uiBatchDrawsPlot = TracyClient.createPlot("render.ui_batch.draws");
|
||||
}
|
||||
return uiBatchDrawsPlot;
|
||||
}
|
||||
}
|
||||
|
||||
private static Plot plotUiBatchVertices() {
|
||||
Plot plot = uiBatchVerticesPlot;
|
||||
if (plot != null) return plot;
|
||||
synchronized (DevTracyProfiler.class) {
|
||||
if (uiBatchVerticesPlot == null) {
|
||||
uiBatchVerticesPlot = TracyClient.createPlot("render.ui_batch.vertices");
|
||||
}
|
||||
return uiBatchVerticesPlot;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Scope implements AutoCloseable {
|
||||
private final Zone zone;
|
||||
|
||||
private Scope(Zone zone) {
|
||||
this.zone = zone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (zone != null) {
|
||||
zone.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
16
mod/src/dev/resources/lovisual-dev.mixins.json
Normal file
16
mod/src/dev/resources/lovisual-dev.mixins.json
Normal 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
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue